blob: e87252ca0835acf18a4c3266bdfc2c6b6d49e03e [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>
Nick Piggin0f8053a2006-03-22 00:08:33 -080043#include "internal.h"
44
Robert Jarzmikfe0bfaa2013-04-29 15:06:10 -070045#define CREATE_TRACE_POINTS
46#include <trace/events/filemap.h>
47
Linus Torvalds1da177e2005-04-16 15:20:36 -070048/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070049 * FIXME: remove all knowledge of the buffer layer from the core VM
50 */
Jan Kara148f9482009-08-17 19:52:36 +020051#include <linux/buffer_head.h> /* for try_to_free_buffers */
Linus Torvalds1da177e2005-04-16 15:20:36 -070052
Linus Torvalds1da177e2005-04-16 15:20:36 -070053#include <asm/mman.h>
54
55/*
56 * Shared mappings implemented 30.11.1994. It's not fully working yet,
57 * though.
58 *
59 * Shared mappings now work. 15.8.1995 Bruno.
60 *
61 * finished 'unifying' the page and buffer cache and SMP-threaded the
62 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
63 *
64 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
65 */
66
67/*
68 * Lock ordering:
69 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080070 * ->i_mmap_rwsem (truncate_pagecache)
Linus Torvalds1da177e2005-04-16 15:20:36 -070071 * ->private_lock (__free_pte->__set_page_dirty_buffers)
Hugh Dickins5d337b92005-09-03 15:54:41 -070072 * ->swap_lock (exclusive_swap_page, others)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070073 * ->i_pages lock
Linus Torvalds1da177e2005-04-16 15:20:36 -070074 *
Jes Sorensen1b1dcc12006-01-09 15:59:24 -080075 * ->i_mutex
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080076 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
Linus Torvalds1da177e2005-04-16 15:20:36 -070077 *
78 * ->mmap_sem
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080079 * ->i_mmap_rwsem
Hugh Dickinsb8072f02005-10-29 18:16:41 -070080 * ->page_table_lock or pte_lock (various, mainly in memory.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070081 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
Linus Torvalds1da177e2005-04-16 15:20:36 -070082 *
83 * ->mmap_sem
84 * ->lock_page (access_process_vm)
85 *
Al Viroccad2362014-02-11 22:36:48 -050086 * ->i_mutex (generic_perform_write)
Nick Piggin82591e62006-10-19 23:29:10 -070087 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
Linus Torvalds1da177e2005-04-16 15:20:36 -070088 *
Christoph Hellwigf758eea2011-04-21 18:19:44 -060089 * bdi->wb.list_lock
Dave Chinnera66979a2011-03-22 22:23:41 +110090 * sb_lock (fs/fs-writeback.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070091 * ->i_pages lock (__sync_single_inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -070092 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080093 * ->i_mmap_rwsem
Linus Torvalds1da177e2005-04-16 15:20:36 -070094 * ->anon_vma.lock (vma_adjust)
95 *
96 * ->anon_vma.lock
Hugh Dickinsb8072f02005-10-29 18:16:41 -070097 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
Linus Torvalds1da177e2005-04-16 15:20:36 -070098 *
Hugh Dickinsb8072f02005-10-29 18:16:41 -070099 * ->page_table_lock or pte_lock
Hugh Dickins5d337b92005-09-03 15:54:41 -0700100 * ->swap_lock (try_to_unmap_one)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700101 * ->private_lock (try_to_unmap_one)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700102 * ->i_pages lock (try_to_unmap_one)
Andrey Ryabininf4b7e272019-03-05 15:49:39 -0800103 * ->pgdat->lru_lock (follow_page->mark_page_accessed)
104 * ->pgdat->lru_lock (check_pte_range->isolate_lru_page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700105 * ->private_lock (page_remove_rmap->set_page_dirty)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700106 * ->i_pages lock (page_remove_rmap->set_page_dirty)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600107 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100108 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
Johannes Weiner81f8c3a2016-03-15 14:57:04 -0700109 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600110 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100111 * ->inode->i_lock (zap_pte_range->set_page_dirty)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700112 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
113 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -0800114 * ->i_mmap_rwsem
Andi Kleen9a3c5312012-03-21 16:34:09 -0700115 * ->tasklist_lock (memory_failure, collect_procs_ao)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700116 */
117
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500118static void page_cache_delete(struct address_space *mapping,
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700119 struct page *page, void *shadow)
120{
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500121 XA_STATE(xas, &mapping->i_pages, page->index);
122 unsigned int nr = 1;
Kirill A. Shutemovc70b6472016-12-12 16:43:17 -0800123
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500124 mapping_set_update(&xas, mapping);
125
126 /* hugetlb pages are represented by a single entry in the xarray */
127 if (!PageHuge(page)) {
128 xas_set_order(&xas, page->index, compound_order(page));
129 nr = 1U << compound_order(page);
130 }
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700131
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700132 VM_BUG_ON_PAGE(!PageLocked(page), page);
133 VM_BUG_ON_PAGE(PageTail(page), page);
134 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
Johannes Weiner449dd692014-04-03 14:47:56 -0700135
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500136 xas_store(&xas, shadow);
137 xas_init_marks(&xas);
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200138
Jan Kara23006382017-11-15 17:37:26 -0800139 page->mapping = NULL;
140 /* Leave page->index set: truncation lookup relies upon it */
141
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200142 if (shadow) {
143 mapping->nrexceptional += nr;
144 /*
145 * Make sure the nrexceptional update is committed before
146 * the nrpages update so that final truncate racing
147 * with reclaim does not see both counters 0 at the
148 * same time and miss a shadow entry.
149 */
150 smp_wmb();
151 }
152 mapping->nrpages -= nr;
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700153}
154
Jan Kara5ecc4d82017-11-15 17:37:29 -0800155static void unaccount_page_cache_page(struct address_space *mapping,
156 struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700157{
Jan Kara5ecc4d82017-11-15 17:37:29 -0800158 int nr;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700159
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600160 /*
161 * if we're uptodate, flush out into the cleancache, otherwise
162 * invalidate any existing cleancache entries. We can't leave
163 * stale data around in the cleancache once our page is gone
164 */
165 if (PageUptodate(page) && PageMappedToDisk(page))
166 cleancache_put_page(page);
167 else
Dan Magenheimer31677602011-09-21 11:56:28 -0400168 cleancache_invalidate_page(mapping, page);
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600169
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700170 VM_BUG_ON_PAGE(PageTail(page), page);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800171 VM_BUG_ON_PAGE(page_mapped(page), page);
172 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
173 int mapcount;
174
175 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
176 current->comm, page_to_pfn(page));
177 dump_page(page, "still mapped when deleted");
178 dump_stack();
179 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
180
181 mapcount = page_mapcount(page);
182 if (mapping_exiting(mapping) &&
183 page_count(page) >= mapcount + 2) {
184 /*
185 * All vmas have already been torn down, so it's
186 * a good bet that actually the page is unmapped,
187 * and we'd prefer not to leak it: if we're wrong,
188 * some other bad page check should catch it later.
189 */
190 page_mapcount_reset(page);
Joonsoo Kim6d061f92016-05-19 17:10:46 -0700191 page_ref_sub(page, mapcount);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800192 }
193 }
194
Jan Kara76253fb2017-11-15 17:37:22 -0800195 /* hugetlb pages do not participate in page cache accounting. */
Jan Kara5ecc4d82017-11-15 17:37:29 -0800196 if (PageHuge(page))
197 return;
Jan Kara76253fb2017-11-15 17:37:22 -0800198
Jan Kara5ecc4d82017-11-15 17:37:29 -0800199 nr = hpage_nr_pages(page);
200
201 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
202 if (PageSwapBacked(page)) {
203 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
204 if (PageTransHuge(page))
205 __dec_node_page_state(page, NR_SHMEM_THPS);
206 } else {
207 VM_BUG_ON_PAGE(PageTransHuge(page), page);
Jan Kara76253fb2017-11-15 17:37:22 -0800208 }
Jan Kara5ecc4d82017-11-15 17:37:29 -0800209
210 /*
211 * At this point page must be either written or cleaned by
212 * truncate. Dirty page here signals a bug and loss of
213 * unwritten data.
214 *
215 * This fixes dirty accounting after removing the page entirely
216 * but leaves PageDirty set: it has no effect for truncated
217 * page and anyway will be cleared before returning page into
218 * buddy allocator.
219 */
220 if (WARN_ON_ONCE(PageDirty(page)))
221 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
222}
223
224/*
225 * Delete a page from the page cache and free it. Caller has to make
226 * sure the page is locked and that nobody else uses it - or that usage
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700227 * is safe. The caller must hold the i_pages lock.
Jan Kara5ecc4d82017-11-15 17:37:29 -0800228 */
229void __delete_from_page_cache(struct page *page, void *shadow)
230{
231 struct address_space *mapping = page->mapping;
232
233 trace_mm_filemap_delete_from_page_cache(page);
234
235 unaccount_page_cache_page(mapping, page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500236 page_cache_delete(mapping, page, shadow);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700237}
238
Jan Kara59c66c52017-11-15 17:37:18 -0800239static void page_cache_free_page(struct address_space *mapping,
240 struct page *page)
241{
242 void (*freepage)(struct page *);
243
244 freepage = mapping->a_ops->freepage;
245 if (freepage)
246 freepage(page);
247
248 if (PageTransHuge(page) && !PageHuge(page)) {
249 page_ref_sub(page, HPAGE_PMD_NR);
250 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
251 } else {
252 put_page(page);
253 }
254}
255
Minchan Kim702cfbf2011-03-22 16:32:43 -0700256/**
257 * delete_from_page_cache - delete page from page cache
258 * @page: the page which the kernel is trying to remove from page cache
259 *
260 * This must be called only on pages that have been verified to be in the page
261 * cache and locked. It will never put the page into the free list, the caller
262 * has a reference on the page.
263 */
264void delete_from_page_cache(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700265{
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700266 struct address_space *mapping = page_mapping(page);
Greg Thelenc4843a72015-05-22 17:13:16 -0400267 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700268
Matt Mackallcd7619d2005-05-01 08:59:01 -0700269 BUG_ON(!PageLocked(page));
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700270 xa_lock_irqsave(&mapping->i_pages, flags);
Johannes Weiner62cccb82016-03-15 14:57:22 -0700271 __delete_from_page_cache(page, NULL);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700272 xa_unlock_irqrestore(&mapping->i_pages, flags);
Linus Torvalds6072d132010-12-01 13:35:19 -0500273
Jan Kara59c66c52017-11-15 17:37:18 -0800274 page_cache_free_page(mapping, page);
Minchan Kim97cecb52011-03-22 16:30:53 -0700275}
276EXPORT_SYMBOL(delete_from_page_cache);
277
Jan Karaaa65c292017-11-15 17:37:33 -0800278/*
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500279 * page_cache_delete_batch - delete several pages from page cache
Jan Karaaa65c292017-11-15 17:37:33 -0800280 * @mapping: the mapping to which pages belong
281 * @pvec: pagevec with pages to delete
282 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700283 * The function walks over mapping->i_pages and removes pages passed in @pvec
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700284 * from the mapping. The function expects @pvec to be sorted by page index
285 * and is optimised for it to be dense.
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700286 * It tolerates holes in @pvec (mapping entries at those indices are not
Jan Karaaa65c292017-11-15 17:37:33 -0800287 * modified). The function expects only THP head pages to be present in the
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700288 * @pvec.
Jan Karaaa65c292017-11-15 17:37:33 -0800289 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700290 * The function expects the i_pages lock to be held.
Jan Karaaa65c292017-11-15 17:37:33 -0800291 */
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500292static void page_cache_delete_batch(struct address_space *mapping,
Jan Karaaa65c292017-11-15 17:37:33 -0800293 struct pagevec *pvec)
294{
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500295 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
Jan Karaaa65c292017-11-15 17:37:33 -0800296 int total_pages = 0;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700297 int i = 0;
Jan Karaaa65c292017-11-15 17:37:33 -0800298 struct page *page;
Jan Karaaa65c292017-11-15 17:37:33 -0800299
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500300 mapping_set_update(&xas, mapping);
301 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700302 if (i >= pagevec_count(pvec))
Jan Karaaa65c292017-11-15 17:37:33 -0800303 break;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700304
305 /* A swap/dax/shadow entry got inserted? Skip it. */
Matthew Wilcox3159f942017-11-03 13:30:42 -0400306 if (xa_is_value(page))
Jan Karaaa65c292017-11-15 17:37:33 -0800307 continue;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700308 /*
309 * A page got inserted in our range? Skip it. We have our
310 * pages locked so they are protected from being removed.
311 * If we see a page whose index is higher than ours, it
312 * means our page has been removed, which shouldn't be
313 * possible because we're holding the PageLock.
314 */
315 if (page != pvec->pages[i]) {
316 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
317 page);
318 continue;
Jan Karaaa65c292017-11-15 17:37:33 -0800319 }
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700320
321 WARN_ON_ONCE(!PageLocked(page));
322
323 if (page->index == xas.xa_index)
324 page->mapping = NULL;
325 /* Leave page->index set: truncation lookup relies on it */
326
327 /*
328 * Move to the next page in the vector if this is a regular
329 * page or the index is of the last sub-page of this compound
330 * page.
331 */
332 if (page->index + (1UL << compound_order(page)) - 1 ==
333 xas.xa_index)
334 i++;
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500335 xas_store(&xas, NULL);
Jan Karaaa65c292017-11-15 17:37:33 -0800336 total_pages++;
337 }
338 mapping->nrpages -= total_pages;
339}
340
341void delete_from_page_cache_batch(struct address_space *mapping,
342 struct pagevec *pvec)
343{
344 int i;
345 unsigned long flags;
346
347 if (!pagevec_count(pvec))
348 return;
349
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700350 xa_lock_irqsave(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800351 for (i = 0; i < pagevec_count(pvec); i++) {
352 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
353
354 unaccount_page_cache_page(mapping, pvec->pages[i]);
355 }
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500356 page_cache_delete_batch(mapping, pvec);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700357 xa_unlock_irqrestore(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800358
359 for (i = 0; i < pagevec_count(pvec); i++)
360 page_cache_free_page(mapping, pvec->pages[i]);
361}
362
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200363int filemap_check_errors(struct address_space *mapping)
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700364{
365 int ret = 0;
366 /* Check for outstanding write errors */
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700367 if (test_bit(AS_ENOSPC, &mapping->flags) &&
368 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700369 ret = -ENOSPC;
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700370 if (test_bit(AS_EIO, &mapping->flags) &&
371 test_and_clear_bit(AS_EIO, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700372 ret = -EIO;
373 return ret;
374}
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200375EXPORT_SYMBOL(filemap_check_errors);
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700376
Jeff Layton76341ca2017-07-06 07:02:22 -0400377static int filemap_check_and_keep_errors(struct address_space *mapping)
378{
379 /* Check for outstanding write errors */
380 if (test_bit(AS_EIO, &mapping->flags))
381 return -EIO;
382 if (test_bit(AS_ENOSPC, &mapping->flags))
383 return -ENOSPC;
384 return 0;
385}
386
Linus Torvalds1da177e2005-04-16 15:20:36 -0700387/**
Randy Dunlap485bb992006-06-23 02:03:49 -0700388 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
Martin Waitz67be2dd2005-05-01 08:59:26 -0700389 * @mapping: address space structure to write
390 * @start: offset in bytes where the range starts
Andrew Morton469eb4d2006-03-24 03:17:45 -0800391 * @end: offset in bytes where the range ends (inclusive)
Martin Waitz67be2dd2005-05-01 08:59:26 -0700392 * @sync_mode: enable synchronous operation
Linus Torvalds1da177e2005-04-16 15:20:36 -0700393 *
Randy Dunlap485bb992006-06-23 02:03:49 -0700394 * Start writeback against all of a mapping's dirty pages that lie
395 * within the byte offsets <start, end> inclusive.
396 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700397 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
Randy Dunlap485bb992006-06-23 02:03:49 -0700398 * opposed to a regular memory cleansing writeback. The difference between
Linus Torvalds1da177e2005-04-16 15:20:36 -0700399 * these two operations is that if a dirty page/buffer is encountered, it must
400 * be waited upon, and not just skipped over.
Mike Rapoporta862f682019-03-05 15:48:42 -0800401 *
402 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700403 */
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800404int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
405 loff_t end, int sync_mode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700406{
407 int ret;
408 struct writeback_control wbc = {
409 .sync_mode = sync_mode,
Nick Piggin05fe4782009-01-06 14:39:08 -0800410 .nr_to_write = LONG_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700411 .range_start = start,
412 .range_end = end,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700413 };
414
415 if (!mapping_cap_writeback_dirty(mapping))
416 return 0;
417
Tejun Heob16b1de2015-06-02 08:39:48 -0600418 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700419 ret = do_writepages(mapping, &wbc);
Tejun Heob16b1de2015-06-02 08:39:48 -0600420 wbc_detach_inode(&wbc);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700421 return ret;
422}
423
424static inline int __filemap_fdatawrite(struct address_space *mapping,
425 int sync_mode)
426{
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700427 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700428}
429
430int filemap_fdatawrite(struct address_space *mapping)
431{
432 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
433}
434EXPORT_SYMBOL(filemap_fdatawrite);
435
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400436int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800437 loff_t end)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700438{
439 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
440}
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400441EXPORT_SYMBOL(filemap_fdatawrite_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700442
Randy Dunlap485bb992006-06-23 02:03:49 -0700443/**
444 * filemap_flush - mostly a non-blocking flush
445 * @mapping: target address_space
446 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700447 * This is a mostly non-blocking flush. Not suitable for data-integrity
448 * purposes - I/O may not be started against all dirty pages.
Mike Rapoporta862f682019-03-05 15:48:42 -0800449 *
450 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700451 */
452int filemap_flush(struct address_space *mapping)
453{
454 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
455}
456EXPORT_SYMBOL(filemap_flush);
457
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500458/**
459 * filemap_range_has_page - check if a page exists in range.
460 * @mapping: address space within which to check
461 * @start_byte: offset in bytes where the range starts
462 * @end_byte: offset in bytes where the range ends (inclusive)
463 *
464 * Find at least one page in the range supplied, usually used to check if
465 * direct writing in this range will trigger a writeback.
Mike Rapoporta862f682019-03-05 15:48:42 -0800466 *
467 * Return: %true if at least one page exists in the specified range,
468 * %false otherwise.
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500469 */
470bool filemap_range_has_page(struct address_space *mapping,
471 loff_t start_byte, loff_t end_byte)
472{
Jan Karaf7b68042017-09-06 16:21:40 -0700473 struct page *page;
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500474 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
475 pgoff_t max = end_byte >> PAGE_SHIFT;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500476
477 if (end_byte < start_byte)
478 return false;
479
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500480 rcu_read_lock();
481 for (;;) {
482 page = xas_find(&xas, max);
483 if (xas_retry(&xas, page))
484 continue;
485 /* Shadow entries don't count */
486 if (xa_is_value(page))
487 continue;
488 /*
489 * We don't need to try to pin this page; we're about to
490 * release the RCU lock anyway. It is enough to know that
491 * there was a page here recently.
492 */
493 break;
494 }
495 rcu_read_unlock();
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500496
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500497 return page != NULL;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500498}
499EXPORT_SYMBOL(filemap_range_has_page);
500
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400501static void __filemap_fdatawait_range(struct address_space *mapping,
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800502 loff_t start_byte, loff_t end_byte)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700503{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300504 pgoff_t index = start_byte >> PAGE_SHIFT;
505 pgoff_t end = end_byte >> PAGE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700506 struct pagevec pvec;
507 int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700508
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200509 if (end_byte < start_byte)
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400510 return;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700511
Mel Gorman86679822017-11-15 17:37:52 -0800512 pagevec_init(&pvec);
Jan Kara312e9d22017-11-15 17:35:05 -0800513 while (index <= end) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700514 unsigned i;
515
Jan Kara312e9d22017-11-15 17:35:05 -0800516 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
Jan Kara67fd7072017-11-15 17:35:19 -0800517 end, PAGECACHE_TAG_WRITEBACK);
Jan Kara312e9d22017-11-15 17:35:05 -0800518 if (!nr_pages)
519 break;
520
Linus Torvalds1da177e2005-04-16 15:20:36 -0700521 for (i = 0; i < nr_pages; i++) {
522 struct page *page = pvec.pages[i];
523
Linus Torvalds1da177e2005-04-16 15:20:36 -0700524 wait_on_page_writeback(page);
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400525 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700526 }
527 pagevec_release(&pvec);
528 cond_resched();
529 }
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800530}
531
532/**
533 * filemap_fdatawait_range - wait for writeback to complete
534 * @mapping: address space structure to wait for
535 * @start_byte: offset in bytes where the range starts
536 * @end_byte: offset in bytes where the range ends (inclusive)
537 *
538 * Walk the list of under-writeback pages of the given address space
539 * in the given range and wait for all of them. Check error status of
540 * the address space and return it.
541 *
542 * Since the error status of the address space is cleared by this function,
543 * callers are responsible for checking the return value and handling and/or
544 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800545 *
546 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800547 */
548int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
549 loff_t end_byte)
550{
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400551 __filemap_fdatawait_range(mapping, start_byte, end_byte);
552 return filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700553}
Jan Karad3bccb6f2009-08-17 19:30:27 +0200554EXPORT_SYMBOL(filemap_fdatawait_range);
555
556/**
Ross Zwisleraa0bfcd2019-06-20 17:05:37 -0400557 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
558 * @mapping: address space structure to wait for
559 * @start_byte: offset in bytes where the range starts
560 * @end_byte: offset in bytes where the range ends (inclusive)
561 *
562 * Walk the list of under-writeback pages of the given address space in the
563 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
564 * this function does not clear error status of the address space.
565 *
566 * Use this function if callers don't handle errors themselves. Expected
567 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
568 * fsfreeze(8)
569 */
570int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
571 loff_t start_byte, loff_t end_byte)
572{
573 __filemap_fdatawait_range(mapping, start_byte, end_byte);
574 return filemap_check_and_keep_errors(mapping);
575}
576EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
577
578/**
Jeff Laytona823e452017-07-28 07:24:43 -0400579 * file_fdatawait_range - wait for writeback to complete
580 * @file: file pointing to address space structure to wait for
581 * @start_byte: offset in bytes where the range starts
582 * @end_byte: offset in bytes where the range ends (inclusive)
583 *
584 * Walk the list of under-writeback pages of the address space that file
585 * refers to, in the given range and wait for all of them. Check error
586 * status of the address space vs. the file->f_wb_err cursor and return it.
587 *
588 * Since the error status of the file is advanced by this function,
589 * callers are responsible for checking the return value and handling and/or
590 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800591 *
592 * Return: error status of the address space vs. the file->f_wb_err cursor.
Jeff Laytona823e452017-07-28 07:24:43 -0400593 */
594int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
595{
596 struct address_space *mapping = file->f_mapping;
597
598 __filemap_fdatawait_range(mapping, start_byte, end_byte);
599 return file_check_and_advance_wb_err(file);
600}
601EXPORT_SYMBOL(file_fdatawait_range);
602
603/**
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800604 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
605 * @mapping: address space structure to wait for
606 *
607 * Walk the list of under-writeback pages of the given address space
608 * and wait for all of them. Unlike filemap_fdatawait(), this function
609 * does not clear error status of the address space.
610 *
611 * Use this function if callers don't handle errors themselves. Expected
612 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
613 * fsfreeze(8)
Mike Rapoporta862f682019-03-05 15:48:42 -0800614 *
615 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800616 */
Jeff Layton76341ca2017-07-06 07:02:22 -0400617int filemap_fdatawait_keep_errors(struct address_space *mapping)
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800618{
Jeff Laytonffb959b2017-07-31 10:29:38 -0400619 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
Jeff Layton76341ca2017-07-06 07:02:22 -0400620 return filemap_check_and_keep_errors(mapping);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800621}
Jeff Layton76341ca2017-07-06 07:02:22 -0400622EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800623
Jeff Layton9326c9b2017-07-26 10:21:11 -0400624static bool mapping_needs_writeback(struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700625{
Jeff Layton9326c9b2017-07-26 10:21:11 -0400626 return (!dax_mapping(mapping) && mapping->nrpages) ||
627 (dax_mapping(mapping) && mapping->nrexceptional);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700628}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700629
630int filemap_write_and_wait(struct address_space *mapping)
631{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800632 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700633
Jeff Layton9326c9b2017-07-26 10:21:11 -0400634 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800635 err = filemap_fdatawrite(mapping);
636 /*
637 * Even if the above returned error, the pages may be
638 * written partially (e.g. -ENOSPC), so we wait for it.
639 * But the -EIO is special case, it may indicate the worst
640 * thing (e.g. bug) happened, so we avoid waiting for it.
641 */
642 if (err != -EIO) {
643 int err2 = filemap_fdatawait(mapping);
644 if (!err)
645 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400646 } else {
647 /* Clear any previously stored errors */
648 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800649 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700650 } else {
651 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700652 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800653 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700654}
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800655EXPORT_SYMBOL(filemap_write_and_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700656
Randy Dunlap485bb992006-06-23 02:03:49 -0700657/**
658 * filemap_write_and_wait_range - write out & wait on a file range
659 * @mapping: the address_space for the pages
660 * @lstart: offset in bytes where the range starts
661 * @lend: offset in bytes where the range ends (inclusive)
662 *
Andrew Morton469eb4d2006-03-24 03:17:45 -0800663 * Write out and wait upon file offsets lstart->lend, inclusive.
664 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -0300665 * Note that @lend is inclusive (describes the last byte to be written) so
Andrew Morton469eb4d2006-03-24 03:17:45 -0800666 * that this function can be used to write to the very end-of-file (end = -1).
Mike Rapoporta862f682019-03-05 15:48:42 -0800667 *
668 * Return: error status of the address space.
Andrew Morton469eb4d2006-03-24 03:17:45 -0800669 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700670int filemap_write_and_wait_range(struct address_space *mapping,
671 loff_t lstart, loff_t lend)
672{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800673 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700674
Jeff Layton9326c9b2017-07-26 10:21:11 -0400675 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800676 err = __filemap_fdatawrite_range(mapping, lstart, lend,
677 WB_SYNC_ALL);
678 /* See comment of filemap_write_and_wait() */
679 if (err != -EIO) {
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200680 int err2 = filemap_fdatawait_range(mapping,
681 lstart, lend);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800682 if (!err)
683 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400684 } else {
685 /* Clear any previously stored errors */
686 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800687 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700688 } else {
689 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800691 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692}
Chris Masonf6995582009-04-15 13:22:37 -0400693EXPORT_SYMBOL(filemap_write_and_wait_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694
Jeff Layton5660e132017-07-06 07:02:25 -0400695void __filemap_set_wb_err(struct address_space *mapping, int err)
696{
Jeff Layton3acdfd22017-07-24 06:22:15 -0400697 errseq_t eseq = errseq_set(&mapping->wb_err, err);
Jeff Layton5660e132017-07-06 07:02:25 -0400698
699 trace_filemap_set_wb_err(mapping, eseq);
700}
701EXPORT_SYMBOL(__filemap_set_wb_err);
702
703/**
704 * file_check_and_advance_wb_err - report wb error (if any) that was previously
705 * and advance wb_err to current one
706 * @file: struct file on which the error is being reported
707 *
708 * When userland calls fsync (or something like nfsd does the equivalent), we
709 * want to report any writeback errors that occurred since the last fsync (or
710 * since the file was opened if there haven't been any).
711 *
712 * Grab the wb_err from the mapping. If it matches what we have in the file,
713 * then just quickly return 0. The file is all caught up.
714 *
715 * If it doesn't match, then take the mapping value, set the "seen" flag in
716 * it and try to swap it into place. If it works, or another task beat us
717 * to it with the new value, then update the f_wb_err and return the error
718 * portion. The error at this point must be reported via proper channels
719 * (a'la fsync, or NFS COMMIT operation, etc.).
720 *
721 * While we handle mapping->wb_err with atomic operations, the f_wb_err
722 * value is protected by the f_lock since we must ensure that it reflects
723 * the latest value swapped in for this file descriptor.
Mike Rapoporta862f682019-03-05 15:48:42 -0800724 *
725 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400726 */
727int file_check_and_advance_wb_err(struct file *file)
728{
729 int err = 0;
730 errseq_t old = READ_ONCE(file->f_wb_err);
731 struct address_space *mapping = file->f_mapping;
732
733 /* Locklessly handle the common case where nothing has changed */
734 if (errseq_check(&mapping->wb_err, old)) {
735 /* Something changed, must use slow path */
736 spin_lock(&file->f_lock);
737 old = file->f_wb_err;
738 err = errseq_check_and_advance(&mapping->wb_err,
739 &file->f_wb_err);
740 trace_file_check_and_advance_wb_err(file, old);
741 spin_unlock(&file->f_lock);
742 }
Jeff Laytonf4e222c2017-10-03 16:15:25 -0700743
744 /*
745 * We're mostly using this function as a drop in replacement for
746 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
747 * that the legacy code would have had on these flags.
748 */
749 clear_bit(AS_EIO, &mapping->flags);
750 clear_bit(AS_ENOSPC, &mapping->flags);
Jeff Layton5660e132017-07-06 07:02:25 -0400751 return err;
752}
753EXPORT_SYMBOL(file_check_and_advance_wb_err);
754
755/**
756 * file_write_and_wait_range - write out & wait on a file range
757 * @file: file pointing to address_space with pages
758 * @lstart: offset in bytes where the range starts
759 * @lend: offset in bytes where the range ends (inclusive)
760 *
761 * Write out and wait upon file offsets lstart->lend, inclusive.
762 *
763 * Note that @lend is inclusive (describes the last byte to be written) so
764 * that this function can be used to write to the very end-of-file (end = -1).
765 *
766 * After writing out and waiting on the data, we check and advance the
767 * f_wb_err cursor to the latest value, and return any errors detected there.
Mike Rapoporta862f682019-03-05 15:48:42 -0800768 *
769 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400770 */
771int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
772{
773 int err = 0, err2;
774 struct address_space *mapping = file->f_mapping;
775
Jeff Layton9326c9b2017-07-26 10:21:11 -0400776 if (mapping_needs_writeback(mapping)) {
Jeff Layton5660e132017-07-06 07:02:25 -0400777 err = __filemap_fdatawrite_range(mapping, lstart, lend,
778 WB_SYNC_ALL);
779 /* See comment of filemap_write_and_wait() */
780 if (err != -EIO)
781 __filemap_fdatawait_range(mapping, lstart, lend);
782 }
783 err2 = file_check_and_advance_wb_err(file);
784 if (!err)
785 err = err2;
786 return err;
787}
788EXPORT_SYMBOL(file_write_and_wait_range);
789
Randy Dunlap485bb992006-06-23 02:03:49 -0700790/**
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700791 * replace_page_cache_page - replace a pagecache page with a new one
792 * @old: page to be replaced
793 * @new: page to replace with
794 * @gfp_mask: allocation mode
795 *
796 * This function replaces a page in the pagecache with a new one. On
797 * success it acquires the pagecache reference for the new page and
798 * drops it for the old page. Both the old and new pages must be
799 * locked. This function does not add the new page to the LRU, the
800 * caller must do that.
801 *
Matthew Wilcox74d60952017-11-17 10:01:45 -0500802 * The remove + add is atomic. This function cannot fail.
Mike Rapoporta862f682019-03-05 15:48:42 -0800803 *
804 * Return: %0
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700805 */
806int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
807{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500808 struct address_space *mapping = old->mapping;
809 void (*freepage)(struct page *) = mapping->a_ops->freepage;
810 pgoff_t offset = old->index;
811 XA_STATE(xas, &mapping->i_pages, offset);
812 unsigned long flags;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700813
Sasha Levin309381fea2014-01-23 15:52:54 -0800814 VM_BUG_ON_PAGE(!PageLocked(old), old);
815 VM_BUG_ON_PAGE(!PageLocked(new), new);
816 VM_BUG_ON_PAGE(new->mapping, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700817
Matthew Wilcox74d60952017-11-17 10:01:45 -0500818 get_page(new);
819 new->mapping = mapping;
820 new->index = offset;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700821
Matthew Wilcox74d60952017-11-17 10:01:45 -0500822 xas_lock_irqsave(&xas, flags);
823 xas_store(&xas, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700824
Matthew Wilcox74d60952017-11-17 10:01:45 -0500825 old->mapping = NULL;
826 /* hugetlb pages do not participate in page cache accounting. */
827 if (!PageHuge(old))
828 __dec_node_page_state(new, NR_FILE_PAGES);
829 if (!PageHuge(new))
830 __inc_node_page_state(new, NR_FILE_PAGES);
831 if (PageSwapBacked(old))
832 __dec_node_page_state(new, NR_SHMEM);
833 if (PageSwapBacked(new))
834 __inc_node_page_state(new, NR_SHMEM);
835 xas_unlock_irqrestore(&xas, flags);
836 mem_cgroup_migrate(old, new);
837 if (freepage)
838 freepage(old);
839 put_page(old);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700840
Matthew Wilcox74d60952017-11-17 10:01:45 -0500841 return 0;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700842}
843EXPORT_SYMBOL_GPL(replace_page_cache_page);
844
Johannes Weinera5289102014-04-03 14:47:51 -0700845static int __add_to_page_cache_locked(struct page *page,
846 struct address_space *mapping,
847 pgoff_t offset, gfp_t gfp_mask,
848 void **shadowp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700849{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500850 XA_STATE(xas, &mapping->i_pages, offset);
Johannes Weiner00501b52014-08-08 14:19:20 -0700851 int huge = PageHuge(page);
852 struct mem_cgroup *memcg;
Nick Piggine2867812008-07-25 19:45:30 -0700853 int error;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500854 void *old;
Nick Piggine2867812008-07-25 19:45:30 -0700855
Sasha Levin309381fea2014-01-23 15:52:54 -0800856 VM_BUG_ON_PAGE(!PageLocked(page), page);
857 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500858 mapping_set_update(&xas, mapping);
Nick Piggine2867812008-07-25 19:45:30 -0700859
Johannes Weiner00501b52014-08-08 14:19:20 -0700860 if (!huge) {
861 error = mem_cgroup_try_charge(page, current->mm,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800862 gfp_mask, &memcg, false);
Johannes Weiner00501b52014-08-08 14:19:20 -0700863 if (error)
864 return error;
865 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700866
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300867 get_page(page);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700868 page->mapping = mapping;
869 page->index = offset;
870
Matthew Wilcox74d60952017-11-17 10:01:45 -0500871 do {
872 xas_lock_irq(&xas);
873 old = xas_load(&xas);
874 if (old && !xa_is_value(old))
875 xas_set_err(&xas, -EEXIST);
876 xas_store(&xas, page);
877 if (xas_error(&xas))
878 goto unlock;
Michal Hocko4165b9b2015-06-24 16:57:24 -0700879
Matthew Wilcox74d60952017-11-17 10:01:45 -0500880 if (xa_is_value(old)) {
881 mapping->nrexceptional--;
882 if (shadowp)
883 *shadowp = old;
884 }
885 mapping->nrpages++;
886
887 /* hugetlb pages do not participate in page cache accounting */
888 if (!huge)
889 __inc_node_page_state(page, NR_FILE_PAGES);
890unlock:
891 xas_unlock_irq(&xas);
892 } while (xas_nomem(&xas, gfp_mask & GFP_RECLAIM_MASK));
893
894 if (xas_error(&xas))
895 goto error;
896
Johannes Weiner00501b52014-08-08 14:19:20 -0700897 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800898 mem_cgroup_commit_charge(page, memcg, false, false);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700899 trace_mm_filemap_add_to_page_cache(page);
900 return 0;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500901error:
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700902 page->mapping = NULL;
903 /* Leave page->index set: truncation relies upon it */
Johannes Weiner00501b52014-08-08 14:19:20 -0700904 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800905 mem_cgroup_cancel_charge(page, memcg, false);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300906 put_page(page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500907 return xas_error(&xas);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700908}
Josef Bacikcfcbfb12019-05-13 17:21:04 -0700909ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
Johannes Weinera5289102014-04-03 14:47:51 -0700910
911/**
912 * add_to_page_cache_locked - add a locked page to the pagecache
913 * @page: page to add
914 * @mapping: the page's address_space
915 * @offset: page index
916 * @gfp_mask: page allocation mode
917 *
918 * This function is used to add a page to the pagecache. It must be locked.
919 * This function does not add the page to the LRU. The caller must do that.
Mike Rapoporta862f682019-03-05 15:48:42 -0800920 *
921 * Return: %0 on success, negative error code otherwise.
Johannes Weinera5289102014-04-03 14:47:51 -0700922 */
923int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
924 pgoff_t offset, gfp_t gfp_mask)
925{
926 return __add_to_page_cache_locked(page, mapping, offset,
927 gfp_mask, NULL);
928}
Nick Piggine2867812008-07-25 19:45:30 -0700929EXPORT_SYMBOL(add_to_page_cache_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700930
931int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
Al Viro6daa0e22005-10-21 03:18:50 -0400932 pgoff_t offset, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933{
Johannes Weinera5289102014-04-03 14:47:51 -0700934 void *shadow = NULL;
Rik van Riel4f98a2f2008-10-18 20:26:32 -0700935 int ret;
936
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800937 __SetPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700938 ret = __add_to_page_cache_locked(page, mapping, offset,
939 gfp_mask, &shadow);
940 if (unlikely(ret))
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800941 __ClearPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700942 else {
943 /*
944 * The page might have been evicted from cache only
945 * recently, in which case it should be activated like
946 * any other repeatedly accessed page.
Rik van Rielf0281a02016-05-20 16:56:25 -0700947 * The exception is pages getting rewritten; evicting other
948 * data from the working set, only to cache data that will
949 * get overwritten with something else, is a waste of memory.
Johannes Weinera5289102014-04-03 14:47:51 -0700950 */
Johannes Weiner1899ad12018-10-26 15:06:04 -0700951 WARN_ON_ONCE(PageActive(page));
952 if (!(gfp_mask & __GFP_WRITE) && shadow)
953 workingset_refault(page, shadow);
Johannes Weinera5289102014-04-03 14:47:51 -0700954 lru_cache_add(page);
955 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700956 return ret;
957}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +0300958EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959
Paul Jackson44110fe2006-03-24 03:16:04 -0800960#ifdef CONFIG_NUMA
Nick Piggin2ae88142006-10-28 10:38:23 -0700961struct page *__page_cache_alloc(gfp_t gfp)
Paul Jackson44110fe2006-03-24 03:16:04 -0800962{
Miao Xiec0ff7452010-05-24 14:32:08 -0700963 int n;
964 struct page *page;
965
Paul Jackson44110fe2006-03-24 03:16:04 -0800966 if (cpuset_do_page_mem_spread()) {
Mel Gormancc9a6c82012-03-21 16:34:11 -0700967 unsigned int cpuset_mems_cookie;
968 do {
Mel Gormand26914d2014-04-03 14:47:24 -0700969 cpuset_mems_cookie = read_mems_allowed_begin();
Mel Gormancc9a6c82012-03-21 16:34:11 -0700970 n = cpuset_mem_spread_node();
Vlastimil Babka96db8002015-09-08 15:03:50 -0700971 page = __alloc_pages_node(n, gfp, 0);
Mel Gormand26914d2014-04-03 14:47:24 -0700972 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
Mel Gormancc9a6c82012-03-21 16:34:11 -0700973
Miao Xiec0ff7452010-05-24 14:32:08 -0700974 return page;
Paul Jackson44110fe2006-03-24 03:16:04 -0800975 }
Nick Piggin2ae88142006-10-28 10:38:23 -0700976 return alloc_pages(gfp, 0);
Paul Jackson44110fe2006-03-24 03:16:04 -0800977}
Nick Piggin2ae88142006-10-28 10:38:23 -0700978EXPORT_SYMBOL(__page_cache_alloc);
Paul Jackson44110fe2006-03-24 03:16:04 -0800979#endif
980
Linus Torvalds1da177e2005-04-16 15:20:36 -0700981/*
982 * In order to wait for pages to become available there must be
983 * waitqueues associated with pages. By using a hash table of
984 * waitqueues where the bucket discipline is to maintain all
985 * waiters on the same queue and wake all when any of the pages
986 * become available, and for the woken contexts to check to be
987 * sure the appropriate page became available, this saves space
988 * at a cost of "thundering herd" phenomena during rare hash
989 * collisions.
990 */
Nicholas Piggin62906022016-12-25 13:00:30 +1000991#define PAGE_WAIT_TABLE_BITS 8
992#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
993static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
994
995static wait_queue_head_t *page_waitqueue(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700996{
Nicholas Piggin62906022016-12-25 13:00:30 +1000997 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700998}
Nicholas Piggin62906022016-12-25 13:00:30 +1000999
1000void __init pagecache_init(void)
1001{
1002 int i;
1003
1004 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1005 init_waitqueue_head(&page_wait_table[i]);
1006
1007 page_writeback_init();
1008}
1009
Linus Torvalds3510ca22017-08-27 13:55:12 -07001010/* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
Nicholas Piggin62906022016-12-25 13:00:30 +10001011struct wait_page_key {
1012 struct page *page;
1013 int bit_nr;
1014 int page_match;
1015};
1016
1017struct wait_page_queue {
1018 struct page *page;
1019 int bit_nr;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001020 wait_queue_entry_t wait;
Nicholas Piggin62906022016-12-25 13:00:30 +10001021};
1022
Ingo Molnarac6424b2017-06-20 12:06:13 +02001023static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
Nicholas Piggin62906022016-12-25 13:00:30 +10001024{
1025 struct wait_page_key *key = arg;
1026 struct wait_page_queue *wait_page
1027 = container_of(wait, struct wait_page_queue, wait);
1028
1029 if (wait_page->page != key->page)
1030 return 0;
1031 key->page_match = 1;
1032
1033 if (wait_page->bit_nr != key->bit_nr)
1034 return 0;
Linus Torvalds3510ca22017-08-27 13:55:12 -07001035
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001036 /*
1037 * Stop walking if it's locked.
1038 * Is this safe if put_and_wait_on_page_locked() is in use?
1039 * Yes: the waker must hold a reference to this page, and if PG_locked
1040 * has now already been set by another task, that task must also hold
1041 * a reference to the *same usage* of this page; so there is no need
1042 * to walk on to wake even the put_and_wait_on_page_locked() callers.
1043 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001044 if (test_bit(key->bit_nr, &key->page->flags))
Linus Torvalds3510ca22017-08-27 13:55:12 -07001045 return -1;
Nicholas Piggin62906022016-12-25 13:00:30 +10001046
1047 return autoremove_wake_function(wait, mode, sync, key);
1048}
1049
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001050static void wake_up_page_bit(struct page *page, int bit_nr)
Nicholas Piggin62906022016-12-25 13:00:30 +10001051{
1052 wait_queue_head_t *q = page_waitqueue(page);
1053 struct wait_page_key key;
1054 unsigned long flags;
Tim Chen11a19c72017-08-25 09:13:55 -07001055 wait_queue_entry_t bookmark;
Nicholas Piggin62906022016-12-25 13:00:30 +10001056
1057 key.page = page;
1058 key.bit_nr = bit_nr;
1059 key.page_match = 0;
1060
Tim Chen11a19c72017-08-25 09:13:55 -07001061 bookmark.flags = 0;
1062 bookmark.private = NULL;
1063 bookmark.func = NULL;
1064 INIT_LIST_HEAD(&bookmark.entry);
1065
Nicholas Piggin62906022016-12-25 13:00:30 +10001066 spin_lock_irqsave(&q->lock, flags);
Tim Chen11a19c72017-08-25 09:13:55 -07001067 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1068
1069 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1070 /*
1071 * Take a breather from holding the lock,
1072 * allow pages that finish wake up asynchronously
1073 * to acquire the lock and remove themselves
1074 * from wait queue
1075 */
1076 spin_unlock_irqrestore(&q->lock, flags);
1077 cpu_relax();
1078 spin_lock_irqsave(&q->lock, flags);
1079 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1080 }
1081
Nicholas Piggin62906022016-12-25 13:00:30 +10001082 /*
1083 * It is possible for other pages to have collided on the waitqueue
1084 * hash, so in that case check for a page match. That prevents a long-
1085 * term waiter
1086 *
1087 * It is still possible to miss a case here, when we woke page waiters
1088 * and removed them from the waitqueue, but there are still other
1089 * page waiters.
1090 */
1091 if (!waitqueue_active(q) || !key.page_match) {
1092 ClearPageWaiters(page);
1093 /*
1094 * It's possible to miss clearing Waiters here, when we woke
1095 * our page waiters, but the hashed waitqueue has waiters for
1096 * other pages on it.
1097 *
1098 * That's okay, it's a rare case. The next waker will clear it.
1099 */
1100 }
1101 spin_unlock_irqrestore(&q->lock, flags);
1102}
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001103
1104static void wake_up_page(struct page *page, int bit)
1105{
1106 if (!PageWaiters(page))
1107 return;
1108 wake_up_page_bit(page, bit);
1109}
Nicholas Piggin62906022016-12-25 13:00:30 +10001110
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001111/*
1112 * A choice of three behaviors for wait_on_page_bit_common():
1113 */
1114enum behavior {
1115 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1116 * __lock_page() waiting on then setting PG_locked.
1117 */
1118 SHARED, /* Hold ref to page and check the bit when woken, like
1119 * wait_on_page_writeback() waiting on PG_writeback.
1120 */
1121 DROP, /* Drop ref to page before wait, no check when woken,
1122 * like put_and_wait_on_page_locked() on PG_locked.
1123 */
1124};
1125
Nicholas Piggin62906022016-12-25 13:00:30 +10001126static inline int wait_on_page_bit_common(wait_queue_head_t *q,
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001127 struct page *page, int bit_nr, int state, enum behavior behavior)
Nicholas Piggin62906022016-12-25 13:00:30 +10001128{
1129 struct wait_page_queue wait_page;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001130 wait_queue_entry_t *wait = &wait_page.wait;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001131 bool bit_is_set;
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001132 bool thrashing = false;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001133 bool delayacct = false;
Johannes Weinereb414682018-10-26 15:06:27 -07001134 unsigned long pflags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001135 int ret = 0;
1136
Johannes Weinereb414682018-10-26 15:06:27 -07001137 if (bit_nr == PG_locked &&
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001138 !PageUptodate(page) && PageWorkingset(page)) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001139 if (!PageSwapBacked(page)) {
Johannes Weinereb414682018-10-26 15:06:27 -07001140 delayacct_thrashing_start();
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001141 delayacct = true;
1142 }
Johannes Weinereb414682018-10-26 15:06:27 -07001143 psi_memstall_enter(&pflags);
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001144 thrashing = true;
1145 }
1146
Nicholas Piggin62906022016-12-25 13:00:30 +10001147 init_wait(wait);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001148 wait->flags = behavior == EXCLUSIVE ? WQ_FLAG_EXCLUSIVE : 0;
Nicholas Piggin62906022016-12-25 13:00:30 +10001149 wait->func = wake_page_function;
1150 wait_page.page = page;
1151 wait_page.bit_nr = bit_nr;
1152
1153 for (;;) {
1154 spin_lock_irq(&q->lock);
1155
Ingo Molnar2055da92017-06-20 12:06:46 +02001156 if (likely(list_empty(&wait->entry))) {
Linus Torvalds3510ca22017-08-27 13:55:12 -07001157 __add_wait_queue_entry_tail(q, wait);
Nicholas Piggin62906022016-12-25 13:00:30 +10001158 SetPageWaiters(page);
1159 }
1160
1161 set_current_state(state);
1162
1163 spin_unlock_irq(&q->lock);
1164
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001165 bit_is_set = test_bit(bit_nr, &page->flags);
1166 if (behavior == DROP)
1167 put_page(page);
Nicholas Piggin62906022016-12-25 13:00:30 +10001168
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001169 if (likely(bit_is_set))
1170 io_schedule();
1171
1172 if (behavior == EXCLUSIVE) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001173 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1174 break;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001175 } else if (behavior == SHARED) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001176 if (!test_bit(bit_nr, &page->flags))
1177 break;
1178 }
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001179
Davidlohr Buesofa45f112019-01-03 15:28:55 -08001180 if (signal_pending_state(state, current)) {
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001181 ret = -EINTR;
1182 break;
1183 }
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001184
1185 if (behavior == DROP) {
1186 /*
1187 * We can no longer safely access page->flags:
1188 * even if CONFIG_MEMORY_HOTREMOVE is not enabled,
1189 * there is a risk of waiting forever on a page reused
1190 * for something that keeps it locked indefinitely.
1191 * But best check for -EINTR above before breaking.
1192 */
1193 break;
1194 }
Nicholas Piggin62906022016-12-25 13:00:30 +10001195 }
1196
1197 finish_wait(q, wait);
1198
Johannes Weinereb414682018-10-26 15:06:27 -07001199 if (thrashing) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001200 if (delayacct)
Johannes Weinereb414682018-10-26 15:06:27 -07001201 delayacct_thrashing_end();
1202 psi_memstall_leave(&pflags);
1203 }
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001204
Nicholas Piggin62906022016-12-25 13:00:30 +10001205 /*
1206 * A signal could leave PageWaiters set. Clearing it here if
1207 * !waitqueue_active would be possible (by open-coding finish_wait),
1208 * but still fail to catch it in the case of wait hash collision. We
1209 * already can fail to clear wait hash collision cases, so don't
1210 * bother with signals either.
1211 */
1212
1213 return ret;
1214}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001215
Harvey Harrison920c7a52008-02-04 22:29:26 -08001216void wait_on_page_bit(struct page *page, int bit_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001217{
Nicholas Piggin62906022016-12-25 13:00:30 +10001218 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001219 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001220}
1221EXPORT_SYMBOL(wait_on_page_bit);
1222
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001223int wait_on_page_bit_killable(struct page *page, int bit_nr)
1224{
Nicholas Piggin62906022016-12-25 13:00:30 +10001225 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001226 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001227}
David Howells4343d002017-11-02 15:27:52 +00001228EXPORT_SYMBOL(wait_on_page_bit_killable);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001229
Linus Torvalds1da177e2005-04-16 15:20:36 -07001230/**
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001231 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1232 * @page: The page to wait for.
1233 *
1234 * The caller should hold a reference on @page. They expect the page to
1235 * become unlocked relatively soon, but do not wish to hold up migration
1236 * (for example) by holding the reference while waiting for the page to
1237 * come unlocked. After this function returns, the caller should not
1238 * dereference @page.
1239 */
1240void put_and_wait_on_page_locked(struct page *page)
1241{
1242 wait_queue_head_t *q;
1243
1244 page = compound_head(page);
1245 q = page_waitqueue(page);
1246 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1247}
1248
1249/**
David Howells385e1ca5f2009-04-03 16:42:39 +01001250 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
Randy Dunlap697f6192009-04-13 14:39:54 -07001251 * @page: Page defining the wait queue of interest
1252 * @waiter: Waiter to add to the queue
David Howells385e1ca5f2009-04-03 16:42:39 +01001253 *
1254 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1255 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001256void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
David Howells385e1ca5f2009-04-03 16:42:39 +01001257{
1258 wait_queue_head_t *q = page_waitqueue(page);
1259 unsigned long flags;
1260
1261 spin_lock_irqsave(&q->lock, flags);
Linus Torvalds9c3a8152017-08-28 16:45:40 -07001262 __add_wait_queue_entry_tail(q, waiter);
Nicholas Piggin62906022016-12-25 13:00:30 +10001263 SetPageWaiters(page);
David Howells385e1ca5f2009-04-03 16:42:39 +01001264 spin_unlock_irqrestore(&q->lock, flags);
1265}
1266EXPORT_SYMBOL_GPL(add_page_wait_queue);
1267
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001268#ifndef clear_bit_unlock_is_negative_byte
1269
1270/*
1271 * PG_waiters is the high bit in the same byte as PG_lock.
1272 *
1273 * On x86 (and on many other architectures), we can clear PG_lock and
1274 * test the sign bit at the same time. But if the architecture does
1275 * not support that special operation, we just do this all by hand
1276 * instead.
1277 *
1278 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1279 * being cleared, but a memory barrier should be unneccssary since it is
1280 * in the same byte as PG_locked.
1281 */
1282static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1283{
1284 clear_bit_unlock(nr, mem);
1285 /* smp_mb__after_atomic(); */
Olof Johansson98473f92016-12-29 14:16:07 -08001286 return test_bit(PG_waiters, mem);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001287}
1288
1289#endif
1290
David Howells385e1ca5f2009-04-03 16:42:39 +01001291/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001292 * unlock_page - unlock a locked page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001293 * @page: the page
1294 *
1295 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1296 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
Masanari Iidada3dae52014-09-09 01:27:23 +09001297 * mechanism between PageLocked pages and PageWriteback pages is shared.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001298 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1299 *
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001300 * Note that this depends on PG_waiters being the sign bit in the byte
1301 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1302 * clear the PG_locked bit and test PG_waiters at the same time fairly
1303 * portably (architectures that do LL/SC can test any bit, while x86 can
1304 * test the sign bit).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001305 */
Harvey Harrison920c7a52008-02-04 22:29:26 -08001306void unlock_page(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001307{
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001308 BUILD_BUG_ON(PG_waiters != 7);
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -08001309 page = compound_head(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001310 VM_BUG_ON_PAGE(!PageLocked(page), page);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001311 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1312 wake_up_page_bit(page, PG_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001313}
1314EXPORT_SYMBOL(unlock_page);
1315
Randy Dunlap485bb992006-06-23 02:03:49 -07001316/**
1317 * end_page_writeback - end writeback against a page
1318 * @page: the page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001319 */
1320void end_page_writeback(struct page *page)
1321{
Mel Gorman888cf2d2014-06-04 16:10:34 -07001322 /*
1323 * TestClearPageReclaim could be used here but it is an atomic
1324 * operation and overkill in this particular case. Failing to
1325 * shuffle a page marked for immediate reclaim is too mild to
1326 * justify taking an atomic operation penalty at the end of
1327 * ever page writeback.
1328 */
1329 if (PageReclaim(page)) {
1330 ClearPageReclaim(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001331 rotate_reclaimable_page(page);
Mel Gorman888cf2d2014-06-04 16:10:34 -07001332 }
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001333
1334 if (!test_clear_page_writeback(page))
1335 BUG();
1336
Peter Zijlstra4e857c52014-03-17 18:06:10 +01001337 smp_mb__after_atomic();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001338 wake_up_page(page, PG_writeback);
1339}
1340EXPORT_SYMBOL(end_page_writeback);
1341
Matthew Wilcox57d99842014-06-04 16:07:45 -07001342/*
1343 * After completing I/O on a page, call this routine to update the page
1344 * flags appropriately
1345 */
Jens Axboec11f0c02016-08-05 08:11:04 -06001346void page_endio(struct page *page, bool is_write, int err)
Matthew Wilcox57d99842014-06-04 16:07:45 -07001347{
Jens Axboec11f0c02016-08-05 08:11:04 -06001348 if (!is_write) {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001349 if (!err) {
1350 SetPageUptodate(page);
1351 } else {
1352 ClearPageUptodate(page);
1353 SetPageError(page);
1354 }
1355 unlock_page(page);
Mike Christieabf54542016-08-04 14:23:34 -06001356 } else {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001357 if (err) {
Minchan Kimdd8416c2017-02-24 14:59:59 -08001358 struct address_space *mapping;
1359
Matthew Wilcox57d99842014-06-04 16:07:45 -07001360 SetPageError(page);
Minchan Kimdd8416c2017-02-24 14:59:59 -08001361 mapping = page_mapping(page);
1362 if (mapping)
1363 mapping_set_error(mapping, err);
Matthew Wilcox57d99842014-06-04 16:07:45 -07001364 }
1365 end_page_writeback(page);
1366 }
1367}
1368EXPORT_SYMBOL_GPL(page_endio);
1369
Randy Dunlap485bb992006-06-23 02:03:49 -07001370/**
1371 * __lock_page - get a lock on the page, assuming we need to sleep to get it
Randy Dunlap87066752017-02-22 15:44:44 -08001372 * @__page: the page to lock
Linus Torvalds1da177e2005-04-16 15:20:36 -07001373 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001374void __lock_page(struct page *__page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001375{
Nicholas Piggin62906022016-12-25 13:00:30 +10001376 struct page *page = compound_head(__page);
1377 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001378 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1379 EXCLUSIVE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001380}
1381EXPORT_SYMBOL(__lock_page);
1382
Nicholas Piggin62906022016-12-25 13:00:30 +10001383int __lock_page_killable(struct page *__page)
Matthew Wilcox2687a352007-12-06 11:18:49 -05001384{
Nicholas Piggin62906022016-12-25 13:00:30 +10001385 struct page *page = compound_head(__page);
1386 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001387 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1388 EXCLUSIVE);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001389}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +03001390EXPORT_SYMBOL_GPL(__lock_page_killable);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001391
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001392/*
1393 * Return values:
1394 * 1 - page is locked; mmap_sem is still held.
1395 * 0 - page is not locked.
1396 * mmap_sem has been released (up_read()), unless flags had both
1397 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1398 * which case mmap_sem is still held.
1399 *
1400 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1401 * with the page locked and the mmap_sem unperturbed.
1402 */
Michel Lespinassed065bd82010-10-26 14:21:57 -07001403int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1404 unsigned int flags)
1405{
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001406 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1407 /*
1408 * CAUTION! In this case, mmap_sem is not released
1409 * even though return 0.
1410 */
1411 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1412 return 0;
1413
1414 up_read(&mm->mmap_sem);
1415 if (flags & FAULT_FLAG_KILLABLE)
1416 wait_on_page_locked_killable(page);
1417 else
Gleb Natapov318b2752011-03-22 16:30:51 -07001418 wait_on_page_locked(page);
Michel Lespinassed065bd82010-10-26 14:21:57 -07001419 return 0;
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001420 } else {
1421 if (flags & FAULT_FLAG_KILLABLE) {
1422 int ret;
1423
1424 ret = __lock_page_killable(page);
1425 if (ret) {
1426 up_read(&mm->mmap_sem);
1427 return 0;
1428 }
1429 } else
1430 __lock_page(page);
1431 return 1;
Michel Lespinassed065bd82010-10-26 14:21:57 -07001432 }
1433}
1434
Randy Dunlap485bb992006-06-23 02:03:49 -07001435/**
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001436 * page_cache_next_miss() - Find the next gap in the page cache.
1437 * @mapping: Mapping.
1438 * @index: Index.
1439 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001440 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001441 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1442 * gap with the lowest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001443 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001444 * This function may be called under the rcu_read_lock. However, this will
1445 * not atomically search a snapshot of the cache at a single point in time.
1446 * For example, if a gap is created at index 5, then subsequently a gap is
1447 * created at index 10, page_cache_next_miss covering both indices may
1448 * return 10 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001449 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001450 * Return: The index of the gap if found, otherwise an index outside the
1451 * range specified (in which case 'return - index >= max_scan' will be true).
1452 * In the rare case of index wrap-around, 0 will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001453 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001454pgoff_t page_cache_next_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001455 pgoff_t index, unsigned long max_scan)
1456{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001457 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001458
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001459 while (max_scan--) {
1460 void *entry = xas_next(&xas);
1461 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001462 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001463 if (xas.xa_index == 0)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001464 break;
1465 }
1466
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001467 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001468}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001469EXPORT_SYMBOL(page_cache_next_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001470
1471/**
Laurent Dufour2346a562019-05-13 17:21:29 -07001472 * page_cache_prev_miss() - Find the previous gap in the page cache.
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001473 * @mapping: Mapping.
1474 * @index: Index.
1475 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001476 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001477 * Search the range [max(index - max_scan + 1, 0), index] for the
1478 * gap with the highest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001479 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001480 * This function may be called under the rcu_read_lock. However, this will
1481 * not atomically search a snapshot of the cache at a single point in time.
1482 * For example, if a gap is created at index 10, then subsequently a gap is
1483 * created at index 5, page_cache_prev_miss() covering both indices may
1484 * return 5 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001485 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001486 * Return: The index of the gap if found, otherwise an index outside the
1487 * range specified (in which case 'index - return >= max_scan' will be true).
1488 * In the rare case of wrap-around, ULONG_MAX will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001489 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001490pgoff_t page_cache_prev_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001491 pgoff_t index, unsigned long max_scan)
1492{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001493 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001494
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001495 while (max_scan--) {
1496 void *entry = xas_prev(&xas);
1497 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001498 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001499 if (xas.xa_index == ULONG_MAX)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001500 break;
1501 }
1502
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001503 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001504}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001505EXPORT_SYMBOL(page_cache_prev_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001506
1507/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001508 * find_get_entry - find and get a page cache entry
Randy Dunlap485bb992006-06-23 02:03:49 -07001509 * @mapping: the address_space to search
Johannes Weiner0cd61442014-04-03 14:47:46 -07001510 * @offset: the page cache index
Randy Dunlap485bb992006-06-23 02:03:49 -07001511 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001512 * Looks up the page cache slot at @mapping & @offset. If there is a
1513 * page cache page, it is returned with an increased refcount.
1514 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001515 * If the slot holds a shadow entry of a previously evicted page, or a
1516 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001517 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001518 * Return: the found page or shadow entry, %NULL if nothing is found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001519 */
Johannes Weiner0cd61442014-04-03 14:47:46 -07001520struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001521{
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001522 XA_STATE(xas, &mapping->i_pages, offset);
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001523 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001524
Nick Piggina60637c2008-07-25 19:45:31 -07001525 rcu_read_lock();
1526repeat:
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001527 xas_reset(&xas);
1528 page = xas_load(&xas);
1529 if (xas_retry(&xas, page))
1530 goto repeat;
1531 /*
1532 * A shadow entry of a recently evicted page, or a swap entry from
1533 * shmem/tmpfs. Return it without attempting to raise page count.
1534 */
1535 if (!page || xa_is_value(page))
1536 goto out;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001537
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001538 if (!page_cache_get_speculative(page))
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001539 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001540
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001541 /*
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001542 * Has the page moved or been split?
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001543 * This is part of the lockless pagecache protocol. See
1544 * include/linux/pagemap.h for details.
1545 */
1546 if (unlikely(page != xas_reload(&xas))) {
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001547 put_page(page);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001548 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001549 }
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001550 page = find_subpage(page, offset);
Nick Piggin27d20fd2010-11-11 14:05:19 -08001551out:
Nick Piggina60637c2008-07-25 19:45:31 -07001552 rcu_read_unlock();
1553
Linus Torvalds1da177e2005-04-16 15:20:36 -07001554 return page;
1555}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001556EXPORT_SYMBOL(find_get_entry);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001557
Randy Dunlap485bb992006-06-23 02:03:49 -07001558/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001559 * find_lock_entry - locate, pin and lock a page cache entry
1560 * @mapping: the address_space to search
1561 * @offset: the page cache index
1562 *
1563 * Looks up the page cache slot at @mapping & @offset. If there is a
1564 * page cache page, it is returned locked and with an increased
1565 * refcount.
1566 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001567 * If the slot holds a shadow entry of a previously evicted page, or a
1568 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001569 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001570 * find_lock_entry() may sleep.
Mike Rapoporta862f682019-03-05 15:48:42 -08001571 *
1572 * Return: the found page or shadow entry, %NULL if nothing is found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001573 */
1574struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001575{
1576 struct page *page;
1577
Linus Torvalds1da177e2005-04-16 15:20:36 -07001578repeat:
Johannes Weiner0cd61442014-04-03 14:47:46 -07001579 page = find_get_entry(mapping, offset);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001580 if (page && !xa_is_value(page)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001581 lock_page(page);
1582 /* Has the page been truncated? */
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001583 if (unlikely(page_mapping(page) != mapping)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001584 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001585 put_page(page);
Nick Piggina60637c2008-07-25 19:45:31 -07001586 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001587 }
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001588 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001589 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001590 return page;
1591}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001592EXPORT_SYMBOL(find_lock_entry);
1593
1594/**
Mel Gorman2457aec2014-06-04 16:10:31 -07001595 * pagecache_get_page - find and get a page reference
Johannes Weiner0cd61442014-04-03 14:47:46 -07001596 * @mapping: the address_space to search
1597 * @offset: the page index
Mel Gorman2457aec2014-06-04 16:10:31 -07001598 * @fgp_flags: PCG flags
Michal Hocko45f87de2014-12-29 20:30:35 +01001599 * @gfp_mask: gfp mask to use for the page cache data page allocation
Johannes Weiner0cd61442014-04-03 14:47:46 -07001600 *
Mel Gorman2457aec2014-06-04 16:10:31 -07001601 * Looks up the page cache slot at @mapping & @offset.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001602 *
Randy Dunlap75325182014-07-30 16:08:37 -07001603 * PCG flags modify how the page is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001604 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -03001605 * @fgp_flags can be:
1606 *
1607 * - FGP_ACCESSED: the page will be marked accessed
1608 * - FGP_LOCK: Page is return locked
1609 * - FGP_CREAT: If page is not present then a new page is allocated using
1610 * @gfp_mask and added to the page cache and the VM's LRU
1611 * list. The page is returned locked and with an increased
Mike Rapoporta862f682019-03-05 15:48:42 -08001612 * refcount.
Josef Bacika75d4c32019-03-13 11:44:14 -07001613 * - FGP_FOR_MMAP: Similar to FGP_CREAT, only we want to allow the caller to do
1614 * its own locking dance if the page is already in cache, or unlock the page
1615 * before returning if we had to add the page to pagecache.
Mel Gorman2457aec2014-06-04 16:10:31 -07001616 *
1617 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1618 * if the GFP flags specified for FGP_CREAT are atomic.
1619 *
1620 * If there is a page cache page, it is returned with an increased refcount.
Mike Rapoporta862f682019-03-05 15:48:42 -08001621 *
1622 * Return: the found page or %NULL otherwise.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001623 */
Mel Gorman2457aec2014-06-04 16:10:31 -07001624struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
Michal Hocko45f87de2014-12-29 20:30:35 +01001625 int fgp_flags, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001626{
Nick Piggineb2be182007-10-16 01:24:57 -07001627 struct page *page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001628
Linus Torvalds1da177e2005-04-16 15:20:36 -07001629repeat:
Mel Gorman2457aec2014-06-04 16:10:31 -07001630 page = find_get_entry(mapping, offset);
Matthew Wilcox3159f942017-11-03 13:30:42 -04001631 if (xa_is_value(page))
Mel Gorman2457aec2014-06-04 16:10:31 -07001632 page = NULL;
1633 if (!page)
1634 goto no_page;
1635
1636 if (fgp_flags & FGP_LOCK) {
1637 if (fgp_flags & FGP_NOWAIT) {
1638 if (!trylock_page(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001639 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001640 return NULL;
1641 }
1642 } else {
1643 lock_page(page);
1644 }
1645
1646 /* Has the page been truncated? */
1647 if (unlikely(page->mapping != mapping)) {
1648 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001649 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001650 goto repeat;
1651 }
1652 VM_BUG_ON_PAGE(page->index != offset, page);
1653 }
1654
Kirill Tkhaic16eb002018-12-28 00:37:35 -08001655 if (fgp_flags & FGP_ACCESSED)
Mel Gorman2457aec2014-06-04 16:10:31 -07001656 mark_page_accessed(page);
1657
1658no_page:
1659 if (!page && (fgp_flags & FGP_CREAT)) {
1660 int err;
1661 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
Michal Hocko45f87de2014-12-29 20:30:35 +01001662 gfp_mask |= __GFP_WRITE;
1663 if (fgp_flags & FGP_NOFS)
1664 gfp_mask &= ~__GFP_FS;
Mel Gorman2457aec2014-06-04 16:10:31 -07001665
Michal Hocko45f87de2014-12-29 20:30:35 +01001666 page = __page_cache_alloc(gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001667 if (!page)
1668 return NULL;
Mel Gorman2457aec2014-06-04 16:10:31 -07001669
Josef Bacika75d4c32019-03-13 11:44:14 -07001670 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
Mel Gorman2457aec2014-06-04 16:10:31 -07001671 fgp_flags |= FGP_LOCK;
1672
Hugh Dickinseb39d612014-08-06 16:06:43 -07001673 /* Init accessed so avoid atomic mark_page_accessed later */
Mel Gorman2457aec2014-06-04 16:10:31 -07001674 if (fgp_flags & FGP_ACCESSED)
Hugh Dickinseb39d612014-08-06 16:06:43 -07001675 __SetPageReferenced(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001676
Matthew Wilcoxabc1be12018-04-20 14:56:20 -07001677 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001678 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001679 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07001680 page = NULL;
1681 if (err == -EEXIST)
1682 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001683 }
Josef Bacika75d4c32019-03-13 11:44:14 -07001684
1685 /*
1686 * add_to_page_cache_lru locks the page, and for mmap we expect
1687 * an unlocked page.
1688 */
1689 if (page && (fgp_flags & FGP_FOR_MMAP))
1690 unlock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001691 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001692
Linus Torvalds1da177e2005-04-16 15:20:36 -07001693 return page;
1694}
Mel Gorman2457aec2014-06-04 16:10:31 -07001695EXPORT_SYMBOL(pagecache_get_page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001696
1697/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001698 * find_get_entries - gang pagecache lookup
1699 * @mapping: The address_space to search
1700 * @start: The starting page cache index
1701 * @nr_entries: The maximum number of entries
1702 * @entries: Where the resulting entries are placed
1703 * @indices: The cache indices corresponding to the entries in @entries
1704 *
1705 * find_get_entries() will search for and return a group of up to
1706 * @nr_entries entries in the mapping. The entries are placed at
1707 * @entries. find_get_entries() takes a reference against any actual
1708 * pages it returns.
1709 *
1710 * The search returns a group of mapping-contiguous page cache entries
1711 * with ascending indexes. There may be holes in the indices due to
1712 * not-present pages.
1713 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001714 * Any shadow entries of evicted pages, or swap entries from
1715 * shmem/tmpfs, are included in the returned array.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001716 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001717 * Return: the number of pages and shadow entries which were found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001718 */
1719unsigned find_get_entries(struct address_space *mapping,
1720 pgoff_t start, unsigned int nr_entries,
1721 struct page **entries, pgoff_t *indices)
1722{
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001723 XA_STATE(xas, &mapping->i_pages, start);
1724 struct page *page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001725 unsigned int ret = 0;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001726
1727 if (!nr_entries)
1728 return 0;
1729
1730 rcu_read_lock();
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001731 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001732 if (xas_retry(&xas, page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001733 continue;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001734 /*
1735 * A shadow entry of a recently evicted page, a swap
1736 * entry from shmem/tmpfs or a DAX entry. Return it
1737 * without attempting to raise page count.
1738 */
1739 if (xa_is_value(page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001740 goto export;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001741
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001742 if (!page_cache_get_speculative(page))
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001743 goto retry;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001744
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001745 /* Has the page moved or been split? */
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001746 if (unlikely(page != xas_reload(&xas)))
1747 goto put_page;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001748 page = find_subpage(page, xas.xa_index);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001749
Johannes Weiner0cd61442014-04-03 14:47:46 -07001750export:
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001751 indices[ret] = xas.xa_index;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001752 entries[ret] = page;
1753 if (++ret == nr_entries)
1754 break;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001755 continue;
1756put_page:
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001757 put_page(page);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001758retry:
1759 xas_reset(&xas);
Johannes Weiner0cd61442014-04-03 14:47:46 -07001760 }
1761 rcu_read_unlock();
1762 return ret;
1763}
1764
1765/**
Jan Karab947cee2017-09-06 16:21:21 -07001766 * find_get_pages_range - gang pagecache lookup
Linus Torvalds1da177e2005-04-16 15:20:36 -07001767 * @mapping: The address_space to search
1768 * @start: The starting page index
Jan Karab947cee2017-09-06 16:21:21 -07001769 * @end: The final page index (inclusive)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001770 * @nr_pages: The maximum number of pages
1771 * @pages: Where the resulting pages are placed
1772 *
Jan Karab947cee2017-09-06 16:21:21 -07001773 * find_get_pages_range() will search for and return a group of up to @nr_pages
1774 * pages in the mapping starting at index @start and up to index @end
1775 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1776 * a reference against the returned pages.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001777 *
1778 * The search returns a group of mapping-contiguous pages with ascending
1779 * indexes. There may be holes in the indices due to not-present pages.
Jan Karad72dc8a2017-09-06 16:21:18 -07001780 * We also update @start to index the next page for the traversal.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001781 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001782 * Return: the number of pages which were found. If this number is
1783 * smaller than @nr_pages, the end of specified range has been
Jan Karab947cee2017-09-06 16:21:21 -07001784 * reached.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001785 */
Jan Karab947cee2017-09-06 16:21:21 -07001786unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1787 pgoff_t end, unsigned int nr_pages,
1788 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001789{
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001790 XA_STATE(xas, &mapping->i_pages, *start);
1791 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001792 unsigned ret = 0;
1793
1794 if (unlikely(!nr_pages))
1795 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001796
Nick Piggina60637c2008-07-25 19:45:31 -07001797 rcu_read_lock();
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001798 xas_for_each(&xas, page, end) {
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001799 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001800 continue;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001801 /* Skip over shadow, swap and DAX entries */
1802 if (xa_is_value(page))
Hugh Dickins8079b1c2011-08-03 16:21:28 -07001803 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001804
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001805 if (!page_cache_get_speculative(page))
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001806 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001807
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001808 /* Has the page moved or been split? */
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001809 if (unlikely(page != xas_reload(&xas)))
1810 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001811
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001812 pages[ret] = find_subpage(page, xas.xa_index);
Jan Karab947cee2017-09-06 16:21:21 -07001813 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001814 *start = xas.xa_index + 1;
Jan Karab947cee2017-09-06 16:21:21 -07001815 goto out;
1816 }
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001817 continue;
1818put_page:
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001819 put_page(page);
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001820retry:
1821 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001822 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001823
Jan Karab947cee2017-09-06 16:21:21 -07001824 /*
1825 * We come here when there is no page beyond @end. We take care to not
1826 * overflow the index @start as it confuses some of the callers. This
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001827 * breaks the iteration when there is a page at index -1 but that is
Jan Karab947cee2017-09-06 16:21:21 -07001828 * already broken anyway.
1829 */
1830 if (end == (pgoff_t)-1)
1831 *start = (pgoff_t)-1;
1832 else
1833 *start = end + 1;
1834out:
Nick Piggina60637c2008-07-25 19:45:31 -07001835 rcu_read_unlock();
Jan Karad72dc8a2017-09-06 16:21:18 -07001836
Linus Torvalds1da177e2005-04-16 15:20:36 -07001837 return ret;
1838}
1839
Jens Axboeebf43502006-04-27 08:46:01 +02001840/**
1841 * find_get_pages_contig - gang contiguous pagecache lookup
1842 * @mapping: The address_space to search
1843 * @index: The starting page index
1844 * @nr_pages: The maximum number of pages
1845 * @pages: Where the resulting pages are placed
1846 *
1847 * find_get_pages_contig() works exactly like find_get_pages(), except
1848 * that the returned number of pages are guaranteed to be contiguous.
1849 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001850 * Return: the number of pages which were found.
Jens Axboeebf43502006-04-27 08:46:01 +02001851 */
1852unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1853 unsigned int nr_pages, struct page **pages)
1854{
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001855 XA_STATE(xas, &mapping->i_pages, index);
1856 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001857 unsigned int ret = 0;
1858
1859 if (unlikely(!nr_pages))
1860 return 0;
Jens Axboeebf43502006-04-27 08:46:01 +02001861
Nick Piggina60637c2008-07-25 19:45:31 -07001862 rcu_read_lock();
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001863 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001864 if (xas_retry(&xas, page))
1865 continue;
1866 /*
1867 * If the entry has been swapped out, we can stop looking.
1868 * No current caller is looking for DAX entries.
1869 */
1870 if (xa_is_value(page))
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001871 break;
Hugh Dickins9d8aa4e2011-03-22 16:33:06 -07001872
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001873 if (!page_cache_get_speculative(page))
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001874 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001875
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001876 /* Has the page moved or been split? */
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001877 if (unlikely(page != xas_reload(&xas)))
1878 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001879
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001880 pages[ret] = find_subpage(page, xas.xa_index);
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001881 if (++ret == nr_pages)
1882 break;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001883 continue;
1884put_page:
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001885 put_page(page);
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001886retry:
1887 xas_reset(&xas);
Jens Axboeebf43502006-04-27 08:46:01 +02001888 }
Nick Piggina60637c2008-07-25 19:45:31 -07001889 rcu_read_unlock();
1890 return ret;
Jens Axboeebf43502006-04-27 08:46:01 +02001891}
David Howellsef71c152007-05-09 02:33:44 -07001892EXPORT_SYMBOL(find_get_pages_contig);
Jens Axboeebf43502006-04-27 08:46:01 +02001893
Randy Dunlap485bb992006-06-23 02:03:49 -07001894/**
Jan Kara72b045a2017-11-15 17:34:33 -08001895 * find_get_pages_range_tag - find and return pages in given range matching @tag
Randy Dunlap485bb992006-06-23 02:03:49 -07001896 * @mapping: the address_space to search
1897 * @index: the starting page index
Jan Kara72b045a2017-11-15 17:34:33 -08001898 * @end: The final page index (inclusive)
Randy Dunlap485bb992006-06-23 02:03:49 -07001899 * @tag: the tag index
1900 * @nr_pages: the maximum number of pages
1901 * @pages: where the resulting pages are placed
1902 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001903 * Like find_get_pages, except we only return pages which are tagged with
Randy Dunlap485bb992006-06-23 02:03:49 -07001904 * @tag. We update @index to index the next page for the traversal.
Mike Rapoporta862f682019-03-05 15:48:42 -08001905 *
1906 * Return: the number of pages which were found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001907 */
Jan Kara72b045a2017-11-15 17:34:33 -08001908unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001909 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
Jan Kara72b045a2017-11-15 17:34:33 -08001910 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001911{
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001912 XA_STATE(xas, &mapping->i_pages, *index);
1913 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001914 unsigned ret = 0;
1915
1916 if (unlikely(!nr_pages))
1917 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001918
Nick Piggina60637c2008-07-25 19:45:31 -07001919 rcu_read_lock();
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001920 xas_for_each_marked(&xas, page, end, tag) {
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001921 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001922 continue;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001923 /*
1924 * Shadow entries should never be tagged, but this iteration
1925 * is lockless so there is a window for page reclaim to evict
1926 * a page we saw tagged. Skip over it.
1927 */
1928 if (xa_is_value(page))
Johannes Weiner139b6a62014-05-06 12:50:05 -07001929 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001930
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001931 if (!page_cache_get_speculative(page))
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001932 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001933
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001934 /* Has the page moved or been split? */
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001935 if (unlikely(page != xas_reload(&xas)))
1936 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001937
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001938 pages[ret] = find_subpage(page, xas.xa_index);
Jan Kara72b045a2017-11-15 17:34:33 -08001939 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001940 *index = xas.xa_index + 1;
Jan Kara72b045a2017-11-15 17:34:33 -08001941 goto out;
1942 }
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001943 continue;
1944put_page:
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07001945 put_page(page);
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001946retry:
1947 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001948 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001949
Jan Kara72b045a2017-11-15 17:34:33 -08001950 /*
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001951 * We come here when we got to @end. We take care to not overflow the
Jan Kara72b045a2017-11-15 17:34:33 -08001952 * index @index as it confuses some of the callers. This breaks the
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001953 * iteration when there is a page at index -1 but that is already
1954 * broken anyway.
Jan Kara72b045a2017-11-15 17:34:33 -08001955 */
1956 if (end == (pgoff_t)-1)
1957 *index = (pgoff_t)-1;
1958 else
1959 *index = end + 1;
1960out:
Nick Piggina60637c2008-07-25 19:45:31 -07001961 rcu_read_unlock();
1962
Linus Torvalds1da177e2005-04-16 15:20:36 -07001963 return ret;
1964}
Jan Kara72b045a2017-11-15 17:34:33 -08001965EXPORT_SYMBOL(find_get_pages_range_tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001966
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001967/*
1968 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1969 * a _large_ part of the i/o request. Imagine the worst scenario:
1970 *
1971 * ---R__________________________________________B__________
1972 * ^ reading here ^ bad block(assume 4k)
1973 *
1974 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1975 * => failing the whole request => read(R) => read(R+1) =>
1976 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1977 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1978 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1979 *
1980 * It is going insane. Fix it by quickly scaling down the readahead size.
1981 */
1982static void shrink_readahead_size_eio(struct file *filp,
1983 struct file_ra_state *ra)
1984{
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001985 ra->ra_pages /= 4;
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001986}
1987
Randy Dunlap485bb992006-06-23 02:03:49 -07001988/**
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02001989 * generic_file_buffered_read - generic file read routine
1990 * @iocb: the iocb to read
Al Viro6e58e792014-02-03 17:07:03 -05001991 * @iter: data destination
1992 * @written: already copied
Randy Dunlap485bb992006-06-23 02:03:49 -07001993 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001994 * This is a generic file read routine, and uses the
Randy Dunlap485bb992006-06-23 02:03:49 -07001995 * mapping->a_ops->readpage() function for the actual low-level stuff.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001996 *
1997 * This is really ugly. But the goto's actually try to clarify some
1998 * of the logic when it comes to error handling etc.
Mike Rapoporta862f682019-03-05 15:48:42 -08001999 *
2000 * Return:
2001 * * total number of bytes copied, including those the were already @written
2002 * * negative error code if nothing was copied
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003 */
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002004static ssize_t generic_file_buffered_read(struct kiocb *iocb,
Al Viro6e58e792014-02-03 17:07:03 -05002005 struct iov_iter *iter, ssize_t written)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002006{
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002007 struct file *filp = iocb->ki_filp;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002008 struct address_space *mapping = filp->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002009 struct inode *inode = mapping->host;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002010 struct file_ra_state *ra = &filp->f_ra;
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002011 loff_t *ppos = &iocb->ki_pos;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002012 pgoff_t index;
2013 pgoff_t last_index;
2014 pgoff_t prev_index;
2015 unsigned long offset; /* offset into pagecache page */
Jan Karaec0f1632007-05-06 14:49:25 -07002016 unsigned int prev_offset;
Al Viro6e58e792014-02-03 17:07:03 -05002017 int error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002018
Wei Fangc2a97372016-10-07 17:01:52 -07002019 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
Linus Torvaldsd05c5f72016-12-14 12:45:25 -08002020 return 0;
Wei Fangc2a97372016-10-07 17:01:52 -07002021 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2022
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002023 index = *ppos >> PAGE_SHIFT;
2024 prev_index = ra->prev_pos >> PAGE_SHIFT;
2025 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2026 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2027 offset = *ppos & ~PAGE_MASK;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002028
Linus Torvalds1da177e2005-04-16 15:20:36 -07002029 for (;;) {
2030 struct page *page;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002031 pgoff_t end_index;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002032 loff_t isize;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002033 unsigned long nr, ret;
2034
Linus Torvalds1da177e2005-04-16 15:20:36 -07002035 cond_resched();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002036find_page:
Michal Hocko5abf1862017-02-03 13:13:29 -08002037 if (fatal_signal_pending(current)) {
2038 error = -EINTR;
2039 goto out;
2040 }
2041
Linus Torvalds1da177e2005-04-16 15:20:36 -07002042 page = find_get_page(mapping, index);
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002043 if (!page) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002044 if (iocb->ki_flags & IOCB_NOWAIT)
2045 goto would_block;
Rusty Russellcf914a72007-07-19 01:48:08 -07002046 page_cache_sync_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002047 ra, filp,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002048 index, last_index - index);
2049 page = find_get_page(mapping, index);
2050 if (unlikely(page == NULL))
2051 goto no_cached_page;
2052 }
2053 if (PageReadahead(page)) {
Rusty Russellcf914a72007-07-19 01:48:08 -07002054 page_cache_async_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002055 ra, filp, page,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002056 index, last_index - index);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002057 }
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002058 if (!PageUptodate(page)) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002059 if (iocb->ki_flags & IOCB_NOWAIT) {
2060 put_page(page);
2061 goto would_block;
2062 }
2063
Mel Gormanebded022016-03-15 14:55:39 -07002064 /*
2065 * See comment in do_read_cache_page on why
2066 * wait_on_page_locked is used to avoid unnecessarily
2067 * serialisations and why it's safe.
2068 */
Bart Van Asschec4b209a2016-10-07 16:58:33 -07002069 error = wait_on_page_locked_killable(page);
2070 if (unlikely(error))
2071 goto readpage_error;
Mel Gormanebded022016-03-15 14:55:39 -07002072 if (PageUptodate(page))
2073 goto page_ok;
2074
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002075 if (inode->i_blkbits == PAGE_SHIFT ||
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002076 !mapping->a_ops->is_partially_uptodate)
2077 goto page_not_up_to_date;
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002078 /* pipes can't handle partially uptodate pages */
David Howells00e23702018-10-22 13:07:28 +01002079 if (unlikely(iov_iter_is_pipe(iter)))
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002080 goto page_not_up_to_date;
Nick Piggin529ae9a2008-08-02 12:01:03 +02002081 if (!trylock_page(page))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002082 goto page_not_up_to_date;
Dave Hansen8d056cb2010-11-11 14:05:15 -08002083 /* Did it get truncated before we got the lock? */
2084 if (!page->mapping)
2085 goto page_not_up_to_date_locked;
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002086 if (!mapping->a_ops->is_partially_uptodate(page,
Al Viro6e58e792014-02-03 17:07:03 -05002087 offset, iter->count))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002088 goto page_not_up_to_date_locked;
2089 unlock_page(page);
2090 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002091page_ok:
NeilBrowna32ea1e2007-07-17 04:03:04 -07002092 /*
2093 * i_size must be checked after we know the page is Uptodate.
2094 *
2095 * Checking i_size after the check allows us to calculate
2096 * the correct value for "nr", which means the zero-filled
2097 * part of the page is not copied back to userspace (unless
2098 * another truncate extends the file - this is desired though).
2099 */
2100
2101 isize = i_size_read(inode);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002102 end_index = (isize - 1) >> PAGE_SHIFT;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002103 if (unlikely(!isize || index > end_index)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002104 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002105 goto out;
2106 }
2107
2108 /* nr is the maximum number of bytes to copy from this page */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002109 nr = PAGE_SIZE;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002110 if (index == end_index) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002111 nr = ((isize - 1) & ~PAGE_MASK) + 1;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002112 if (nr <= offset) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002113 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002114 goto out;
2115 }
2116 }
2117 nr = nr - offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002118
2119 /* If users can be writing to this page using arbitrary
2120 * virtual addresses, take care about potential aliasing
2121 * before reading the page on the kernel side.
2122 */
2123 if (mapping_writably_mapped(mapping))
2124 flush_dcache_page(page);
2125
2126 /*
Jan Karaec0f1632007-05-06 14:49:25 -07002127 * When a sequential read accesses a page several times,
2128 * only mark it as accessed the first time.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002129 */
Jan Karaec0f1632007-05-06 14:49:25 -07002130 if (prev_index != index || offset != prev_offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002131 mark_page_accessed(page);
2132 prev_index = index;
2133
2134 /*
2135 * Ok, we have the page, and it's up-to-date, so
2136 * now we can copy it to user space...
Linus Torvalds1da177e2005-04-16 15:20:36 -07002137 */
Al Viro6e58e792014-02-03 17:07:03 -05002138
2139 ret = copy_page_to_iter(page, offset, nr, iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002140 offset += ret;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002141 index += offset >> PAGE_SHIFT;
2142 offset &= ~PAGE_MASK;
Jan Kara6ce745e2007-05-06 14:49:26 -07002143 prev_offset = offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002144
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002145 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002146 written += ret;
2147 if (!iov_iter_count(iter))
2148 goto out;
2149 if (ret < nr) {
2150 error = -EFAULT;
2151 goto out;
2152 }
2153 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002154
2155page_not_up_to_date:
2156 /* Get exclusive access to the page ... */
Oleg Nesterov85462322008-06-08 21:20:43 +04002157 error = lock_page_killable(page);
2158 if (unlikely(error))
2159 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002160
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002161page_not_up_to_date_locked:
Nick Pigginda6052f2006-09-25 23:31:35 -07002162 /* Did it get truncated before we got the lock? */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002163 if (!page->mapping) {
2164 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002165 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002166 continue;
2167 }
2168
2169 /* Did somebody else fill it already? */
2170 if (PageUptodate(page)) {
2171 unlock_page(page);
2172 goto page_ok;
2173 }
2174
2175readpage:
Jeff Moyer91803b42010-05-26 11:49:40 -04002176 /*
2177 * A previous I/O error may have been due to temporary
2178 * failures, eg. multipath errors.
2179 * PG_error will be set again if readpage fails.
2180 */
2181 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002182 /* Start the actual read. The read will unlock the page. */
2183 error = mapping->a_ops->readpage(filp, page);
2184
Zach Brown994fc28c2005-12-15 14:28:17 -08002185 if (unlikely(error)) {
2186 if (error == AOP_TRUNCATED_PAGE) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002187 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002188 error = 0;
Zach Brown994fc28c2005-12-15 14:28:17 -08002189 goto find_page;
2190 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002191 goto readpage_error;
Zach Brown994fc28c2005-12-15 14:28:17 -08002192 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002193
2194 if (!PageUptodate(page)) {
Oleg Nesterov85462322008-06-08 21:20:43 +04002195 error = lock_page_killable(page);
2196 if (unlikely(error))
2197 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002198 if (!PageUptodate(page)) {
2199 if (page->mapping == NULL) {
2200 /*
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01002201 * invalidate_mapping_pages got it
Linus Torvalds1da177e2005-04-16 15:20:36 -07002202 */
2203 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002204 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002205 goto find_page;
2206 }
2207 unlock_page(page);
Fengguang Wu7ff81072007-10-16 01:24:35 -07002208 shrink_readahead_size_eio(filp, ra);
Oleg Nesterov85462322008-06-08 21:20:43 +04002209 error = -EIO;
2210 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002211 }
2212 unlock_page(page);
2213 }
2214
Linus Torvalds1da177e2005-04-16 15:20:36 -07002215 goto page_ok;
2216
2217readpage_error:
2218 /* UHHUH! A synchronous read error occurred. Report it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002219 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002220 goto out;
2221
2222no_cached_page:
2223 /*
2224 * Ok, it wasn't cached, so we need to create a new
2225 * page..
2226 */
Mel Gorman453f85d2017-11-15 17:38:03 -08002227 page = page_cache_alloc(mapping);
Nick Piggineb2be182007-10-16 01:24:57 -07002228 if (!page) {
Al Viro6e58e792014-02-03 17:07:03 -05002229 error = -ENOMEM;
Nick Piggineb2be182007-10-16 01:24:57 -07002230 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002231 }
Michal Hocko6afdb852015-06-24 16:58:06 -07002232 error = add_to_page_cache_lru(page, mapping, index,
Michal Hockoc62d2552015-11-06 16:28:49 -08002233 mapping_gfp_constraint(mapping, GFP_KERNEL));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002234 if (error) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002235 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002236 if (error == -EEXIST) {
2237 error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002238 goto find_page;
Al Viro6e58e792014-02-03 17:07:03 -05002239 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002240 goto out;
2241 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002242 goto readpage;
2243 }
2244
Milosz Tanski3239d832017-08-29 16:13:19 +02002245would_block:
2246 error = -EAGAIN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002247out:
Fengguang Wu7ff81072007-10-16 01:24:35 -07002248 ra->prev_pos = prev_index;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002249 ra->prev_pos <<= PAGE_SHIFT;
Fengguang Wu7ff81072007-10-16 01:24:35 -07002250 ra->prev_pos |= prev_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002251
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002252 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002253 file_accessed(filp);
Al Viro6e58e792014-02-03 17:07:03 -05002254 return written ? written : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002255}
2256
Randy Dunlap485bb992006-06-23 02:03:49 -07002257/**
Al Viro6abd2322014-04-04 14:20:57 -04002258 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002259 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002260 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002261 *
Al Viro6abd2322014-04-04 14:20:57 -04002262 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002263 * that can use the page cache directly.
Mike Rapoporta862f682019-03-05 15:48:42 -08002264 * Return:
2265 * * number of bytes copied, even for partial reads
2266 * * negative error code if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002267 */
2268ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002269generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002270{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002271 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002272 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002273
2274 if (!count)
2275 goto out; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002276
Al Viro2ba48ce2015-04-09 13:52:01 -04002277 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002278 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002279 struct address_space *mapping = file->f_mapping;
2280 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002281 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002282
Linus Torvalds1da177e2005-04-16 15:20:36 -07002283 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002284 if (iocb->ki_flags & IOCB_NOWAIT) {
2285 if (filemap_range_has_page(mapping, iocb->ki_pos,
2286 iocb->ki_pos + count - 1))
2287 return -EAGAIN;
2288 } else {
2289 retval = filemap_write_and_wait_range(mapping,
2290 iocb->ki_pos,
2291 iocb->ki_pos + count - 1);
2292 if (retval < 0)
2293 goto out;
2294 }
Al Viroed978a82014-03-05 22:53:04 -05002295
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002296 file_accessed(file);
2297
Al Viro5ecda132017-04-13 14:13:36 -04002298 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002299 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002300 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002301 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002302 }
Al Viro5b47d592017-05-08 13:54:47 -04002303 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002304
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002305 /*
2306 * Btrfs can have a short DIO read if we encounter
2307 * compressed extents, so if there was an error, or if
2308 * we've already read everything we wanted to, or if
2309 * there was a short read because we hit EOF, go ahead
2310 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002311 * the rest of the read. Buffered reads will not work for
2312 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002313 */
Al Viro5ecda132017-04-13 14:13:36 -04002314 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002315 IS_DAX(inode))
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002316 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002317 }
2318
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002319 retval = generic_file_buffered_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002320out:
2321 return retval;
2322}
Al Viroed978a82014-03-05 22:53:04 -05002323EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002324
Linus Torvalds1da177e2005-04-16 15:20:36 -07002325#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002326#define MMAP_LOTSAMISS (100)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002327static struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
2328 struct file *fpin)
2329{
2330 int flags = vmf->flags;
2331
2332 if (fpin)
2333 return fpin;
2334
2335 /*
2336 * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
2337 * anything, so we only pin the file and drop the mmap_sem if only
2338 * FAULT_FLAG_ALLOW_RETRY is set.
2339 */
2340 if ((flags & (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT)) ==
2341 FAULT_FLAG_ALLOW_RETRY) {
2342 fpin = get_file(vmf->vma->vm_file);
2343 up_read(&vmf->vma->vm_mm->mmap_sem);
2344 }
2345 return fpin;
2346}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002347
Linus Torvaldsef00e082009-06-16 15:31:25 -07002348/*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002349 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_sem
2350 * @vmf - the vm_fault for this fault.
2351 * @page - the page to lock.
2352 * @fpin - the pointer to the file we may pin (or is already pinned).
2353 *
2354 * This works similar to lock_page_or_retry in that it can drop the mmap_sem.
2355 * It differs in that it actually returns the page locked if it returns 1 and 0
2356 * if it couldn't lock the page. If we did have to drop the mmap_sem then fpin
2357 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002358 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002359static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2360 struct file **fpin)
2361{
2362 if (trylock_page(page))
2363 return 1;
2364
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002365 /*
2366 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2367 * the mmap_sem still held. That's how FAULT_FLAG_RETRY_NOWAIT
2368 * is supposed to work. We have way too many special cases..
2369 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002370 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2371 return 0;
2372
2373 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2374 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2375 if (__lock_page_killable(page)) {
2376 /*
2377 * We didn't have the right flags to drop the mmap_sem,
2378 * but all fault_handlers only check for fatal signals
2379 * if we return VM_FAULT_RETRY, so we need to drop the
2380 * mmap_sem here and return 0 if we don't have a fpin.
2381 */
2382 if (*fpin == NULL)
2383 up_read(&vmf->vma->vm_mm->mmap_sem);
2384 return 0;
2385 }
2386 } else
2387 __lock_page(page);
2388 return 1;
2389}
2390
2391
2392/*
2393 * Synchronous readahead happens when we don't even find a page in the page
2394 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2395 * to drop the mmap sem we return the file that was pinned in order for us to do
2396 * that. If we didn't pin a file then we return NULL. The file that is
2397 * returned needs to be fput()'ed when we're done with it.
2398 */
2399static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002400{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002401 struct file *file = vmf->vma->vm_file;
2402 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002403 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002404 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002405 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002406
2407 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002408 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002409 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002410 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002411 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002412
Josef Bacik2a1180f2019-03-13 11:44:18 -07002413 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002414 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang7ffc59b2009-06-16 15:31:38 -07002415 page_cache_sync_readahead(mapping, ra, file, offset,
2416 ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002417 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002418 }
2419
Andi Kleen207d04b2011-05-24 17:12:29 -07002420 /* Avoid banging the cache line if not needed */
2421 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002422 ra->mmap_miss++;
2423
2424 /*
2425 * Do we miss much more than hit in this file? If so,
2426 * stop bothering with read-ahead. It will only hurt.
2427 */
2428 if (ra->mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002429 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002430
Wu Fengguangd30a1102009-06-16 15:31:30 -07002431 /*
2432 * mmap read-around
2433 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002434 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002435 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2436 ra->size = ra->ra_pages;
2437 ra->async_size = ra->ra_pages / 4;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002438 ra_submit(ra, mapping, file);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002439 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002440}
2441
2442/*
2443 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002444 * so we want to possibly extend the readahead further. We return the file that
2445 * was pinned if we have to drop the mmap_sem in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002446 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002447static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2448 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002449{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002450 struct file *file = vmf->vma->vm_file;
2451 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002452 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002453 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002454 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002455
2456 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002457 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002458 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002459 if (ra->mmap_miss > 0)
2460 ra->mmap_miss--;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002461 if (PageReadahead(page)) {
2462 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002463 page_cache_async_readahead(mapping, ra, file,
2464 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002465 }
2466 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002467}
2468
Randy Dunlap485bb992006-06-23 02:03:49 -07002469/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002470 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002471 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002472 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002473 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002474 * mapped memory region to read in file data during a page fault.
2475 *
2476 * The goto's are kind of ugly, but this streamlines the normal case of having
2477 * it in the page cache, and handles the special cases reasonably without
2478 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002479 *
2480 * vma->vm_mm->mmap_sem must be held on entry.
2481 *
2482 * If our return value has VM_FAULT_RETRY set, it's because
2483 * lock_page_or_retry() returned 0.
2484 * The mmap_sem has usually been released in this case.
2485 * See __lock_page_or_retry() for the exception.
2486 *
2487 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2488 * has not been released.
2489 *
2490 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002491 *
2492 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002493 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002494vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002495{
2496 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002497 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002498 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002499 struct address_space *mapping = file->f_mapping;
2500 struct file_ra_state *ra = &file->f_ra;
2501 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002502 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002503 pgoff_t max_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002504 struct page *page;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002505 vm_fault_t ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002506
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002507 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2508 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002509 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002510
Linus Torvalds1da177e2005-04-16 15:20:36 -07002511 /*
Johannes Weiner49426422013-10-16 13:46:59 -07002512 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07002513 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002514 page = find_get_page(mapping, offset);
Shaohua Li45cac652012-10-08 16:32:19 -07002515 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002516 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002517 * We found the page, so try async readahead before
2518 * waiting for the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002519 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002520 fpin = do_async_mmap_readahead(vmf, page);
Shaohua Li45cac652012-10-08 16:32:19 -07002521 } else if (!page) {
Linus Torvaldsef00e082009-06-16 15:31:25 -07002522 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002523 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07002524 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002525 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002526 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002527retry_find:
Josef Bacika75d4c32019-03-13 11:44:14 -07002528 page = pagecache_get_page(mapping, offset,
2529 FGP_CREAT|FGP_FOR_MMAP,
2530 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002531 if (!page) {
2532 if (fpin)
2533 goto out_retry;
Josef Bacika75d4c32019-03-13 11:44:14 -07002534 return vmf_error(-ENOMEM);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002535 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002536 }
2537
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002538 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2539 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07002540
2541 /* Did it get truncated? */
2542 if (unlikely(page->mapping != mapping)) {
2543 unlock_page(page);
2544 put_page(page);
2545 goto retry_find;
2546 }
Sasha Levin309381fea2014-01-23 15:52:54 -08002547 VM_BUG_ON_PAGE(page->index != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07002548
Linus Torvalds1da177e2005-04-16 15:20:36 -07002549 /*
Nick Piggind00806b2007-07-19 01:46:57 -07002550 * We have a locked page in the page cache, now we need to check
2551 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002552 */
Nick Piggind00806b2007-07-19 01:46:57 -07002553 if (unlikely(!PageUptodate(page)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002554 goto page_not_uptodate;
2555
Linus Torvaldsef00e082009-06-16 15:31:25 -07002556 /*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002557 * We've made it this far and we had to drop our mmap_sem, now is the
2558 * time to return to the upper layer and have it re-find the vma and
2559 * redo the fault.
2560 */
2561 if (fpin) {
2562 unlock_page(page);
2563 goto out_retry;
2564 }
2565
2566 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002567 * Found the page and have a reference on it.
2568 * We must recheck i_size under page lock.
2569 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002570 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2571 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07002572 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002573 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07002574 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07002575 }
2576
Nick Piggind0217ac2007-07-19 01:47:03 -07002577 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07002578 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002579
Linus Torvalds1da177e2005-04-16 15:20:36 -07002580page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002581 /*
2582 * Umm, take care of errors if the page isn't up-to-date.
2583 * Try to re-read it _once_. We do this synchronously,
2584 * because there really aren't any performance issues here
2585 * and we need to check for errors.
2586 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002587 ClearPageError(page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002588 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Zach Brown994fc28c2005-12-15 14:28:17 -08002589 error = mapping->a_ops->readpage(file, page);
Miklos Szeredi3ef0f722008-05-14 16:05:37 -07002590 if (!error) {
2591 wait_on_page_locked(page);
2592 if (!PageUptodate(page))
2593 error = -EIO;
2594 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002595 if (fpin)
2596 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002597 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07002598
2599 if (!error || error == AOP_TRUNCATED_PAGE)
2600 goto retry_find;
2601
2602 /* Things didn't work out. Return zero to tell the mm layer so. */
2603 shrink_readahead_size_eio(file, ra);
Nick Piggind0217ac2007-07-19 01:47:03 -07002604 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002605
2606out_retry:
2607 /*
2608 * We dropped the mmap_sem, we need to return to the fault handler to
2609 * re-find the vma and come back and find our hopefully still populated
2610 * page.
2611 */
2612 if (page)
2613 put_page(page);
2614 if (fpin)
2615 fput(fpin);
2616 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07002617}
2618EXPORT_SYMBOL(filemap_fault);
2619
Jan Kara82b0f8c2016-12-14 15:06:58 -08002620void filemap_map_pages(struct vm_fault *vmf,
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002621 pgoff_t start_pgoff, pgoff_t end_pgoff)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002622{
Jan Kara82b0f8c2016-12-14 15:06:58 -08002623 struct file *file = vmf->vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002624 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002625 pgoff_t last_pgoff = start_pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002626 unsigned long max_idx;
Matthew Wilcox070e8072018-05-17 00:08:30 -04002627 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07002628 struct page *page;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002629
2630 rcu_read_lock();
Matthew Wilcox070e8072018-05-17 00:08:30 -04002631 xas_for_each(&xas, page, end_pgoff) {
2632 if (xas_retry(&xas, page))
2633 continue;
2634 if (xa_is_value(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002635 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002636
Michal Hockoe0975b22018-12-28 00:38:36 -08002637 /*
2638 * Check for a locked page first, as a speculative
2639 * reference may adversely influence page migration.
2640 */
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07002641 if (PageLocked(page))
Michal Hockoe0975b22018-12-28 00:38:36 -08002642 goto next;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07002643 if (!page_cache_get_speculative(page))
Matthew Wilcox070e8072018-05-17 00:08:30 -04002644 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002645
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07002646 /* Has the page moved or been split? */
Matthew Wilcox070e8072018-05-17 00:08:30 -04002647 if (unlikely(page != xas_reload(&xas)))
2648 goto skip;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -07002649 page = find_subpage(page, xas.xa_index);
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002650
2651 if (!PageUptodate(page) ||
2652 PageReadahead(page) ||
2653 PageHWPoison(page))
2654 goto skip;
2655 if (!trylock_page(page))
2656 goto skip;
2657
2658 if (page->mapping != mapping || !PageUptodate(page))
2659 goto unlock;
2660
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002661 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2662 if (page->index >= max_idx)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002663 goto unlock;
2664
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002665 if (file->f_ra.mmap_miss > 0)
2666 file->f_ra.mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002667
Matthew Wilcox070e8072018-05-17 00:08:30 -04002668 vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002669 if (vmf->pte)
Matthew Wilcox070e8072018-05-17 00:08:30 -04002670 vmf->pte += xas.xa_index - last_pgoff;
2671 last_pgoff = xas.xa_index;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002672 if (alloc_set_pte(vmf, NULL, page))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002673 goto unlock;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002674 unlock_page(page);
2675 goto next;
2676unlock:
2677 unlock_page(page);
2678skip:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002679 put_page(page);
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002680next:
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002681 /* Huge page is mapped? No need to proceed. */
Jan Kara82b0f8c2016-12-14 15:06:58 -08002682 if (pmd_trans_huge(*vmf->pmd))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002683 break;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002684 }
2685 rcu_read_unlock();
2686}
2687EXPORT_SYMBOL(filemap_map_pages);
2688
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002689vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02002690{
2691 struct page *page = vmf->page;
Dave Jiang11bac802017-02-24 14:56:41 -08002692 struct inode *inode = file_inode(vmf->vma->vm_file);
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002693 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02002694
Jan Kara14da9202012-06-12 16:20:37 +02002695 sb_start_pagefault(inode->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08002696 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002697 lock_page(page);
2698 if (page->mapping != inode->i_mapping) {
2699 unlock_page(page);
2700 ret = VM_FAULT_NOPAGE;
2701 goto out;
2702 }
Jan Kara14da9202012-06-12 16:20:37 +02002703 /*
2704 * We mark the page dirty already here so that when freeze is in
2705 * progress, we are guaranteed that writeback during freezing will
2706 * see the dirty page and writeprotect it again.
2707 */
2708 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08002709 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002710out:
Jan Kara14da9202012-06-12 16:20:37 +02002711 sb_end_pagefault(inode->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002712 return ret;
2713}
Jan Kara4fcf1c62012-06-12 16:20:29 +02002714
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04002715const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07002716 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002717 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02002718 .page_mkwrite = filemap_page_mkwrite,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002719};
2720
2721/* This is used for a general mmap of a disk file */
2722
2723int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2724{
2725 struct address_space *mapping = file->f_mapping;
2726
2727 if (!mapping->a_ops->readpage)
2728 return -ENOEXEC;
2729 file_accessed(file);
2730 vma->vm_ops = &generic_file_vm_ops;
2731 return 0;
2732}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002733
2734/*
2735 * This is for filesystems which do not implement ->writepage.
2736 */
2737int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2738{
2739 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2740 return -EINVAL;
2741 return generic_file_mmap(file, vma);
2742}
2743#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07002744vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann453972282018-04-13 15:35:27 -07002745{
Souptick Joarder4b96a372018-10-26 15:04:03 -07002746 return VM_FAULT_SIGBUS;
Arnd Bergmann453972282018-04-13 15:35:27 -07002747}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002748int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2749{
2750 return -ENOSYS;
2751}
2752int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2753{
2754 return -ENOSYS;
2755}
2756#endif /* CONFIG_MMU */
2757
Arnd Bergmann453972282018-04-13 15:35:27 -07002758EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002759EXPORT_SYMBOL(generic_file_mmap);
2760EXPORT_SYMBOL(generic_file_readonly_mmap);
2761
Sasha Levin67f9fd92014-04-03 14:48:18 -07002762static struct page *wait_on_page_read(struct page *page)
2763{
2764 if (!IS_ERR(page)) {
2765 wait_on_page_locked(page);
2766 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002767 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07002768 page = ERR_PTR(-EIO);
2769 }
2770 }
2771 return page;
2772}
2773
Mel Gorman32b63522016-03-15 14:55:36 -07002774static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07002775 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002776 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002777 void *data,
2778 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002779{
Nick Piggineb2be182007-10-16 01:24:57 -07002780 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002781 int err;
2782repeat:
2783 page = find_get_page(mapping, index);
2784 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08002785 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002786 if (!page)
2787 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002788 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002789 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002790 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07002791 if (err == -EEXIST)
2792 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05002793 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002794 return ERR_PTR(err);
2795 }
Mel Gorman32b63522016-03-15 14:55:36 -07002796
2797filler:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002798 err = filler(data, page);
2799 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002800 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002801 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002802 }
Mel Gorman32b63522016-03-15 14:55:36 -07002803
2804 page = wait_on_page_read(page);
2805 if (IS_ERR(page))
2806 return page;
2807 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002808 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002809 if (PageUptodate(page))
2810 goto out;
2811
Mel Gormanebded022016-03-15 14:55:39 -07002812 /*
2813 * Page is not up to date and may be locked due one of the following
2814 * case a: Page is being filled and the page lock is held
2815 * case b: Read/write error clearing the page uptodate status
2816 * case c: Truncation in progress (page locked)
2817 * case d: Reclaim in progress
2818 *
2819 * Case a, the page will be up to date when the page is unlocked.
2820 * There is no need to serialise on the page lock here as the page
2821 * is pinned so the lock gives no additional protection. Even if the
2822 * the page is truncated, the data is still valid if PageUptodate as
2823 * it's a race vs truncate race.
2824 * Case b, the page will not be up to date
2825 * Case c, the page may be truncated but in itself, the data may still
2826 * be valid after IO completes as it's a read vs truncate race. The
2827 * operation must restart if the page is not uptodate on unlock but
2828 * otherwise serialising on page lock to stabilise the mapping gives
2829 * no additional guarantees to the caller as the page lock is
2830 * released before return.
2831 * Case d, similar to truncation. If reclaim holds the page lock, it
2832 * will be a race with remove_mapping that determines if the mapping
2833 * is valid on unlock but otherwise the data is valid and there is
2834 * no need to serialise with page lock.
2835 *
2836 * As the page lock gives no additional guarantee, we optimistically
2837 * wait on the page to be unlocked and check if it's up to date and
2838 * use the page if it is. Otherwise, the page lock is required to
2839 * distinguish between the different cases. The motivation is that we
2840 * avoid spurious serialisations and wakeups when multiple processes
2841 * wait on the same page for IO to complete.
2842 */
2843 wait_on_page_locked(page);
2844 if (PageUptodate(page))
2845 goto out;
2846
2847 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002848 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07002849
2850 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002851 if (!page->mapping) {
2852 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002853 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002854 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002855 }
Mel Gormanebded022016-03-15 14:55:39 -07002856
2857 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002858 if (PageUptodate(page)) {
2859 unlock_page(page);
2860 goto out;
2861 }
Mel Gorman32b63522016-03-15 14:55:36 -07002862 goto filler;
2863
David Howellsc855ff32007-05-09 13:42:20 +01002864out:
Nick Piggin6fe69002007-05-06 14:49:04 -07002865 mark_page_accessed(page);
2866 return page;
2867}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002868
2869/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07002870 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002871 * @mapping: the page's address_space
2872 * @index: the page index
2873 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002874 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002875 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002876 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07002877 * not set, try to fill the page and wait for it to become unlocked.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002878 *
2879 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002880 *
2881 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002882 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07002883struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002884 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002885 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002886 void *data)
2887{
2888 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2889}
Sasha Levin67f9fd92014-04-03 14:48:18 -07002890EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002891
2892/**
2893 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2894 * @mapping: the page's address_space
2895 * @index: the page index
2896 * @gfp: the page allocator flags to use if allocating
2897 *
2898 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002899 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002900 *
2901 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002902 *
2903 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002904 */
2905struct page *read_cache_page_gfp(struct address_space *mapping,
2906 pgoff_t index,
2907 gfp_t gfp)
2908{
2909 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2910
Sasha Levin67f9fd92014-04-03 14:48:18 -07002911 return do_read_cache_page(mapping, index, filler, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002912}
2913EXPORT_SYMBOL(read_cache_page_gfp);
2914
Nick Piggin2f718ff2007-10-16 01:24:59 -07002915/*
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002916 * Don't operate on ranges the page cache doesn't support, and don't exceed the
2917 * LFS limits. If pos is under the limit it becomes a short access. If it
2918 * exceeds the limit we return -EFBIG.
2919 */
2920static int generic_access_check_limits(struct file *file, loff_t pos,
2921 loff_t *count)
2922{
2923 struct inode *inode = file->f_mapping->host;
2924 loff_t max_size = inode->i_sb->s_maxbytes;
2925
2926 if (!(file->f_flags & O_LARGEFILE))
2927 max_size = MAX_NON_LFS;
2928
2929 if (unlikely(pos >= max_size))
2930 return -EFBIG;
2931 *count = min(*count, max_size - pos);
2932 return 0;
2933}
2934
2935static int generic_write_check_limits(struct file *file, loff_t pos,
2936 loff_t *count)
2937{
2938 loff_t limit = rlimit(RLIMIT_FSIZE);
2939
2940 if (limit != RLIM_INFINITY) {
2941 if (pos >= limit) {
2942 send_sig(SIGXFSZ, current, 0);
2943 return -EFBIG;
2944 }
2945 *count = min(*count, limit - pos);
2946 }
2947
2948 return generic_access_check_limits(file, pos, count);
2949}
2950
2951/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002952 * Performs necessary checks before doing a write
2953 *
Randy Dunlap485bb992006-06-23 02:03:49 -07002954 * Can adjust writing position or amount of bytes to write.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002955 * Returns appropriate error code that caller should return or
2956 * zero in case that write should be allowed.
2957 */
Al Viro3309dd02015-04-09 12:55:47 -04002958inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002959{
Al Viro3309dd02015-04-09 12:55:47 -04002960 struct file *file = iocb->ki_filp;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002961 struct inode *inode = file->f_mapping->host;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002962 loff_t count;
2963 int ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002964
Al Viro3309dd02015-04-09 12:55:47 -04002965 if (!iov_iter_count(from))
2966 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002967
Al Viro0fa6b002015-04-04 04:05:48 -04002968 /* FIXME: this is for backwards compatibility with 2.4 */
Al Viro2ba48ce2015-04-09 13:52:01 -04002969 if (iocb->ki_flags & IOCB_APPEND)
Al Viro3309dd02015-04-09 12:55:47 -04002970 iocb->ki_pos = i_size_read(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002971
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002972 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2973 return -EINVAL;
2974
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002975 count = iov_iter_count(from);
2976 ret = generic_write_check_limits(file, iocb->ki_pos, &count);
2977 if (ret)
2978 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002979
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002980 iov_iter_truncate(from, count);
Al Viro3309dd02015-04-09 12:55:47 -04002981 return iov_iter_count(from);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002982}
2983EXPORT_SYMBOL(generic_write_checks);
2984
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11002985/*
2986 * Performs necessary checks before doing a clone.
2987 *
2988 * Can adjust amount of bytes to clone.
2989 * Returns appropriate error code that caller should return or
2990 * zero in case the clone should be allowed.
2991 */
2992int generic_remap_checks(struct file *file_in, loff_t pos_in,
2993 struct file *file_out, loff_t pos_out,
Darrick J. Wong42ec3d42018-10-30 10:41:49 +11002994 loff_t *req_count, unsigned int remap_flags)
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11002995{
2996 struct inode *inode_in = file_in->f_mapping->host;
2997 struct inode *inode_out = file_out->f_mapping->host;
2998 uint64_t count = *req_count;
2999 uint64_t bcount;
3000 loff_t size_in, size_out;
3001 loff_t bs = inode_out->i_sb->s_blocksize;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003002 int ret;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003003
3004 /* The start of both ranges must be aligned to an fs block. */
3005 if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_out, bs))
3006 return -EINVAL;
3007
3008 /* Ensure offsets don't wrap. */
3009 if (pos_in + count < pos_in || pos_out + count < pos_out)
3010 return -EINVAL;
3011
3012 size_in = i_size_read(inode_in);
3013 size_out = i_size_read(inode_out);
3014
3015 /* Dedupe requires both ranges to be within EOF. */
Darrick J. Wong3d281932018-10-30 10:41:34 +11003016 if ((remap_flags & REMAP_FILE_DEDUP) &&
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003017 (pos_in >= size_in || pos_in + count > size_in ||
3018 pos_out >= size_out || pos_out + count > size_out))
3019 return -EINVAL;
3020
3021 /* Ensure the infile range is within the infile. */
3022 if (pos_in >= size_in)
3023 return -EINVAL;
3024 count = min(count, size_in - (uint64_t)pos_in);
3025
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003026 ret = generic_access_check_limits(file_in, pos_in, &count);
3027 if (ret)
3028 return ret;
3029
3030 ret = generic_write_check_limits(file_out, pos_out, &count);
3031 if (ret)
3032 return ret;
3033
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003034 /*
3035 * If the user wanted us to link to the infile's EOF, round up to the
3036 * next block boundary for this check.
3037 *
3038 * Otherwise, make sure the count is also block-aligned, having
3039 * already confirmed the starting offsets' block alignment.
3040 */
3041 if (pos_in + count == size_in) {
3042 bcount = ALIGN(size_in, bs) - pos_in;
3043 } else {
3044 if (!IS_ALIGNED(count, bs))
Darrick J. Wongeca36542018-10-30 10:42:10 +11003045 count = ALIGN_DOWN(count, bs);
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003046 bcount = count;
3047 }
3048
3049 /* Don't allow overlapped cloning within the same file. */
3050 if (inode_in == inode_out &&
3051 pos_out + bcount > pos_in &&
3052 pos_out < pos_in + bcount)
3053 return -EINVAL;
3054
Darrick J. Wongeca36542018-10-30 10:42:10 +11003055 /*
3056 * We shortened the request but the caller can't deal with that, so
3057 * bounce the request back to userspace.
3058 */
3059 if (*req_count != count && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003060 return -EINVAL;
3061
Darrick J. Wongeca36542018-10-30 10:42:10 +11003062 *req_count = count;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003063 return 0;
3064}
3065
Nick Pigginafddba42007-10-16 01:25:01 -07003066int pagecache_write_begin(struct file *file, struct address_space *mapping,
3067 loff_t pos, unsigned len, unsigned flags,
3068 struct page **pagep, void **fsdata)
3069{
3070 const struct address_space_operations *aops = mapping->a_ops;
3071
Nick Piggin4e02ed42008-10-29 14:00:55 -07003072 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003073 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003074}
3075EXPORT_SYMBOL(pagecache_write_begin);
3076
3077int pagecache_write_end(struct file *file, struct address_space *mapping,
3078 loff_t pos, unsigned len, unsigned copied,
3079 struct page *page, void *fsdata)
3080{
3081 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003082
Nick Piggin4e02ed42008-10-29 14:00:55 -07003083 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003084}
3085EXPORT_SYMBOL(pagecache_write_end);
3086
Linus Torvalds1da177e2005-04-16 15:20:36 -07003087ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003088generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003089{
3090 struct file *file = iocb->ki_filp;
3091 struct address_space *mapping = file->f_mapping;
3092 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003093 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003094 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003095 size_t write_len;
3096 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003097
Al Viro0c949332014-03-22 06:51:37 -04003098 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003099 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003100
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003101 if (iocb->ki_flags & IOCB_NOWAIT) {
3102 /* If there are pages to writeback, return */
3103 if (filemap_range_has_page(inode->i_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003104 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003105 return -EAGAIN;
3106 } else {
3107 written = filemap_write_and_wait_range(mapping, pos,
3108 pos + write_len - 1);
3109 if (written)
3110 goto out;
3111 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003112
3113 /*
3114 * After a write we want buffered reads to be sure to go to disk to get
3115 * the new data. We invalidate clean cached page from the region we're
3116 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003117 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003118 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003119 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003120 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003121 /*
3122 * If a page can not be invalidated, return 0 to fall back
3123 * to buffered write.
3124 */
3125 if (written) {
3126 if (written == -EBUSY)
3127 return 0;
3128 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003129 }
3130
Al Viro639a93a52017-04-13 14:10:15 -04003131 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003132
3133 /*
3134 * Finally, try again to invalidate clean pages which might have been
3135 * cached by non-direct readahead, or faulted in by get_user_pages()
3136 * if the source of the write was an mmap'ed region of the file
3137 * we're writing. Either one is a pretty crazy thing to do,
3138 * so we don't support it 100%. If this invalidation
3139 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003140 *
3141 * Most of the time we do not need this since dio_complete() will do
3142 * the invalidation for us. However there are some file systems that
3143 * do not end up with dio_complete() being called, so let's not break
3144 * them by removing it completely
Christoph Hellwiga969e902008-07-23 21:27:04 -07003145 */
Lukas Czerner332391a2017-09-21 08:16:29 -06003146 if (mapping->nrpages)
3147 invalidate_inode_pages2_range(mapping,
3148 pos >> PAGE_SHIFT, end);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003149
Linus Torvalds1da177e2005-04-16 15:20:36 -07003150 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003151 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003152 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003153 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3154 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003155 mark_inode_dirty(inode);
3156 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003157 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003158 }
Al Viro639a93a52017-04-13 14:10:15 -04003159 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003160out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003161 return written;
3162}
3163EXPORT_SYMBOL(generic_file_direct_write);
3164
Nick Piggineb2be182007-10-16 01:24:57 -07003165/*
3166 * Find or create a page at the given pagecache position. Return the locked
3167 * page. This function is specifically for buffered writes.
3168 */
Nick Piggin54566b22009-01-04 12:00:53 -08003169struct page *grab_cache_page_write_begin(struct address_space *mapping,
3170 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003171{
Nick Piggineb2be182007-10-16 01:24:57 -07003172 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003173 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003174
Nick Piggin54566b22009-01-04 12:00:53 -08003175 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003176 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003177
Mel Gorman2457aec2014-06-04 16:10:31 -07003178 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003179 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003180 if (page)
3181 wait_for_stable_page(page);
3182
Nick Piggineb2be182007-10-16 01:24:57 -07003183 return page;
3184}
Nick Piggin54566b22009-01-04 12:00:53 -08003185EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003186
Al Viro3b93f912014-02-11 21:34:08 -05003187ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003188 struct iov_iter *i, loff_t pos)
3189{
3190 struct address_space *mapping = file->f_mapping;
3191 const struct address_space_operations *a_ops = mapping->a_ops;
3192 long status = 0;
3193 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003194 unsigned int flags = 0;
3195
Nick Pigginafddba42007-10-16 01:25:01 -07003196 do {
3197 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003198 unsigned long offset; /* Offset into pagecache page */
3199 unsigned long bytes; /* Bytes to write to page */
3200 size_t copied; /* Bytes copied from user */
3201 void *fsdata;
3202
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003203 offset = (pos & (PAGE_SIZE - 1));
3204 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003205 iov_iter_count(i));
3206
3207again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003208 /*
3209 * Bring in the user page that we will copy from _first_.
3210 * Otherwise there's a nasty deadlock on copying from the
3211 * same page as we're writing to, without it being marked
3212 * up-to-date.
3213 *
3214 * Not only is this an optimisation, but it is also required
3215 * to check that the address is actually valid, when atomic
3216 * usercopies are used, below.
3217 */
3218 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3219 status = -EFAULT;
3220 break;
3221 }
3222
Jan Kara296291c2015-10-22 13:32:21 -07003223 if (fatal_signal_pending(current)) {
3224 status = -EINTR;
3225 break;
3226 }
3227
Nick Piggin674b8922007-10-16 01:25:03 -07003228 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003229 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003230 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003231 break;
3232
anfei zhou931e80e2010-02-02 13:44:02 -08003233 if (mapping_writably_mapped(mapping))
3234 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003235
Nick Pigginafddba42007-10-16 01:25:01 -07003236 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
Nick Pigginafddba42007-10-16 01:25:01 -07003237 flush_dcache_page(page);
3238
3239 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3240 page, fsdata);
3241 if (unlikely(status < 0))
3242 break;
3243 copied = status;
3244
3245 cond_resched();
3246
Nick Piggin124d3b72008-02-02 15:01:17 +01003247 iov_iter_advance(i, copied);
Nick Pigginafddba42007-10-16 01:25:01 -07003248 if (unlikely(copied == 0)) {
3249 /*
3250 * If we were unable to copy any data at all, we must
3251 * fall back to a single segment length write.
3252 *
3253 * If we didn't fallback here, we could livelock
3254 * because not all segments in the iov can be copied at
3255 * once without a pagefault.
3256 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003257 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003258 iov_iter_single_seg_count(i));
3259 goto again;
3260 }
Nick Pigginafddba42007-10-16 01:25:01 -07003261 pos += copied;
3262 written += copied;
3263
3264 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003265 } while (iov_iter_count(i));
3266
3267 return written ? written : status;
3268}
Al Viro3b93f912014-02-11 21:34:08 -05003269EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003270
Jan Karae4dd9de2009-08-17 18:10:06 +02003271/**
Al Viro81742022014-04-03 03:17:43 -04003272 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003273 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003274 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003275 *
3276 * This function does all the work needed for actually writing data to a
3277 * file. It does all basic checks, removes SUID from the file, updates
3278 * modification times and calls proper subroutines depending on whether we
3279 * do direct IO or a standard buffered write.
3280 *
3281 * It expects i_mutex to be grabbed unless we work on a block device or similar
3282 * object which does not need locking at all.
3283 *
3284 * This function does *not* take care of syncing data in case of O_SYNC write.
3285 * A caller has to handle it. This is mainly due to the fact that we want to
3286 * avoid syncing under i_mutex.
Mike Rapoporta862f682019-03-05 15:48:42 -08003287 *
3288 * Return:
3289 * * number of bytes written, even for truncated writes
3290 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003291 */
Al Viro81742022014-04-03 03:17:43 -04003292ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003293{
3294 struct file *file = iocb->ki_filp;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003295 struct address_space * mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003296 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003297 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003298 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003299 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003300
Linus Torvalds1da177e2005-04-16 15:20:36 -07003301 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003302 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003303 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003304 if (err)
3305 goto out;
3306
Josef Bacikc3b2da32012-03-26 09:59:21 -04003307 err = file_update_time(file);
3308 if (err)
3309 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003310
Al Viro2ba48ce2015-04-09 13:52:01 -04003311 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003312 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003313
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003314 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003315 /*
3316 * If the write stopped short of completing, fall back to
3317 * buffered writes. Some filesystems do this for writes to
3318 * holes, for example. For DAX files, a buffered write will
3319 * not succeed (even if it did, DAX does not handle dirty
3320 * page-cache pages correctly).
3321 */
Al Viro0b8def92015-04-07 10:22:53 -04003322 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003323 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003324
Al Viro0b8def92015-04-07 10:22:53 -04003325 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003326 /*
Al Viro3b93f912014-02-11 21:34:08 -05003327 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003328 * then we want to return the number of bytes which were
3329 * direct-written, or the error code if that was zero. Note
3330 * that this differs from normal direct-io semantics, which
3331 * will return -EFOO even if some bytes were written.
3332 */
Al Viro60bb4522014-08-08 12:39:16 -04003333 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003334 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003335 goto out;
3336 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003337 /*
3338 * We need to ensure that the page cache pages are written to
3339 * disk and invalidated to preserve the expected O_DIRECT
3340 * semantics.
3341 */
Al Viro3b93f912014-02-11 21:34:08 -05003342 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003343 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003344 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003345 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003346 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003347 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003348 pos >> PAGE_SHIFT,
3349 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003350 } else {
3351 /*
3352 * We don't know how much we wrote, so just return
3353 * the number of bytes which were direct-written
3354 */
3355 }
3356 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003357 written = generic_perform_write(file, from, iocb->ki_pos);
3358 if (likely(written > 0))
3359 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003360 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003361out:
3362 current->backing_dev_info = NULL;
3363 return written ? written : err;
3364}
Al Viro81742022014-04-03 03:17:43 -04003365EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003366
Jan Karae4dd9de2009-08-17 18:10:06 +02003367/**
Al Viro81742022014-04-03 03:17:43 -04003368 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003369 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003370 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003371 *
Al Viro81742022014-04-03 03:17:43 -04003372 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003373 * filesystems. It takes care of syncing the file in case of O_SYNC file
3374 * and acquires i_mutex as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003375 * Return:
3376 * * negative error code if no data has been written at all of
3377 * vfs_fsync_range() failed for a synchronous write
3378 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003379 */
Al Viro81742022014-04-03 03:17:43 -04003380ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003381{
3382 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003383 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003384 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003385
Al Viro59551022016-01-22 15:40:57 -05003386 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003387 ret = generic_write_checks(iocb, from);
3388 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003389 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003390 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003391
Christoph Hellwige2592212016-04-07 08:52:01 -07003392 if (ret > 0)
3393 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003394 return ret;
3395}
Al Viro81742022014-04-03 03:17:43 -04003396EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003397
David Howellscf9a2ae2006-08-29 19:05:54 +01003398/**
3399 * try_to_release_page() - release old fs-specific metadata on a page
3400 *
3401 * @page: the page which the kernel is trying to free
3402 * @gfp_mask: memory allocation flags (and I/O mode)
3403 *
3404 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003405 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003406 *
David Howells266cf652009-04-03 16:42:36 +01003407 * This may also be called if PG_fscache is set on a page, indicating that the
3408 * page is known to the local caching routines.
3409 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003410 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003411 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003412 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003413 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003414 */
3415int try_to_release_page(struct page *page, gfp_t gfp_mask)
3416{
3417 struct address_space * const mapping = page->mapping;
3418
3419 BUG_ON(!PageLocked(page));
3420 if (PageWriteback(page))
3421 return 0;
3422
3423 if (mapping && mapping->a_ops->releasepage)
3424 return mapping->a_ops->releasepage(page, gfp_mask);
3425 return try_to_free_buffers(page);
3426}
3427
3428EXPORT_SYMBOL(try_to_release_page);