blob: dd1db5745741ad5fc20ad34324b484f9e884e0c4 [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;
Wei Fangc2a97372016-10-07 17:01:52 -07002214 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2215
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002216 index = *ppos >> PAGE_SHIFT;
2217 prev_index = ra->prev_pos >> PAGE_SHIFT;
2218 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2219 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2220 offset = *ppos & ~PAGE_MASK;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002221
Jens Axboe13bd6912020-10-17 08:31:29 -06002222 /*
2223 * If we've already successfully copied some data, then we
2224 * can no longer safely return -EIOCBQUEUED. Hence mark
2225 * an async read NOWAIT at that point.
2226 */
2227 if (written && (iocb->ki_flags & IOCB_WAITQ))
2228 iocb->ki_flags |= IOCB_NOWAIT;
2229
Linus Torvalds1da177e2005-04-16 15:20:36 -07002230 for (;;) {
2231 struct page *page;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002232 pgoff_t end_index;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002233 loff_t isize;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002234 unsigned long nr, ret;
2235
Linus Torvalds1da177e2005-04-16 15:20:36 -07002236 cond_resched();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002237find_page:
Michal Hocko5abf1862017-02-03 13:13:29 -08002238 if (fatal_signal_pending(current)) {
2239 error = -EINTR;
2240 goto out;
2241 }
2242
Linus Torvalds1da177e2005-04-16 15:20:36 -07002243 page = find_get_page(mapping, index);
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002244 if (!page) {
Linus Torvaldscdc8fcb2020-08-03 13:01:22 -07002245 if (iocb->ki_flags & IOCB_NOIO)
Milosz Tanski3239d832017-08-29 16:13:19 +02002246 goto would_block;
Rusty Russellcf914a72007-07-19 01:48:08 -07002247 page_cache_sync_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002248 ra, filp,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002249 index, last_index - index);
2250 page = find_get_page(mapping, index);
2251 if (unlikely(page == NULL))
2252 goto no_cached_page;
2253 }
2254 if (PageReadahead(page)) {
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002255 if (iocb->ki_flags & IOCB_NOIO) {
2256 put_page(page);
2257 goto out;
2258 }
Rusty Russellcf914a72007-07-19 01:48:08 -07002259 page_cache_async_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002260 ra, filp, page,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002261 index, last_index - index);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002262 }
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002263 if (!PageUptodate(page)) {
Mel Gormanebded022016-03-15 14:55:39 -07002264 /*
2265 * See comment in do_read_cache_page on why
2266 * wait_on_page_locked is used to avoid unnecessarily
2267 * serialisations and why it's safe.
2268 */
Jens Axboe1a0a7852020-05-22 09:18:38 -06002269 if (iocb->ki_flags & IOCB_WAITQ) {
2270 if (written) {
2271 put_page(page);
2272 goto out;
2273 }
2274 error = wait_on_page_locked_async(page,
2275 iocb->ki_waitq);
2276 } else {
2277 if (iocb->ki_flags & IOCB_NOWAIT) {
2278 put_page(page);
2279 goto would_block;
2280 }
2281 error = wait_on_page_locked_killable(page);
2282 }
Bart Van Asschec4b209a2016-10-07 16:58:33 -07002283 if (unlikely(error))
2284 goto readpage_error;
Mel Gormanebded022016-03-15 14:55:39 -07002285 if (PageUptodate(page))
2286 goto page_ok;
2287
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002288 if (inode->i_blkbits == PAGE_SHIFT ||
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002289 !mapping->a_ops->is_partially_uptodate)
2290 goto page_not_up_to_date;
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002291 /* pipes can't handle partially uptodate pages */
David Howells00e23702018-10-22 13:07:28 +01002292 if (unlikely(iov_iter_is_pipe(iter)))
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002293 goto page_not_up_to_date;
Nick Piggin529ae9a2008-08-02 12:01:03 +02002294 if (!trylock_page(page))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002295 goto page_not_up_to_date;
Dave Hansen8d056cb2010-11-11 14:05:15 -08002296 /* Did it get truncated before we got the lock? */
2297 if (!page->mapping)
2298 goto page_not_up_to_date_locked;
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002299 if (!mapping->a_ops->is_partially_uptodate(page,
Al Viro6e58e792014-02-03 17:07:03 -05002300 offset, iter->count))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002301 goto page_not_up_to_date_locked;
2302 unlock_page(page);
2303 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002304page_ok:
NeilBrowna32ea1e2007-07-17 04:03:04 -07002305 /*
2306 * i_size must be checked after we know the page is Uptodate.
2307 *
2308 * Checking i_size after the check allows us to calculate
2309 * the correct value for "nr", which means the zero-filled
2310 * part of the page is not copied back to userspace (unless
2311 * another truncate extends the file - this is desired though).
2312 */
2313
2314 isize = i_size_read(inode);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002315 end_index = (isize - 1) >> PAGE_SHIFT;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002316 if (unlikely(!isize || index > end_index)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002317 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002318 goto out;
2319 }
2320
2321 /* nr is the maximum number of bytes to copy from this page */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002322 nr = PAGE_SIZE;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002323 if (index == end_index) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002324 nr = ((isize - 1) & ~PAGE_MASK) + 1;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002325 if (nr <= offset) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002326 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002327 goto out;
2328 }
2329 }
2330 nr = nr - offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002331
2332 /* If users can be writing to this page using arbitrary
2333 * virtual addresses, take care about potential aliasing
2334 * before reading the page on the kernel side.
2335 */
2336 if (mapping_writably_mapped(mapping))
2337 flush_dcache_page(page);
2338
2339 /*
Jan Karaec0f1632007-05-06 14:49:25 -07002340 * When a sequential read accesses a page several times,
2341 * only mark it as accessed the first time.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002342 */
Jan Karaec0f1632007-05-06 14:49:25 -07002343 if (prev_index != index || offset != prev_offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002344 mark_page_accessed(page);
2345 prev_index = index;
2346
2347 /*
2348 * Ok, we have the page, and it's up-to-date, so
2349 * now we can copy it to user space...
Linus Torvalds1da177e2005-04-16 15:20:36 -07002350 */
Al Viro6e58e792014-02-03 17:07:03 -05002351
2352 ret = copy_page_to_iter(page, offset, nr, iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002353 offset += ret;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002354 index += offset >> PAGE_SHIFT;
2355 offset &= ~PAGE_MASK;
Jan Kara6ce745e2007-05-06 14:49:26 -07002356 prev_offset = offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002357
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002358 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002359 written += ret;
2360 if (!iov_iter_count(iter))
2361 goto out;
2362 if (ret < nr) {
2363 error = -EFAULT;
2364 goto out;
2365 }
2366 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002367
2368page_not_up_to_date:
2369 /* Get exclusive access to the page ... */
Jens Axboe0abed7c2020-11-16 13:36:24 -07002370 if (iocb->ki_flags & IOCB_WAITQ) {
2371 if (written) {
2372 put_page(page);
2373 goto out;
2374 }
Jens Axboe1a0a7852020-05-22 09:18:38 -06002375 error = lock_page_async(page, iocb->ki_waitq);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002376 } else {
Jens Axboe1a0a7852020-05-22 09:18:38 -06002377 error = lock_page_killable(page);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002378 }
Oleg Nesterov85462322008-06-08 21:20:43 +04002379 if (unlikely(error))
2380 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002381
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002382page_not_up_to_date_locked:
Nick Pigginda6052f2006-09-25 23:31:35 -07002383 /* Did it get truncated before we got the lock? */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002384 if (!page->mapping) {
2385 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002386 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002387 continue;
2388 }
2389
2390 /* Did somebody else fill it already? */
2391 if (PageUptodate(page)) {
2392 unlock_page(page);
2393 goto page_ok;
2394 }
2395
2396readpage:
Linus Torvaldscdc8fcb2020-08-03 13:01:22 -07002397 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT)) {
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002398 unlock_page(page);
2399 put_page(page);
2400 goto would_block;
2401 }
Jeff Moyer91803b42010-05-26 11:49:40 -04002402 /*
2403 * A previous I/O error may have been due to temporary
2404 * failures, eg. multipath errors.
2405 * PG_error will be set again if readpage fails.
2406 */
2407 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002408 /* Start the actual read. The read will unlock the page. */
2409 error = mapping->a_ops->readpage(filp, page);
2410
Zach Brown994fc28c2005-12-15 14:28:17 -08002411 if (unlikely(error)) {
2412 if (error == AOP_TRUNCATED_PAGE) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002413 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002414 error = 0;
Zach Brown994fc28c2005-12-15 14:28:17 -08002415 goto find_page;
2416 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002417 goto readpage_error;
Zach Brown994fc28c2005-12-15 14:28:17 -08002418 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002419
2420 if (!PageUptodate(page)) {
Jens Axboe0abed7c2020-11-16 13:36:24 -07002421 if (iocb->ki_flags & IOCB_WAITQ) {
2422 if (written) {
2423 put_page(page);
2424 goto out;
2425 }
Hao Xuc8d317a2020-09-29 20:00:45 +08002426 error = lock_page_async(page, iocb->ki_waitq);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002427 } else {
Hao Xuc8d317a2020-09-29 20:00:45 +08002428 error = lock_page_killable(page);
Jens Axboe0abed7c2020-11-16 13:36:24 -07002429 }
Hao Xuc8d317a2020-09-29 20:00:45 +08002430
Oleg Nesterov85462322008-06-08 21:20:43 +04002431 if (unlikely(error))
2432 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002433 if (!PageUptodate(page)) {
2434 if (page->mapping == NULL) {
2435 /*
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01002436 * invalidate_mapping_pages got it
Linus Torvalds1da177e2005-04-16 15:20:36 -07002437 */
2438 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002439 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002440 goto find_page;
2441 }
2442 unlock_page(page);
Souptick Joarder0f8e2db2020-04-01 21:04:50 -07002443 shrink_readahead_size_eio(ra);
Oleg Nesterov85462322008-06-08 21:20:43 +04002444 error = -EIO;
2445 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446 }
2447 unlock_page(page);
2448 }
2449
Linus Torvalds1da177e2005-04-16 15:20:36 -07002450 goto page_ok;
2451
2452readpage_error:
2453 /* UHHUH! A synchronous read error occurred. Report it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002454 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002455 goto out;
2456
2457no_cached_page:
2458 /*
2459 * Ok, it wasn't cached, so we need to create a new
2460 * page..
2461 */
Mel Gorman453f85d2017-11-15 17:38:03 -08002462 page = page_cache_alloc(mapping);
Nick Piggineb2be182007-10-16 01:24:57 -07002463 if (!page) {
Al Viro6e58e792014-02-03 17:07:03 -05002464 error = -ENOMEM;
Nick Piggineb2be182007-10-16 01:24:57 -07002465 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002466 }
Michal Hocko6afdb852015-06-24 16:58:06 -07002467 error = add_to_page_cache_lru(page, mapping, index,
Michal Hockoc62d2552015-11-06 16:28:49 -08002468 mapping_gfp_constraint(mapping, GFP_KERNEL));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002469 if (error) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002470 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002471 if (error == -EEXIST) {
2472 error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002473 goto find_page;
Al Viro6e58e792014-02-03 17:07:03 -05002474 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002475 goto out;
2476 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002477 goto readpage;
2478 }
2479
Milosz Tanski3239d832017-08-29 16:13:19 +02002480would_block:
2481 error = -EAGAIN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002482out:
Fengguang Wu7ff81072007-10-16 01:24:35 -07002483 ra->prev_pos = prev_index;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002484 ra->prev_pos <<= PAGE_SHIFT;
Fengguang Wu7ff81072007-10-16 01:24:35 -07002485 ra->prev_pos |= prev_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002486
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002487 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002488 file_accessed(filp);
Al Viro6e58e792014-02-03 17:07:03 -05002489 return written ? written : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002490}
Goldwyn Rodriguesd85dc2e2019-08-30 12:09:24 -05002491EXPORT_SYMBOL_GPL(generic_file_buffered_read);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002492
Randy Dunlap485bb992006-06-23 02:03:49 -07002493/**
Al Viro6abd2322014-04-04 14:20:57 -04002494 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002495 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002496 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002497 *
Al Viro6abd2322014-04-04 14:20:57 -04002498 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002499 * that can use the page cache directly.
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002500 *
2501 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2502 * be returned when no data can be read without waiting for I/O requests
2503 * to complete; it doesn't prevent readahead.
2504 *
2505 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2506 * requests shall be made for the read or for readahead. When no data
2507 * can be read, -EAGAIN shall be returned. When readahead would be
2508 * triggered, a partial, possibly empty read shall be returned.
2509 *
Mike Rapoporta862f682019-03-05 15:48:42 -08002510 * Return:
2511 * * number of bytes copied, even for partial reads
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002512 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002513 */
2514ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002515generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002516{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002517 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002518 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002519
2520 if (!count)
2521 goto out; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002522
Al Viro2ba48ce2015-04-09 13:52:01 -04002523 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002524 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002525 struct address_space *mapping = file->f_mapping;
2526 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002527 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002528
Linus Torvalds1da177e2005-04-16 15:20:36 -07002529 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002530 if (iocb->ki_flags & IOCB_NOWAIT) {
2531 if (filemap_range_has_page(mapping, iocb->ki_pos,
2532 iocb->ki_pos + count - 1))
2533 return -EAGAIN;
2534 } else {
2535 retval = filemap_write_and_wait_range(mapping,
2536 iocb->ki_pos,
2537 iocb->ki_pos + count - 1);
2538 if (retval < 0)
2539 goto out;
2540 }
Al Viroed978a82014-03-05 22:53:04 -05002541
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002542 file_accessed(file);
2543
Al Viro5ecda132017-04-13 14:13:36 -04002544 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002545 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002546 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002547 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002548 }
Al Viro5b47d592017-05-08 13:54:47 -04002549 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002550
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002551 /*
2552 * Btrfs can have a short DIO read if we encounter
2553 * compressed extents, so if there was an error, or if
2554 * we've already read everything we wanted to, or if
2555 * there was a short read because we hit EOF, go ahead
2556 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002557 * the rest of the read. Buffered reads will not work for
2558 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002559 */
Al Viro5ecda132017-04-13 14:13:36 -04002560 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002561 IS_DAX(inode))
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002562 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002563 }
2564
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002565 retval = generic_file_buffered_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002566out:
2567 return retval;
2568}
Al Viroed978a82014-03-05 22:53:04 -05002569EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002570
Linus Torvalds1da177e2005-04-16 15:20:36 -07002571#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002572#define MMAP_LOTSAMISS (100)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002573/*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002574 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002575 * @vmf - the vm_fault for this fault.
2576 * @page - the page to lock.
2577 * @fpin - the pointer to the file we may pin (or is already pinned).
2578 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002579 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002580 * It differs in that it actually returns the page locked if it returns 1 and 0
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002581 * 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 -07002582 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002583 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002584static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2585 struct file **fpin)
2586{
2587 if (trylock_page(page))
2588 return 1;
2589
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002590 /*
2591 * NOTE! This will make us return with VM_FAULT_RETRY, but with
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002592 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002593 * is supposed to work. We have way too many special cases..
2594 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002595 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2596 return 0;
2597
2598 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2599 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2600 if (__lock_page_killable(page)) {
2601 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002602 * We didn't have the right flags to drop the mmap_lock,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002603 * but all fault_handlers only check for fatal signals
2604 * if we return VM_FAULT_RETRY, so we need to drop the
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002605 * mmap_lock here and return 0 if we don't have a fpin.
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002606 */
2607 if (*fpin == NULL)
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002608 mmap_read_unlock(vmf->vma->vm_mm);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002609 return 0;
2610 }
2611 } else
2612 __lock_page(page);
2613 return 1;
2614}
2615
2616
2617/*
2618 * Synchronous readahead happens when we don't even find a page in the page
2619 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2620 * to drop the mmap sem we return the file that was pinned in order for us to do
2621 * that. If we didn't pin a file then we return NULL. The file that is
2622 * returned needs to be fput()'ed when we're done with it.
2623 */
2624static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002625{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002626 struct file *file = vmf->vma->vm_file;
2627 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002628 struct address_space *mapping = file->f_mapping;
David Howellsdb660d42020-10-15 20:06:31 -07002629 DEFINE_READAHEAD(ractl, file, mapping, vmf->pgoff);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002630 struct file *fpin = NULL;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002631 unsigned int mmap_miss;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002632
2633 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002634 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002635 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002636 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002637 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002638
Josef Bacik2a1180f2019-03-13 11:44:18 -07002639 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002640 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
David Howellsdb660d42020-10-15 20:06:31 -07002641 page_cache_sync_ra(&ractl, ra, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002642 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002643 }
2644
Andi Kleen207d04b2011-05-24 17:12:29 -07002645 /* Avoid banging the cache line if not needed */
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002646 mmap_miss = READ_ONCE(ra->mmap_miss);
2647 if (mmap_miss < MMAP_LOTSAMISS * 10)
2648 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002649
2650 /*
2651 * Do we miss much more than hit in this file? If so,
2652 * stop bothering with read-ahead. It will only hurt.
2653 */
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002654 if (mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002655 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002656
Wu Fengguangd30a1102009-06-16 15:31:30 -07002657 /*
2658 * mmap read-around
2659 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002660 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
David Howellsdb660d42020-10-15 20:06:31 -07002661 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002662 ra->size = ra->ra_pages;
2663 ra->async_size = ra->ra_pages / 4;
David Howellsdb660d42020-10-15 20:06:31 -07002664 ractl._index = ra->start;
2665 do_page_cache_ra(&ractl, ra->size, ra->async_size);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002666 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002667}
2668
2669/*
2670 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002671 * so we want to possibly extend the readahead further. We return the file that
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002672 * was pinned if we have to drop the mmap_lock in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002673 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002674static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2675 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002676{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002677 struct file *file = vmf->vma->vm_file;
2678 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002679 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002680 struct file *fpin = NULL;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002681 unsigned int mmap_miss;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002682 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002683
2684 /* If we don't want any read-ahead, don't bother */
Jan Kara5c72fee2020-04-01 21:04:40 -07002685 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002686 return fpin;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002687 mmap_miss = READ_ONCE(ra->mmap_miss);
2688 if (mmap_miss)
2689 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002690 if (PageReadahead(page)) {
2691 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002692 page_cache_async_readahead(mapping, ra, file,
2693 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002694 }
2695 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002696}
2697
Randy Dunlap485bb992006-06-23 02:03:49 -07002698/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002699 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002700 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002701 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002702 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002703 * mapped memory region to read in file data during a page fault.
2704 *
2705 * The goto's are kind of ugly, but this streamlines the normal case of having
2706 * it in the page cache, and handles the special cases reasonably without
2707 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002708 *
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002709 * If FAULT_FLAG_SPECULATIVE is set, this function runs with elevated vma
2710 * refcount and with mmap lock not held.
2711 * Otherwise, vma->vm_mm->mmap_lock must be held on entry.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002712 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002713 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
Yang Shia4985832019-07-11 20:55:29 -07002714 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002715 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002716 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002717 * has not been released.
2718 *
2719 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002720 *
2721 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002722 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002723vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002724{
2725 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002726 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002727 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002728 struct address_space *mapping = file->f_mapping;
2729 struct file_ra_state *ra = &file->f_ra;
2730 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002731 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002732 pgoff_t max_off;
Liangliang Lida33f6f2021-06-08 10:00:02 +08002733 struct page *page = NULL;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002734 vm_fault_t ret = 0;
Liangliang Lida33f6f2021-06-08 10:00:02 +08002735 bool retry = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002736
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002737 if (vmf->flags & FAULT_FLAG_SPECULATIVE) {
2738 page = find_get_page(mapping, offset);
Patrick Daly1d052132022-10-10 19:25:27 -07002739 if (unlikely(!page))
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002740 return VM_FAULT_RETRY;
2741
Patrick Daly1d052132022-10-10 19:25:27 -07002742 if (unlikely(PageReadahead(page)))
2743 goto page_put;
2744
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002745 if (!trylock_page(page))
Patrick Daly1d052132022-10-10 19:25:27 -07002746 goto page_put;
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002747
2748 if (unlikely(compound_head(page)->mapping != mapping))
2749 goto page_unlock;
2750 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
2751 if (unlikely(!PageUptodate(page)))
2752 goto page_unlock;
2753
2754 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2755 if (unlikely(offset >= max_off))
2756 goto page_unlock;
2757
2758 /*
2759 * Update readahead mmap_miss statistic.
2760 *
2761 * Note that we are not sure if finish_fault() will
2762 * manage to complete the transaction. If it fails,
2763 * we'll come back to filemap_fault() non-speculative
2764 * case which will update mmap_miss a second time.
2765 * This is not ideal, we would prefer to guarantee the
2766 * update will happen exactly once.
2767 */
2768 if (!(vmf->vma->vm_flags & VM_RAND_READ) && ra->ra_pages) {
2769 unsigned int mmap_miss = READ_ONCE(ra->mmap_miss);
2770 if (mmap_miss)
2771 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
2772 }
2773
2774 vmf->page = page;
2775 return VM_FAULT_LOCKED;
2776page_unlock:
2777 unlock_page(page);
Patrick Daly1d052132022-10-10 19:25:27 -07002778page_put:
2779 put_page(page);
Michel Lespinasse59d4d122021-04-29 10:28:25 -07002780 return VM_FAULT_RETRY;
2781 }
2782
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002783 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2784 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002785 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002786
Liangliang Lida33f6f2021-06-08 10:00:02 +08002787 trace_android_vh_filemap_fault_get_page(vmf, &page, &retry);
2788 if (unlikely(retry))
2789 goto out_retry;
2790 if (unlikely(page))
2791 goto page_ok;
2792
Linus Torvalds1da177e2005-04-16 15:20:36 -07002793 /*
Johannes Weiner49426422013-10-16 13:46:59 -07002794 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07002795 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002796 page = find_get_page(mapping, offset);
Shaohua Li45cac652012-10-08 16:32:19 -07002797 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002798 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002799 * We found the page, so try async readahead before
2800 * waiting for the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002801 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002802 fpin = do_async_mmap_readahead(vmf, page);
Shaohua Li45cac652012-10-08 16:32:19 -07002803 } else if (!page) {
Linus Torvaldsef00e082009-06-16 15:31:25 -07002804 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002805 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07002806 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002807 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002808 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002809retry_find:
Josef Bacika75d4c32019-03-13 11:44:14 -07002810 page = pagecache_get_page(mapping, offset,
2811 FGP_CREAT|FGP_FOR_MMAP,
2812 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002813 if (!page) {
2814 if (fpin)
2815 goto out_retry;
Matthew Wilcox (Oracle)e520e932020-04-01 21:04:53 -07002816 return VM_FAULT_OOM;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002817 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002818 }
2819
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002820 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2821 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07002822
2823 /* Did it get truncated? */
Song Liu585e5a72019-09-23 15:37:44 -07002824 if (unlikely(compound_head(page)->mapping != mapping)) {
Michel Lespinasseb522c942010-10-26 14:21:56 -07002825 unlock_page(page);
2826 put_page(page);
2827 goto retry_find;
2828 }
Song Liu520e5ba2019-09-23 15:37:50 -07002829 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07002830
Linus Torvalds1da177e2005-04-16 15:20:36 -07002831 /*
Nick Piggind00806b2007-07-19 01:46:57 -07002832 * We have a locked page in the page cache, now we need to check
2833 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002834 */
Nick Piggind00806b2007-07-19 01:46:57 -07002835 if (unlikely(!PageUptodate(page)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002836 goto page_not_uptodate;
2837
Linus Torvaldsef00e082009-06-16 15:31:25 -07002838 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002839 * We've made it this far and we had to drop our mmap_lock, now is the
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002840 * time to return to the upper layer and have it re-find the vma and
2841 * redo the fault.
2842 */
2843 if (fpin) {
2844 unlock_page(page);
2845 goto out_retry;
2846 }
2847
Liangliang Lida33f6f2021-06-08 10:00:02 +08002848page_ok:
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002849 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002850 * Found the page and have a reference on it.
2851 * We must recheck i_size under page lock.
2852 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002853 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2854 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07002855 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002856 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07002857 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07002858 }
2859
Nick Piggind0217ac2007-07-19 01:47:03 -07002860 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07002861 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002862
Linus Torvalds1da177e2005-04-16 15:20:36 -07002863page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002864 /*
2865 * Umm, take care of errors if the page isn't up-to-date.
2866 * Try to re-read it _once_. We do this synchronously,
2867 * because there really aren't any performance issues here
2868 * and we need to check for errors.
2869 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002870 ClearPageError(page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002871 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Zach Brown994fc28c2005-12-15 14:28:17 -08002872 error = mapping->a_ops->readpage(file, page);
Miklos Szeredi3ef0f722008-05-14 16:05:37 -07002873 if (!error) {
2874 wait_on_page_locked(page);
2875 if (!PageUptodate(page))
2876 error = -EIO;
2877 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002878 if (fpin)
2879 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002880 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07002881
2882 if (!error || error == AOP_TRUNCATED_PAGE)
2883 goto retry_find;
2884
Souptick Joarder0f8e2db2020-04-01 21:04:50 -07002885 shrink_readahead_size_eio(ra);
Nick Piggind0217ac2007-07-19 01:47:03 -07002886 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002887
2888out_retry:
2889 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002890 * We dropped the mmap_lock, we need to return to the fault handler to
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002891 * re-find the vma and come back and find our hopefully still populated
2892 * page.
2893 */
Liangliang Lida33f6f2021-06-08 10:00:02 +08002894 if (page) {
2895 trace_android_vh_filemap_fault_cache_page(vmf, page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002896 put_page(page);
Liangliang Lida33f6f2021-06-08 10:00:02 +08002897 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002898 if (fpin)
2899 fput(fpin);
2900 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07002901}
2902EXPORT_SYMBOL(filemap_fault);
2903
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03002904static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002905{
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03002906 struct mm_struct *mm = vmf->vma->vm_mm;
2907
2908 /* Huge page is mapped? No need to proceed. */
2909 if (pmd_trans_huge(*vmf->pmd)) {
2910 unlock_page(page);
2911 put_page(page);
2912 return true;
2913 }
2914
2915 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
2916 vm_fault_t ret = do_set_pmd(vmf, page);
2917 if (!ret) {
2918 /* The page is mapped successfully, reference consumed. */
2919 unlock_page(page);
2920 return true;
2921 }
2922 }
2923
2924 if (pmd_none(*vmf->pmd)) {
2925 vmf->ptl = pmd_lock(mm, vmf->pmd);
2926 if (likely(pmd_none(*vmf->pmd))) {
2927 mm_inc_nr_ptes(mm);
2928 pmd_populate(mm, vmf->pmd, vmf->prealloc_pte);
2929 vmf->prealloc_pte = NULL;
2930 }
2931 spin_unlock(vmf->ptl);
2932 }
2933
2934 /* See comment in handle_pte_fault() */
2935 if (pmd_devmap_trans_unstable(vmf->pmd)) {
2936 unlock_page(page);
2937 put_page(page);
2938 return true;
2939 }
2940
2941 return false;
2942}
2943
2944static struct page *next_uptodate_page(struct page *page,
2945 struct address_space *mapping,
2946 struct xa_state *xas, pgoff_t end_pgoff)
2947{
2948 unsigned long max_idx;
2949
2950 do {
2951 if (!page)
2952 return NULL;
2953 if (xas_retry(xas, page))
2954 continue;
2955 if (xa_is_value(page))
2956 continue;
2957 if (PageLocked(page))
2958 continue;
2959 if (!page_cache_get_speculative(page))
2960 continue;
2961 /* Has the page moved or been split? */
2962 if (unlikely(page != xas_reload(xas)))
2963 goto skip;
2964 if (!PageUptodate(page) || PageReadahead(page))
2965 goto skip;
2966 if (PageHWPoison(page))
2967 goto skip;
2968 if (!trylock_page(page))
2969 goto skip;
2970 if (page->mapping != mapping)
2971 goto unlock;
2972 if (!PageUptodate(page))
2973 goto unlock;
2974 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2975 if (xas->xa_index >= max_idx)
2976 goto unlock;
2977 return page;
2978unlock:
2979 unlock_page(page);
2980skip:
2981 put_page(page);
2982 } while ((page = xas_next_entry(xas, end_pgoff)) != NULL);
2983
2984 return NULL;
2985}
2986
2987static inline struct page *first_map_page(struct address_space *mapping,
2988 struct xa_state *xas,
2989 pgoff_t end_pgoff)
2990{
2991 return next_uptodate_page(xas_find(xas, end_pgoff),
2992 mapping, xas, end_pgoff);
2993}
2994
2995static inline struct page *next_map_page(struct address_space *mapping,
2996 struct xa_state *xas,
2997 pgoff_t end_pgoff)
2998{
2999 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3000 mapping, xas, end_pgoff);
3001}
3002
Vinayak Menon35eacb52021-03-18 15:20:17 +05303003#ifdef CONFIG_SPECULATIVE_PAGE_FAULT
3004bool filemap_allow_speculation(void)
3005{
3006 return true;
3007}
3008EXPORT_SYMBOL_GPL(filemap_allow_speculation);
3009#endif
3010
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003011vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3012 pgoff_t start_pgoff, pgoff_t end_pgoff)
3013{
3014 struct vm_area_struct *vma = vmf->vma;
3015 struct file *file = vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003016 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07003017 pgoff_t last_pgoff = start_pgoff;
Will Deacondb6cf102021-01-14 15:24:19 +00003018 unsigned long addr;
Matthew Wilcox070e8072018-05-17 00:08:30 -04003019 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003020 struct page *head, *page;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003021 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
Suren Baghdasaryan2bb39b92022-11-18 15:36:13 -08003022 vm_fault_t ret = (vmf->flags & FAULT_FLAG_SPECULATIVE) ?
3023 VM_FAULT_RETRY : 0;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003024
3025 rcu_read_lock();
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003026 head = first_map_page(mapping, &xas, end_pgoff);
3027 if (!head)
3028 goto out;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003029
Suren Baghdasaryan2bb39b92022-11-18 15:36:13 -08003030 if (!(vmf->flags & FAULT_FLAG_SPECULATIVE) &&
3031 filemap_map_pmd(vmf, head)) {
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003032 ret = VM_FAULT_NOPAGE;
3033 goto out;
3034 }
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003035
Will Deacondb6cf102021-01-14 15:24:19 +00003036 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
Vinayak Menon35eacb52021-03-18 15:20:17 +05303037 if (!pte_map_lock_addr(vmf, addr)) {
Vinayak Menon4d9d8662021-09-13 16:27:10 +05303038 unlock_page(head);
3039 put_page(head);
Vinayak Menon35eacb52021-03-18 15:20:17 +05303040 goto out;
3041 }
3042
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003043 do {
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003044 page = find_subpage(head, xas.xa_index);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003045 if (PageHWPoison(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003046 goto unlock;
3047
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003048 if (mmap_miss > 0)
3049 mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07003050
Will Deacondb6cf102021-01-14 15:24:19 +00003051 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003052 vmf->pte += xas.xa_index - last_pgoff;
Matthew Wilcox070e8072018-05-17 00:08:30 -04003053 last_pgoff = xas.xa_index;
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003054
3055 if (!pte_none(*vmf->pte))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07003056 goto unlock;
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003057
Will Deaconef3b7322020-11-24 18:48:26 +00003058 /* We're about to handle the fault */
Will Deacondb6cf102021-01-14 15:24:19 +00003059 if (vmf->address == addr)
Will Deaconef3b7322020-11-24 18:48:26 +00003060 ret = VM_FAULT_NOPAGE;
Will Deaconef3b7322020-11-24 18:48:26 +00003061
Will Deacondb6cf102021-01-14 15:24:19 +00003062 do_set_pte(vmf, page, addr);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003063 /* no need to invalidate: a not-present page won't be cached */
Will Deacondb6cf102021-01-14 15:24:19 +00003064 update_mmu_cache(vma, addr, vmf->pte);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003065 unlock_page(head);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003066 continue;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003067unlock:
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003068 unlock_page(head);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003069 put_page(head);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003070 } while ((head = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3071 pte_unmap_unlock(vmf->pte, vmf->ptl);
3072out:
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003073 rcu_read_unlock();
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003074 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
Kirill A. Shutemov0aa300a2020-12-19 15:19:23 +03003075 return ret;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003076}
3077EXPORT_SYMBOL(filemap_map_pages);
3078
Souptick Joarder2bcd6452018-06-07 17:08:00 -07003079vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02003080{
3081 struct page *page = vmf->page;
Dave Jiang11bac802017-02-24 14:56:41 -08003082 struct inode *inode = file_inode(vmf->vma->vm_file);
Souptick Joarder2bcd6452018-06-07 17:08:00 -07003083 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02003084
Jan Kara14da9202012-06-12 16:20:37 +02003085 sb_start_pagefault(inode->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08003086 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003087 lock_page(page);
3088 if (page->mapping != inode->i_mapping) {
3089 unlock_page(page);
3090 ret = VM_FAULT_NOPAGE;
3091 goto out;
3092 }
Jan Kara14da9202012-06-12 16:20:37 +02003093 /*
3094 * We mark the page dirty already here so that when freeze is in
3095 * progress, we are guaranteed that writeback during freezing will
3096 * see the dirty page and writeprotect it again.
3097 */
3098 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08003099 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003100out:
Jan Kara14da9202012-06-12 16:20:37 +02003101 sb_end_pagefault(inode->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003102 return ret;
3103}
Jan Kara4fcf1c62012-06-12 16:20:29 +02003104
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04003105const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07003106 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003107 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02003108 .page_mkwrite = filemap_page_mkwrite,
Vinayak Menon35eacb52021-03-18 15:20:17 +05303109#ifdef CONFIG_SPECULATIVE_PAGE_FAULT
3110 .allow_speculation = filemap_allow_speculation,
3111#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -07003112};
3113
3114/* This is used for a general mmap of a disk file */
3115
3116int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
3117{
3118 struct address_space *mapping = file->f_mapping;
3119
3120 if (!mapping->a_ops->readpage)
3121 return -ENOEXEC;
3122 file_accessed(file);
3123 vma->vm_ops = &generic_file_vm_ops;
3124 return 0;
3125}
Linus Torvalds1da177e2005-04-16 15:20:36 -07003126
3127/*
3128 * This is for filesystems which do not implement ->writepage.
3129 */
3130int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3131{
3132 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3133 return -EINVAL;
3134 return generic_file_mmap(file, vma);
3135}
3136#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07003137vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann45397222018-04-13 15:35:27 -07003138{
Souptick Joarder4b96a372018-10-26 15:04:03 -07003139 return VM_FAULT_SIGBUS;
Arnd Bergmann45397222018-04-13 15:35:27 -07003140}
Linus Torvalds1da177e2005-04-16 15:20:36 -07003141int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
3142{
3143 return -ENOSYS;
3144}
3145int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
3146{
3147 return -ENOSYS;
3148}
3149#endif /* CONFIG_MMU */
3150
Arnd Bergmann45397222018-04-13 15:35:27 -07003151EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003152EXPORT_SYMBOL(generic_file_mmap);
3153EXPORT_SYMBOL(generic_file_readonly_mmap);
3154
Sasha Levin67f9fd92014-04-03 14:48:18 -07003155static struct page *wait_on_page_read(struct page *page)
3156{
3157 if (!IS_ERR(page)) {
3158 wait_on_page_locked(page);
3159 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003160 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07003161 page = ERR_PTR(-EIO);
3162 }
3163 }
3164 return page;
3165}
3166
Mel Gorman32b63522016-03-15 14:55:36 -07003167static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07003168 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003169 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003170 void *data,
3171 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003172{
Nick Piggineb2be182007-10-16 01:24:57 -07003173 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003174 int err;
3175repeat:
3176 page = find_get_page(mapping, index);
3177 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08003178 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07003179 if (!page)
3180 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06003181 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07003182 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003183 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07003184 if (err == -EEXIST)
3185 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05003186 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003187 return ERR_PTR(err);
3188 }
Mel Gorman32b63522016-03-15 14:55:36 -07003189
3190filler:
Christoph Hellwig6c45b452019-07-11 20:55:20 -07003191 if (filler)
3192 err = filler(data, page);
3193 else
3194 err = mapping->a_ops->readpage(data, page);
3195
Linus Torvalds1da177e2005-04-16 15:20:36 -07003196 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003197 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003198 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003199 }
Mel Gorman32b63522016-03-15 14:55:36 -07003200
3201 page = wait_on_page_read(page);
3202 if (IS_ERR(page))
3203 return page;
3204 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003205 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003206 if (PageUptodate(page))
3207 goto out;
3208
Mel Gormanebded022016-03-15 14:55:39 -07003209 /*
Miaohe Lin0e9aa672020-10-15 20:09:58 -07003210 * Page is not up to date and may be locked due to one of the following
Mel Gormanebded022016-03-15 14:55:39 -07003211 * case a: Page is being filled and the page lock is held
3212 * case b: Read/write error clearing the page uptodate status
3213 * case c: Truncation in progress (page locked)
3214 * case d: Reclaim in progress
3215 *
3216 * Case a, the page will be up to date when the page is unlocked.
3217 * There is no need to serialise on the page lock here as the page
3218 * is pinned so the lock gives no additional protection. Even if the
Randy Dunlapce89fddf2020-08-11 18:32:53 -07003219 * page is truncated, the data is still valid if PageUptodate as
Mel Gormanebded022016-03-15 14:55:39 -07003220 * it's a race vs truncate race.
3221 * Case b, the page will not be up to date
3222 * Case c, the page may be truncated but in itself, the data may still
3223 * be valid after IO completes as it's a read vs truncate race. The
3224 * operation must restart if the page is not uptodate on unlock but
3225 * otherwise serialising on page lock to stabilise the mapping gives
3226 * no additional guarantees to the caller as the page lock is
3227 * released before return.
3228 * Case d, similar to truncation. If reclaim holds the page lock, it
3229 * will be a race with remove_mapping that determines if the mapping
3230 * is valid on unlock but otherwise the data is valid and there is
3231 * no need to serialise with page lock.
3232 *
3233 * As the page lock gives no additional guarantee, we optimistically
3234 * wait on the page to be unlocked and check if it's up to date and
3235 * use the page if it is. Otherwise, the page lock is required to
3236 * distinguish between the different cases. The motivation is that we
3237 * avoid spurious serialisations and wakeups when multiple processes
3238 * wait on the same page for IO to complete.
3239 */
3240 wait_on_page_locked(page);
3241 if (PageUptodate(page))
3242 goto out;
3243
3244 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003245 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07003246
3247 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003248 if (!page->mapping) {
3249 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003250 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003251 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003252 }
Mel Gormanebded022016-03-15 14:55:39 -07003253
3254 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003255 if (PageUptodate(page)) {
3256 unlock_page(page);
3257 goto out;
3258 }
Xianting Tianfaffdfa2020-04-01 21:04:47 -07003259
3260 /*
3261 * A previous I/O error may have been due to temporary
3262 * failures.
3263 * Clear page error before actual read, PG_error will be
3264 * set again if read page fails.
3265 */
3266 ClearPageError(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003267 goto filler;
3268
David Howellsc855ff32007-05-09 13:42:20 +01003269out:
Nick Piggin6fe69002007-05-06 14:49:04 -07003270 mark_page_accessed(page);
3271 return page;
3272}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003273
3274/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07003275 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003276 * @mapping: the page's address_space
3277 * @index: the page index
3278 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003279 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003280 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003281 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07003282 * not set, try to fill the page and wait for it to become unlocked.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003283 *
3284 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08003285 *
3286 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003287 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07003288struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003289 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003290 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003291 void *data)
3292{
Christoph Hellwigd322a8e2019-07-11 20:55:17 -07003293 return do_read_cache_page(mapping, index, filler, data,
3294 mapping_gfp_mask(mapping));
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003295}
Sasha Levin67f9fd92014-04-03 14:48:18 -07003296EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003297
3298/**
3299 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3300 * @mapping: the page's address_space
3301 * @index: the page index
3302 * @gfp: the page allocator flags to use if allocating
3303 *
3304 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06003305 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003306 *
3307 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08003308 *
3309 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003310 */
3311struct page *read_cache_page_gfp(struct address_space *mapping,
3312 pgoff_t index,
3313 gfp_t gfp)
3314{
Christoph Hellwig6c45b452019-07-11 20:55:20 -07003315 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003316}
3317EXPORT_SYMBOL(read_cache_page_gfp);
3318
Nick Pigginafddba42007-10-16 01:25:01 -07003319int pagecache_write_begin(struct file *file, struct address_space *mapping,
3320 loff_t pos, unsigned len, unsigned flags,
3321 struct page **pagep, void **fsdata)
3322{
3323 const struct address_space_operations *aops = mapping->a_ops;
3324
Nick Piggin4e02ed42008-10-29 14:00:55 -07003325 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003326 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003327}
3328EXPORT_SYMBOL(pagecache_write_begin);
3329
3330int pagecache_write_end(struct file *file, struct address_space *mapping,
3331 loff_t pos, unsigned len, unsigned copied,
3332 struct page *page, void *fsdata)
3333{
3334 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003335
Nick Piggin4e02ed42008-10-29 14:00:55 -07003336 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003337}
3338EXPORT_SYMBOL(pagecache_write_end);
3339
Konstantin Khlebnikova92853b2019-11-30 17:49:44 -08003340/*
3341 * Warn about a page cache invalidation failure during a direct I/O write.
3342 */
3343void dio_warn_stale_pagecache(struct file *filp)
3344{
3345 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3346 char pathname[128];
3347 struct inode *inode = file_inode(filp);
3348 char *path;
3349
3350 errseq_set(&inode->i_mapping->wb_err, -EIO);
3351 if (__ratelimit(&_rs)) {
3352 path = file_path(filp, pathname, sizeof(pathname));
3353 if (IS_ERR(path))
3354 path = "(unknown)";
3355 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3356 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3357 current->comm);
3358 }
3359}
3360
Linus Torvalds1da177e2005-04-16 15:20:36 -07003361ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003362generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003363{
3364 struct file *file = iocb->ki_filp;
3365 struct address_space *mapping = file->f_mapping;
3366 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003367 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003368 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003369 size_t write_len;
3370 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003371
Al Viro0c949332014-03-22 06:51:37 -04003372 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003373 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003374
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003375 if (iocb->ki_flags & IOCB_NOWAIT) {
3376 /* If there are pages to writeback, return */
3377 if (filemap_range_has_page(inode->i_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003378 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003379 return -EAGAIN;
3380 } else {
3381 written = filemap_write_and_wait_range(mapping, pos,
3382 pos + write_len - 1);
3383 if (written)
3384 goto out;
3385 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003386
3387 /*
3388 * After a write we want buffered reads to be sure to go to disk to get
3389 * the new data. We invalidate clean cached page from the region we're
3390 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003391 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003392 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003393 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003394 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003395 /*
3396 * If a page can not be invalidated, return 0 to fall back
3397 * to buffered write.
3398 */
3399 if (written) {
3400 if (written == -EBUSY)
3401 return 0;
3402 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003403 }
3404
Al Viro639a93a52017-04-13 14:10:15 -04003405 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003406
3407 /*
3408 * Finally, try again to invalidate clean pages which might have been
3409 * cached by non-direct readahead, or faulted in by get_user_pages()
3410 * if the source of the write was an mmap'ed region of the file
3411 * we're writing. Either one is a pretty crazy thing to do,
3412 * so we don't support it 100%. If this invalidation
3413 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003414 *
3415 * Most of the time we do not need this since dio_complete() will do
3416 * the invalidation for us. However there are some file systems that
3417 * do not end up with dio_complete() being called, so let's not break
Konstantin Khlebnikov80c1fe92019-11-30 17:49:41 -08003418 * them by removing it completely.
3419 *
Konstantin Khlebnikov9266a142019-11-30 17:49:47 -08003420 * Noticeable example is a blkdev_direct_IO().
3421 *
Konstantin Khlebnikov80c1fe92019-11-30 17:49:41 -08003422 * Skip invalidation for async writes or if mapping has no pages.
Christoph Hellwiga969e902008-07-23 21:27:04 -07003423 */
Konstantin Khlebnikov9266a142019-11-30 17:49:47 -08003424 if (written > 0 && mapping->nrpages &&
3425 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3426 dio_warn_stale_pagecache(file);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003427
Linus Torvalds1da177e2005-04-16 15:20:36 -07003428 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003429 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003430 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003431 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3432 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003433 mark_inode_dirty(inode);
3434 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003435 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003436 }
Al Viro639a93a52017-04-13 14:10:15 -04003437 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003438out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003439 return written;
3440}
3441EXPORT_SYMBOL(generic_file_direct_write);
3442
Nick Piggineb2be182007-10-16 01:24:57 -07003443/*
3444 * Find or create a page at the given pagecache position. Return the locked
3445 * page. This function is specifically for buffered writes.
3446 */
Nick Piggin54566b22009-01-04 12:00:53 -08003447struct page *grab_cache_page_write_begin(struct address_space *mapping,
3448 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003449{
Nick Piggineb2be182007-10-16 01:24:57 -07003450 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003451 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003452
Nick Piggin54566b22009-01-04 12:00:53 -08003453 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003454 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003455
Mel Gorman2457aec2014-06-04 16:10:31 -07003456 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003457 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003458 if (page)
3459 wait_for_stable_page(page);
3460
Nick Piggineb2be182007-10-16 01:24:57 -07003461 return page;
3462}
Nick Piggin54566b22009-01-04 12:00:53 -08003463EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003464
Al Viro3b93f912014-02-11 21:34:08 -05003465ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003466 struct iov_iter *i, loff_t pos)
3467{
3468 struct address_space *mapping = file->f_mapping;
3469 const struct address_space_operations *a_ops = mapping->a_ops;
3470 long status = 0;
3471 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003472 unsigned int flags = 0;
3473
Nick Pigginafddba42007-10-16 01:25:01 -07003474 do {
3475 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003476 unsigned long offset; /* Offset into pagecache page */
3477 unsigned long bytes; /* Bytes to write to page */
3478 size_t copied; /* Bytes copied from user */
Alexander Potapenko294ef122022-09-15 17:04:16 +02003479 void *fsdata = NULL;
Nick Pigginafddba42007-10-16 01:25:01 -07003480
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003481 offset = (pos & (PAGE_SIZE - 1));
3482 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003483 iov_iter_count(i));
3484
3485again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003486 /*
3487 * Bring in the user page that we will copy from _first_.
3488 * Otherwise there's a nasty deadlock on copying from the
3489 * same page as we're writing to, without it being marked
3490 * up-to-date.
3491 *
3492 * Not only is this an optimisation, but it is also required
3493 * to check that the address is actually valid, when atomic
3494 * usercopies are used, below.
3495 */
3496 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3497 status = -EFAULT;
3498 break;
3499 }
3500
Jan Kara296291c2015-10-22 13:32:21 -07003501 if (fatal_signal_pending(current)) {
3502 status = -EINTR;
3503 break;
3504 }
3505
Nick Piggin674b8922007-10-16 01:25:03 -07003506 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003507 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003508 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003509 break;
3510
anfei zhou931e80e2010-02-02 13:44:02 -08003511 if (mapping_writably_mapped(mapping))
3512 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003513
Nick Pigginafddba42007-10-16 01:25:01 -07003514 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
Nick Pigginafddba42007-10-16 01:25:01 -07003515 flush_dcache_page(page);
3516
3517 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3518 page, fsdata);
3519 if (unlikely(status < 0))
3520 break;
3521 copied = status;
3522
3523 cond_resched();
3524
Nick Piggin124d3b72008-02-02 15:01:17 +01003525 iov_iter_advance(i, copied);
Nick Pigginafddba42007-10-16 01:25:01 -07003526 if (unlikely(copied == 0)) {
3527 /*
3528 * If we were unable to copy any data at all, we must
3529 * fall back to a single segment length write.
3530 *
3531 * If we didn't fallback here, we could livelock
3532 * because not all segments in the iov can be copied at
3533 * once without a pagefault.
3534 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003535 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003536 iov_iter_single_seg_count(i));
3537 goto again;
3538 }
Nick Pigginafddba42007-10-16 01:25:01 -07003539 pos += copied;
3540 written += copied;
3541
3542 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003543 } while (iov_iter_count(i));
3544
3545 return written ? written : status;
3546}
Al Viro3b93f912014-02-11 21:34:08 -05003547EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003548
Jan Karae4dd9de2009-08-17 18:10:06 +02003549/**
Al Viro81742022014-04-03 03:17:43 -04003550 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003551 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003552 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003553 *
3554 * This function does all the work needed for actually writing data to a
3555 * file. It does all basic checks, removes SUID from the file, updates
3556 * modification times and calls proper subroutines depending on whether we
3557 * do direct IO or a standard buffered write.
3558 *
3559 * It expects i_mutex to be grabbed unless we work on a block device or similar
3560 * object which does not need locking at all.
3561 *
3562 * This function does *not* take care of syncing data in case of O_SYNC write.
3563 * A caller has to handle it. This is mainly due to the fact that we want to
3564 * avoid syncing under i_mutex.
Mike Rapoporta862f682019-03-05 15:48:42 -08003565 *
3566 * Return:
3567 * * number of bytes written, even for truncated writes
3568 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003569 */
Al Viro81742022014-04-03 03:17:43 -04003570ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003571{
3572 struct file *file = iocb->ki_filp;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003573 struct address_space * mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003574 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003575 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003576 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003577 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003578
Linus Torvalds1da177e2005-04-16 15:20:36 -07003579 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003580 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003581 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003582 if (err)
3583 goto out;
3584
Josef Bacikc3b2da32012-03-26 09:59:21 -04003585 err = file_update_time(file);
3586 if (err)
3587 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003588
Al Viro2ba48ce2015-04-09 13:52:01 -04003589 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003590 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003591
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003592 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003593 /*
3594 * If the write stopped short of completing, fall back to
3595 * buffered writes. Some filesystems do this for writes to
3596 * holes, for example. For DAX files, a buffered write will
3597 * not succeed (even if it did, DAX does not handle dirty
3598 * page-cache pages correctly).
3599 */
Al Viro0b8def92015-04-07 10:22:53 -04003600 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003601 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003602
Al Viro0b8def92015-04-07 10:22:53 -04003603 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003604 /*
Al Viro3b93f912014-02-11 21:34:08 -05003605 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003606 * then we want to return the number of bytes which were
3607 * direct-written, or the error code if that was zero. Note
3608 * that this differs from normal direct-io semantics, which
3609 * will return -EFOO even if some bytes were written.
3610 */
Al Viro60bb4522014-08-08 12:39:16 -04003611 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003612 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003613 goto out;
3614 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003615 /*
3616 * We need to ensure that the page cache pages are written to
3617 * disk and invalidated to preserve the expected O_DIRECT
3618 * semantics.
3619 */
Al Viro3b93f912014-02-11 21:34:08 -05003620 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003621 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003622 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003623 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003624 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003625 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003626 pos >> PAGE_SHIFT,
3627 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003628 } else {
3629 /*
3630 * We don't know how much we wrote, so just return
3631 * the number of bytes which were direct-written
3632 */
3633 }
3634 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003635 written = generic_perform_write(file, from, iocb->ki_pos);
3636 if (likely(written > 0))
3637 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003638 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003639out:
3640 current->backing_dev_info = NULL;
3641 return written ? written : err;
3642}
Al Viro81742022014-04-03 03:17:43 -04003643EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003644
Jan Karae4dd9de2009-08-17 18:10:06 +02003645/**
Al Viro81742022014-04-03 03:17:43 -04003646 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003647 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003648 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003649 *
Al Viro81742022014-04-03 03:17:43 -04003650 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003651 * filesystems. It takes care of syncing the file in case of O_SYNC file
3652 * and acquires i_mutex as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003653 * Return:
3654 * * negative error code if no data has been written at all of
3655 * vfs_fsync_range() failed for a synchronous write
3656 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003657 */
Al Viro81742022014-04-03 03:17:43 -04003658ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003659{
3660 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003661 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003662 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003663
Al Viro59551022016-01-22 15:40:57 -05003664 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003665 ret = generic_write_checks(iocb, from);
3666 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003667 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003668 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003669
Christoph Hellwige2592212016-04-07 08:52:01 -07003670 if (ret > 0)
3671 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003672 return ret;
3673}
Al Viro81742022014-04-03 03:17:43 -04003674EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003675
David Howellscf9a2ae2006-08-29 19:05:54 +01003676/**
3677 * try_to_release_page() - release old fs-specific metadata on a page
3678 *
3679 * @page: the page which the kernel is trying to free
3680 * @gfp_mask: memory allocation flags (and I/O mode)
3681 *
3682 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003683 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003684 *
David Howells266cf652009-04-03 16:42:36 +01003685 * This may also be called if PG_fscache is set on a page, indicating that the
3686 * page is known to the local caching routines.
3687 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003688 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003689 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003690 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003691 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003692 */
3693int try_to_release_page(struct page *page, gfp_t gfp_mask)
3694{
3695 struct address_space * const mapping = page->mapping;
3696
3697 BUG_ON(!PageLocked(page));
3698 if (PageWriteback(page))
3699 return 0;
3700
3701 if (mapping && mapping->a_ops->releasepage)
3702 return mapping->a_ops->releasepage(page, gfp_mask);
3703 return try_to_free_buffers(page);
3704}
3705
3706EXPORT_SYMBOL(try_to_release_page);