blob: 1146fcfa321511b61e5dd258c9825b6bf759426e [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));
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -0700129 nr = compound_nr(page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500130 }
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);
Song Liu99cb0db2019-09-23 15:38:00 -0700206 } else if (PageTransHuge(page)) {
207 __dec_node_page_state(page, NR_FILE_THPS);
Song Liu09d91cd2019-09-23 15:38:03 -0700208 filemap_nr_thps_dec(mapping);
Jan Kara76253fb2017-11-15 17:37:22 -0800209 }
Jan Kara5ecc4d82017-11-15 17:37:29 -0800210
211 /*
212 * At this point page must be either written or cleaned by
213 * truncate. Dirty page here signals a bug and loss of
214 * unwritten data.
215 *
216 * This fixes dirty accounting after removing the page entirely
217 * but leaves PageDirty set: it has no effect for truncated
218 * page and anyway will be cleared before returning page into
219 * buddy allocator.
220 */
221 if (WARN_ON_ONCE(PageDirty(page)))
222 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
223}
224
225/*
226 * Delete a page from the page cache and free it. Caller has to make
227 * sure the page is locked and that nobody else uses it - or that usage
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700228 * is safe. The caller must hold the i_pages lock.
Jan Kara5ecc4d82017-11-15 17:37:29 -0800229 */
230void __delete_from_page_cache(struct page *page, void *shadow)
231{
232 struct address_space *mapping = page->mapping;
233
234 trace_mm_filemap_delete_from_page_cache(page);
235
236 unaccount_page_cache_page(mapping, page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500237 page_cache_delete(mapping, page, shadow);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700238}
239
Jan Kara59c66c52017-11-15 17:37:18 -0800240static void page_cache_free_page(struct address_space *mapping,
241 struct page *page)
242{
243 void (*freepage)(struct page *);
244
245 freepage = mapping->a_ops->freepage;
246 if (freepage)
247 freepage(page);
248
249 if (PageTransHuge(page) && !PageHuge(page)) {
250 page_ref_sub(page, HPAGE_PMD_NR);
251 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
252 } else {
253 put_page(page);
254 }
255}
256
Minchan Kim702cfbf2011-03-22 16:32:43 -0700257/**
258 * delete_from_page_cache - delete page from page cache
259 * @page: the page which the kernel is trying to remove from page cache
260 *
261 * This must be called only on pages that have been verified to be in the page
262 * cache and locked. It will never put the page into the free list, the caller
263 * has a reference on the page.
264 */
265void delete_from_page_cache(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700266{
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700267 struct address_space *mapping = page_mapping(page);
Greg Thelenc4843a72015-05-22 17:13:16 -0400268 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700269
Matt Mackallcd7619d2005-05-01 08:59:01 -0700270 BUG_ON(!PageLocked(page));
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700271 xa_lock_irqsave(&mapping->i_pages, flags);
Johannes Weiner62cccb82016-03-15 14:57:22 -0700272 __delete_from_page_cache(page, NULL);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700273 xa_unlock_irqrestore(&mapping->i_pages, flags);
Linus Torvalds6072d132010-12-01 13:35:19 -0500274
Jan Kara59c66c52017-11-15 17:37:18 -0800275 page_cache_free_page(mapping, page);
Minchan Kim97cecb52011-03-22 16:30:53 -0700276}
277EXPORT_SYMBOL(delete_from_page_cache);
278
Jan Karaaa65c292017-11-15 17:37:33 -0800279/*
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500280 * page_cache_delete_batch - delete several pages from page cache
Jan Karaaa65c292017-11-15 17:37:33 -0800281 * @mapping: the mapping to which pages belong
282 * @pvec: pagevec with pages to delete
283 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700284 * The function walks over mapping->i_pages and removes pages passed in @pvec
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700285 * from the mapping. The function expects @pvec to be sorted by page index
286 * and is optimised for it to be dense.
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700287 * It tolerates holes in @pvec (mapping entries at those indices are not
Jan Karaaa65c292017-11-15 17:37:33 -0800288 * modified). The function expects only THP head pages to be present in the
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700289 * @pvec.
Jan Karaaa65c292017-11-15 17:37:33 -0800290 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700291 * The function expects the i_pages lock to be held.
Jan Karaaa65c292017-11-15 17:37:33 -0800292 */
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500293static void page_cache_delete_batch(struct address_space *mapping,
Jan Karaaa65c292017-11-15 17:37:33 -0800294 struct pagevec *pvec)
295{
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500296 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
Jan Karaaa65c292017-11-15 17:37:33 -0800297 int total_pages = 0;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700298 int i = 0;
Jan Karaaa65c292017-11-15 17:37:33 -0800299 struct page *page;
Jan Karaaa65c292017-11-15 17:37:33 -0800300
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500301 mapping_set_update(&xas, mapping);
302 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700303 if (i >= pagevec_count(pvec))
Jan Karaaa65c292017-11-15 17:37:33 -0800304 break;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700305
306 /* A swap/dax/shadow entry got inserted? Skip it. */
Matthew Wilcox3159f942017-11-03 13:30:42 -0400307 if (xa_is_value(page))
Jan Karaaa65c292017-11-15 17:37:33 -0800308 continue;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700309 /*
310 * A page got inserted in our range? Skip it. We have our
311 * pages locked so they are protected from being removed.
312 * If we see a page whose index is higher than ours, it
313 * means our page has been removed, which shouldn't be
314 * possible because we're holding the PageLock.
315 */
316 if (page != pvec->pages[i]) {
317 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
318 page);
319 continue;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700320 }
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700321
322 WARN_ON_ONCE(!PageLocked(page));
323
324 if (page->index == xas.xa_index)
325 page->mapping = NULL;
326 /* Leave page->index set: truncation lookup relies on it */
327
328 /*
329 * Move to the next page in the vector if this is a regular
330 * page or the index is of the last sub-page of this compound
331 * page.
332 */
333 if (page->index + compound_nr(page) - 1 == 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
Konstantin Khlebnikovc3aab9a02019-09-23 15:34:45 -0700415 if (!mapping_cap_writeback_dirty(mapping) ||
416 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417 return 0;
418
Tejun Heob16b1de2015-06-02 08:39:48 -0600419 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700420 ret = do_writepages(mapping, &wbc);
Tejun Heob16b1de2015-06-02 08:39:48 -0600421 wbc_detach_inode(&wbc);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700422 return ret;
423}
424
425static inline int __filemap_fdatawrite(struct address_space *mapping,
426 int sync_mode)
427{
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700428 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700429}
430
431int filemap_fdatawrite(struct address_space *mapping)
432{
433 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
434}
435EXPORT_SYMBOL(filemap_fdatawrite);
436
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400437int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800438 loff_t end)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700439{
440 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
441}
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400442EXPORT_SYMBOL(filemap_fdatawrite_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700443
Randy Dunlap485bb992006-06-23 02:03:49 -0700444/**
445 * filemap_flush - mostly a non-blocking flush
446 * @mapping: target address_space
447 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700448 * This is a mostly non-blocking flush. Not suitable for data-integrity
449 * purposes - I/O may not be started against all dirty pages.
Mike Rapoporta862f682019-03-05 15:48:42 -0800450 *
451 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700452 */
453int filemap_flush(struct address_space *mapping)
454{
455 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
456}
457EXPORT_SYMBOL(filemap_flush);
458
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500459/**
460 * filemap_range_has_page - check if a page exists in range.
461 * @mapping: address space within which to check
462 * @start_byte: offset in bytes where the range starts
463 * @end_byte: offset in bytes where the range ends (inclusive)
464 *
465 * Find at least one page in the range supplied, usually used to check if
466 * direct writing in this range will trigger a writeback.
Mike Rapoporta862f682019-03-05 15:48:42 -0800467 *
468 * Return: %true if at least one page exists in the specified range,
469 * %false otherwise.
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500470 */
471bool filemap_range_has_page(struct address_space *mapping,
472 loff_t start_byte, loff_t end_byte)
473{
Jan Karaf7b68042017-09-06 16:21:40 -0700474 struct page *page;
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500475 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
476 pgoff_t max = end_byte >> PAGE_SHIFT;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500477
478 if (end_byte < start_byte)
479 return false;
480
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500481 rcu_read_lock();
482 for (;;) {
483 page = xas_find(&xas, max);
484 if (xas_retry(&xas, page))
485 continue;
486 /* Shadow entries don't count */
487 if (xa_is_value(page))
488 continue;
489 /*
490 * We don't need to try to pin this page; we're about to
491 * release the RCU lock anyway. It is enough to know that
492 * there was a page here recently.
493 */
494 break;
495 }
496 rcu_read_unlock();
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500497
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500498 return page != NULL;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500499}
500EXPORT_SYMBOL(filemap_range_has_page);
501
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400502static void __filemap_fdatawait_range(struct address_space *mapping,
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800503 loff_t start_byte, loff_t end_byte)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700504{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300505 pgoff_t index = start_byte >> PAGE_SHIFT;
506 pgoff_t end = end_byte >> PAGE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700507 struct pagevec pvec;
508 int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700509
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200510 if (end_byte < start_byte)
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400511 return;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700512
Mel Gorman86679822017-11-15 17:37:52 -0800513 pagevec_init(&pvec);
Jan Kara312e9d22017-11-15 17:35:05 -0800514 while (index <= end) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700515 unsigned i;
516
Jan Kara312e9d22017-11-15 17:35:05 -0800517 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
Jan Kara67fd7072017-11-15 17:35:19 -0800518 end, PAGECACHE_TAG_WRITEBACK);
Jan Kara312e9d22017-11-15 17:35:05 -0800519 if (!nr_pages)
520 break;
521
Linus Torvalds1da177e2005-04-16 15:20:36 -0700522 for (i = 0; i < nr_pages; i++) {
523 struct page *page = pvec.pages[i];
524
Linus Torvalds1da177e2005-04-16 15:20:36 -0700525 wait_on_page_writeback(page);
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400526 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700527 }
528 pagevec_release(&pvec);
529 cond_resched();
530 }
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800531}
532
533/**
534 * filemap_fdatawait_range - wait for writeback to complete
535 * @mapping: address space structure to wait for
536 * @start_byte: offset in bytes where the range starts
537 * @end_byte: offset in bytes where the range ends (inclusive)
538 *
539 * Walk the list of under-writeback pages of the given address space
540 * in the given range and wait for all of them. Check error status of
541 * the address space and return it.
542 *
543 * Since the error status of the address space is cleared by this function,
544 * callers are responsible for checking the return value and handling and/or
545 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800546 *
547 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800548 */
549int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
550 loff_t end_byte)
551{
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400552 __filemap_fdatawait_range(mapping, start_byte, end_byte);
553 return filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700554}
Jan Karad3bccb6f2009-08-17 19:30:27 +0200555EXPORT_SYMBOL(filemap_fdatawait_range);
556
557/**
Ross Zwisleraa0bfcd2019-06-20 17:05:37 -0400558 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
559 * @mapping: address space structure to wait for
560 * @start_byte: offset in bytes where the range starts
561 * @end_byte: offset in bytes where the range ends (inclusive)
562 *
563 * Walk the list of under-writeback pages of the given address space in the
564 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
565 * this function does not clear error status of the address space.
566 *
567 * Use this function if callers don't handle errors themselves. Expected
568 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
569 * fsfreeze(8)
570 */
571int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
572 loff_t start_byte, loff_t end_byte)
573{
574 __filemap_fdatawait_range(mapping, start_byte, end_byte);
575 return filemap_check_and_keep_errors(mapping);
576}
577EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
578
579/**
Jeff Laytona823e452017-07-28 07:24:43 -0400580 * file_fdatawait_range - wait for writeback to complete
581 * @file: file pointing to address space structure to wait for
582 * @start_byte: offset in bytes where the range starts
583 * @end_byte: offset in bytes where the range ends (inclusive)
584 *
585 * Walk the list of under-writeback pages of the address space that file
586 * refers to, in the given range and wait for all of them. Check error
587 * status of the address space vs. the file->f_wb_err cursor and return it.
588 *
589 * Since the error status of the file is advanced by this function,
590 * callers are responsible for checking the return value and handling and/or
591 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800592 *
593 * Return: error status of the address space vs. the file->f_wb_err cursor.
Jeff Laytona823e452017-07-28 07:24:43 -0400594 */
595int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
596{
597 struct address_space *mapping = file->f_mapping;
598
599 __filemap_fdatawait_range(mapping, start_byte, end_byte);
600 return file_check_and_advance_wb_err(file);
601}
602EXPORT_SYMBOL(file_fdatawait_range);
603
604/**
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800605 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
606 * @mapping: address space structure to wait for
607 *
608 * Walk the list of under-writeback pages of the given address space
609 * and wait for all of them. Unlike filemap_fdatawait(), this function
610 * does not clear error status of the address space.
611 *
612 * Use this function if callers don't handle errors themselves. Expected
613 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
614 * fsfreeze(8)
Mike Rapoporta862f682019-03-05 15:48:42 -0800615 *
616 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800617 */
Jeff Layton76341ca2017-07-06 07:02:22 -0400618int filemap_fdatawait_keep_errors(struct address_space *mapping)
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800619{
Jeff Laytonffb959b2017-07-31 10:29:38 -0400620 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
Jeff Layton76341ca2017-07-06 07:02:22 -0400621 return filemap_check_and_keep_errors(mapping);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800622}
Jeff Layton76341ca2017-07-06 07:02:22 -0400623EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800624
Konstantin Khlebnikov875d91b2019-09-23 15:34:48 -0700625/* Returns true if writeback might be needed or already in progress. */
Jeff Layton9326c9b2017-07-26 10:21:11 -0400626static bool mapping_needs_writeback(struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627{
Konstantin Khlebnikov875d91b2019-09-23 15:34:48 -0700628 if (dax_mapping(mapping))
629 return mapping->nrexceptional;
630
631 return mapping->nrpages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700632}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700633
634int filemap_write_and_wait(struct address_space *mapping)
635{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800636 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700637
Jeff Layton9326c9b2017-07-26 10:21:11 -0400638 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800639 err = filemap_fdatawrite(mapping);
640 /*
641 * Even if the above returned error, the pages may be
642 * written partially (e.g. -ENOSPC), so we wait for it.
643 * But the -EIO is special case, it may indicate the worst
644 * thing (e.g. bug) happened, so we avoid waiting for it.
645 */
646 if (err != -EIO) {
647 int err2 = filemap_fdatawait(mapping);
648 if (!err)
649 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400650 } else {
651 /* Clear any previously stored errors */
652 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800653 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700654 } else {
655 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700656 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800657 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700658}
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800659EXPORT_SYMBOL(filemap_write_and_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700660
Randy Dunlap485bb992006-06-23 02:03:49 -0700661/**
662 * filemap_write_and_wait_range - write out & wait on a file range
663 * @mapping: the address_space for the pages
664 * @lstart: offset in bytes where the range starts
665 * @lend: offset in bytes where the range ends (inclusive)
666 *
Andrew Morton469eb4d2006-03-24 03:17:45 -0800667 * Write out and wait upon file offsets lstart->lend, inclusive.
668 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -0300669 * Note that @lend is inclusive (describes the last byte to be written) so
Andrew Morton469eb4d2006-03-24 03:17:45 -0800670 * that this function can be used to write to the very end-of-file (end = -1).
Mike Rapoporta862f682019-03-05 15:48:42 -0800671 *
672 * Return: error status of the address space.
Andrew Morton469eb4d2006-03-24 03:17:45 -0800673 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700674int filemap_write_and_wait_range(struct address_space *mapping,
675 loff_t lstart, loff_t lend)
676{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800677 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700678
Jeff Layton9326c9b2017-07-26 10:21:11 -0400679 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800680 err = __filemap_fdatawrite_range(mapping, lstart, lend,
681 WB_SYNC_ALL);
682 /* See comment of filemap_write_and_wait() */
683 if (err != -EIO) {
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200684 int err2 = filemap_fdatawait_range(mapping,
685 lstart, lend);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800686 if (!err)
687 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400688 } else {
689 /* Clear any previously stored errors */
690 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800691 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700692 } else {
693 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800695 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700696}
Chris Masonf6995582009-04-15 13:22:37 -0400697EXPORT_SYMBOL(filemap_write_and_wait_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700698
Jeff Layton5660e132017-07-06 07:02:25 -0400699void __filemap_set_wb_err(struct address_space *mapping, int err)
700{
Jeff Layton3acdfd22017-07-24 06:22:15 -0400701 errseq_t eseq = errseq_set(&mapping->wb_err, err);
Jeff Layton5660e132017-07-06 07:02:25 -0400702
703 trace_filemap_set_wb_err(mapping, eseq);
704}
705EXPORT_SYMBOL(__filemap_set_wb_err);
706
707/**
708 * file_check_and_advance_wb_err - report wb error (if any) that was previously
709 * and advance wb_err to current one
710 * @file: struct file on which the error is being reported
711 *
712 * When userland calls fsync (or something like nfsd does the equivalent), we
713 * want to report any writeback errors that occurred since the last fsync (or
714 * since the file was opened if there haven't been any).
715 *
716 * Grab the wb_err from the mapping. If it matches what we have in the file,
717 * then just quickly return 0. The file is all caught up.
718 *
719 * If it doesn't match, then take the mapping value, set the "seen" flag in
720 * it and try to swap it into place. If it works, or another task beat us
721 * to it with the new value, then update the f_wb_err and return the error
722 * portion. The error at this point must be reported via proper channels
723 * (a'la fsync, or NFS COMMIT operation, etc.).
724 *
725 * While we handle mapping->wb_err with atomic operations, the f_wb_err
726 * value is protected by the f_lock since we must ensure that it reflects
727 * the latest value swapped in for this file descriptor.
Mike Rapoporta862f682019-03-05 15:48:42 -0800728 *
729 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400730 */
731int file_check_and_advance_wb_err(struct file *file)
732{
733 int err = 0;
734 errseq_t old = READ_ONCE(file->f_wb_err);
735 struct address_space *mapping = file->f_mapping;
736
737 /* Locklessly handle the common case where nothing has changed */
738 if (errseq_check(&mapping->wb_err, old)) {
739 /* Something changed, must use slow path */
740 spin_lock(&file->f_lock);
741 old = file->f_wb_err;
742 err = errseq_check_and_advance(&mapping->wb_err,
743 &file->f_wb_err);
744 trace_file_check_and_advance_wb_err(file, old);
745 spin_unlock(&file->f_lock);
746 }
Jeff Laytonf4e222c2017-10-03 16:15:25 -0700747
748 /*
749 * We're mostly using this function as a drop in replacement for
750 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
751 * that the legacy code would have had on these flags.
752 */
753 clear_bit(AS_EIO, &mapping->flags);
754 clear_bit(AS_ENOSPC, &mapping->flags);
Jeff Layton5660e132017-07-06 07:02:25 -0400755 return err;
756}
757EXPORT_SYMBOL(file_check_and_advance_wb_err);
758
759/**
760 * file_write_and_wait_range - write out & wait on a file range
761 * @file: file pointing to address_space with pages
762 * @lstart: offset in bytes where the range starts
763 * @lend: offset in bytes where the range ends (inclusive)
764 *
765 * Write out and wait upon file offsets lstart->lend, inclusive.
766 *
767 * Note that @lend is inclusive (describes the last byte to be written) so
768 * that this function can be used to write to the very end-of-file (end = -1).
769 *
770 * After writing out and waiting on the data, we check and advance the
771 * f_wb_err cursor to the latest value, and return any errors detected there.
Mike Rapoporta862f682019-03-05 15:48:42 -0800772 *
773 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400774 */
775int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
776{
777 int err = 0, err2;
778 struct address_space *mapping = file->f_mapping;
779
Jeff Layton9326c9b2017-07-26 10:21:11 -0400780 if (mapping_needs_writeback(mapping)) {
Jeff Layton5660e132017-07-06 07:02:25 -0400781 err = __filemap_fdatawrite_range(mapping, lstart, lend,
782 WB_SYNC_ALL);
783 /* See comment of filemap_write_and_wait() */
784 if (err != -EIO)
785 __filemap_fdatawait_range(mapping, lstart, lend);
786 }
787 err2 = file_check_and_advance_wb_err(file);
788 if (!err)
789 err = err2;
790 return err;
791}
792EXPORT_SYMBOL(file_write_and_wait_range);
793
Randy Dunlap485bb992006-06-23 02:03:49 -0700794/**
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700795 * replace_page_cache_page - replace a pagecache page with a new one
796 * @old: page to be replaced
797 * @new: page to replace with
798 * @gfp_mask: allocation mode
799 *
800 * This function replaces a page in the pagecache with a new one. On
801 * success it acquires the pagecache reference for the new page and
802 * drops it for the old page. Both the old and new pages must be
803 * locked. This function does not add the new page to the LRU, the
804 * caller must do that.
805 *
Matthew Wilcox74d60952017-11-17 10:01:45 -0500806 * The remove + add is atomic. This function cannot fail.
Mike Rapoporta862f682019-03-05 15:48:42 -0800807 *
808 * Return: %0
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700809 */
810int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
811{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500812 struct address_space *mapping = old->mapping;
813 void (*freepage)(struct page *) = mapping->a_ops->freepage;
814 pgoff_t offset = old->index;
815 XA_STATE(xas, &mapping->i_pages, offset);
816 unsigned long flags;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700817
Sasha Levin309381fea2014-01-23 15:52:54 -0800818 VM_BUG_ON_PAGE(!PageLocked(old), old);
819 VM_BUG_ON_PAGE(!PageLocked(new), new);
820 VM_BUG_ON_PAGE(new->mapping, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700821
Matthew Wilcox74d60952017-11-17 10:01:45 -0500822 get_page(new);
823 new->mapping = mapping;
824 new->index = offset;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700825
Matthew Wilcox74d60952017-11-17 10:01:45 -0500826 xas_lock_irqsave(&xas, flags);
827 xas_store(&xas, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700828
Matthew Wilcox74d60952017-11-17 10:01:45 -0500829 old->mapping = NULL;
830 /* hugetlb pages do not participate in page cache accounting. */
831 if (!PageHuge(old))
832 __dec_node_page_state(new, NR_FILE_PAGES);
833 if (!PageHuge(new))
834 __inc_node_page_state(new, NR_FILE_PAGES);
835 if (PageSwapBacked(old))
836 __dec_node_page_state(new, NR_SHMEM);
837 if (PageSwapBacked(new))
838 __inc_node_page_state(new, NR_SHMEM);
839 xas_unlock_irqrestore(&xas, flags);
840 mem_cgroup_migrate(old, new);
841 if (freepage)
842 freepage(old);
843 put_page(old);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700844
Matthew Wilcox74d60952017-11-17 10:01:45 -0500845 return 0;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700846}
847EXPORT_SYMBOL_GPL(replace_page_cache_page);
848
Johannes Weinera5289102014-04-03 14:47:51 -0700849static int __add_to_page_cache_locked(struct page *page,
850 struct address_space *mapping,
851 pgoff_t offset, gfp_t gfp_mask,
852 void **shadowp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700853{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500854 XA_STATE(xas, &mapping->i_pages, offset);
Johannes Weiner00501b52014-08-08 14:19:20 -0700855 int huge = PageHuge(page);
856 struct mem_cgroup *memcg;
Nick Piggine2867812008-07-25 19:45:30 -0700857 int error;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500858 void *old;
Nick Piggine2867812008-07-25 19:45:30 -0700859
Sasha Levin309381fea2014-01-23 15:52:54 -0800860 VM_BUG_ON_PAGE(!PageLocked(page), page);
861 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500862 mapping_set_update(&xas, mapping);
Nick Piggine2867812008-07-25 19:45:30 -0700863
Johannes Weiner00501b52014-08-08 14:19:20 -0700864 if (!huge) {
865 error = mem_cgroup_try_charge(page, current->mm,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800866 gfp_mask, &memcg, false);
Johannes Weiner00501b52014-08-08 14:19:20 -0700867 if (error)
868 return error;
869 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700870
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300871 get_page(page);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700872 page->mapping = mapping;
873 page->index = offset;
874
Matthew Wilcox74d60952017-11-17 10:01:45 -0500875 do {
876 xas_lock_irq(&xas);
877 old = xas_load(&xas);
878 if (old && !xa_is_value(old))
879 xas_set_err(&xas, -EEXIST);
880 xas_store(&xas, page);
881 if (xas_error(&xas))
882 goto unlock;
Michal Hocko4165b9b42015-06-24 16:57:24 -0700883
Matthew Wilcox74d60952017-11-17 10:01:45 -0500884 if (xa_is_value(old)) {
885 mapping->nrexceptional--;
886 if (shadowp)
887 *shadowp = old;
888 }
889 mapping->nrpages++;
890
891 /* hugetlb pages do not participate in page cache accounting */
892 if (!huge)
893 __inc_node_page_state(page, NR_FILE_PAGES);
894unlock:
895 xas_unlock_irq(&xas);
896 } while (xas_nomem(&xas, gfp_mask & GFP_RECLAIM_MASK));
897
898 if (xas_error(&xas))
899 goto error;
900
Johannes Weiner00501b52014-08-08 14:19:20 -0700901 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800902 mem_cgroup_commit_charge(page, memcg, false, false);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700903 trace_mm_filemap_add_to_page_cache(page);
904 return 0;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500905error:
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700906 page->mapping = NULL;
907 /* Leave page->index set: truncation relies upon it */
Johannes Weiner00501b52014-08-08 14:19:20 -0700908 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800909 mem_cgroup_cancel_charge(page, memcg, false);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300910 put_page(page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500911 return xas_error(&xas);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700912}
Josef Bacikcfcbfb12019-05-13 17:21:04 -0700913ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
Johannes Weinera5289102014-04-03 14:47:51 -0700914
915/**
916 * add_to_page_cache_locked - add a locked page to the pagecache
917 * @page: page to add
918 * @mapping: the page's address_space
919 * @offset: page index
920 * @gfp_mask: page allocation mode
921 *
922 * This function is used to add a page to the pagecache. It must be locked.
923 * This function does not add the page to the LRU. The caller must do that.
Mike Rapoporta862f682019-03-05 15:48:42 -0800924 *
925 * Return: %0 on success, negative error code otherwise.
Johannes Weinera5289102014-04-03 14:47:51 -0700926 */
927int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
928 pgoff_t offset, gfp_t gfp_mask)
929{
930 return __add_to_page_cache_locked(page, mapping, offset,
931 gfp_mask, NULL);
932}
Nick Piggine2867812008-07-25 19:45:30 -0700933EXPORT_SYMBOL(add_to_page_cache_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700934
935int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
Al Viro6daa0e22005-10-21 03:18:50 -0400936 pgoff_t offset, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700937{
Johannes Weinera5289102014-04-03 14:47:51 -0700938 void *shadow = NULL;
Rik van Riel4f98a2f2008-10-18 20:26:32 -0700939 int ret;
940
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800941 __SetPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700942 ret = __add_to_page_cache_locked(page, mapping, offset,
943 gfp_mask, &shadow);
944 if (unlikely(ret))
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800945 __ClearPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700946 else {
947 /*
948 * The page might have been evicted from cache only
949 * recently, in which case it should be activated like
950 * any other repeatedly accessed page.
Rik van Rielf0281a02016-05-20 16:56:25 -0700951 * The exception is pages getting rewritten; evicting other
952 * data from the working set, only to cache data that will
953 * get overwritten with something else, is a waste of memory.
Johannes Weinera5289102014-04-03 14:47:51 -0700954 */
Johannes Weiner1899ad12018-10-26 15:06:04 -0700955 WARN_ON_ONCE(PageActive(page));
956 if (!(gfp_mask & __GFP_WRITE) && shadow)
957 workingset_refault(page, shadow);
Johannes Weinera5289102014-04-03 14:47:51 -0700958 lru_cache_add(page);
959 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700960 return ret;
961}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +0300962EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700963
Paul Jackson44110fe2006-03-24 03:16:04 -0800964#ifdef CONFIG_NUMA
Nick Piggin2ae88142006-10-28 10:38:23 -0700965struct page *__page_cache_alloc(gfp_t gfp)
Paul Jackson44110fe2006-03-24 03:16:04 -0800966{
Miao Xiec0ff7452010-05-24 14:32:08 -0700967 int n;
968 struct page *page;
969
Paul Jackson44110fe2006-03-24 03:16:04 -0800970 if (cpuset_do_page_mem_spread()) {
Mel Gormancc9a6c82012-03-21 16:34:11 -0700971 unsigned int cpuset_mems_cookie;
972 do {
Mel Gormand26914d2014-04-03 14:47:24 -0700973 cpuset_mems_cookie = read_mems_allowed_begin();
Mel Gormancc9a6c82012-03-21 16:34:11 -0700974 n = cpuset_mem_spread_node();
Vlastimil Babka96db8002015-09-08 15:03:50 -0700975 page = __alloc_pages_node(n, gfp, 0);
Mel Gormand26914d2014-04-03 14:47:24 -0700976 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
Mel Gormancc9a6c82012-03-21 16:34:11 -0700977
Miao Xiec0ff7452010-05-24 14:32:08 -0700978 return page;
Paul Jackson44110fe2006-03-24 03:16:04 -0800979 }
Nick Piggin2ae88142006-10-28 10:38:23 -0700980 return alloc_pages(gfp, 0);
Paul Jackson44110fe2006-03-24 03:16:04 -0800981}
Nick Piggin2ae88142006-10-28 10:38:23 -0700982EXPORT_SYMBOL(__page_cache_alloc);
Paul Jackson44110fe2006-03-24 03:16:04 -0800983#endif
984
Linus Torvalds1da177e2005-04-16 15:20:36 -0700985/*
986 * In order to wait for pages to become available there must be
987 * waitqueues associated with pages. By using a hash table of
988 * waitqueues where the bucket discipline is to maintain all
989 * waiters on the same queue and wake all when any of the pages
990 * become available, and for the woken contexts to check to be
991 * sure the appropriate page became available, this saves space
992 * at a cost of "thundering herd" phenomena during rare hash
993 * collisions.
994 */
Nicholas Piggin62906022016-12-25 13:00:30 +1000995#define PAGE_WAIT_TABLE_BITS 8
996#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
997static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
998
999static wait_queue_head_t *page_waitqueue(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001000{
Nicholas Piggin62906022016-12-25 13:00:30 +10001001 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
Linus Torvalds1da177e2005-04-16 15:20:36 -07001002}
Nicholas Piggin62906022016-12-25 13:00:30 +10001003
1004void __init pagecache_init(void)
1005{
1006 int i;
1007
1008 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1009 init_waitqueue_head(&page_wait_table[i]);
1010
1011 page_writeback_init();
1012}
1013
Linus Torvalds3510ca22017-08-27 13:55:12 -07001014/* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
Nicholas Piggin62906022016-12-25 13:00:30 +10001015struct wait_page_key {
1016 struct page *page;
1017 int bit_nr;
1018 int page_match;
1019};
1020
1021struct wait_page_queue {
1022 struct page *page;
1023 int bit_nr;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001024 wait_queue_entry_t wait;
Nicholas Piggin62906022016-12-25 13:00:30 +10001025};
1026
Ingo Molnarac6424b2017-06-20 12:06:13 +02001027static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
Nicholas Piggin62906022016-12-25 13:00:30 +10001028{
1029 struct wait_page_key *key = arg;
1030 struct wait_page_queue *wait_page
1031 = container_of(wait, struct wait_page_queue, wait);
1032
1033 if (wait_page->page != key->page)
1034 return 0;
1035 key->page_match = 1;
1036
1037 if (wait_page->bit_nr != key->bit_nr)
1038 return 0;
Linus Torvalds3510ca22017-08-27 13:55:12 -07001039
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001040 /*
1041 * Stop walking if it's locked.
1042 * Is this safe if put_and_wait_on_page_locked() is in use?
1043 * Yes: the waker must hold a reference to this page, and if PG_locked
1044 * has now already been set by another task, that task must also hold
1045 * a reference to the *same usage* of this page; so there is no need
1046 * to walk on to wake even the put_and_wait_on_page_locked() callers.
1047 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001048 if (test_bit(key->bit_nr, &key->page->flags))
Linus Torvalds3510ca22017-08-27 13:55:12 -07001049 return -1;
Nicholas Piggin62906022016-12-25 13:00:30 +10001050
1051 return autoremove_wake_function(wait, mode, sync, key);
1052}
1053
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001054static void wake_up_page_bit(struct page *page, int bit_nr)
Nicholas Piggin62906022016-12-25 13:00:30 +10001055{
1056 wait_queue_head_t *q = page_waitqueue(page);
1057 struct wait_page_key key;
1058 unsigned long flags;
Tim Chen11a19c72017-08-25 09:13:55 -07001059 wait_queue_entry_t bookmark;
Nicholas Piggin62906022016-12-25 13:00:30 +10001060
1061 key.page = page;
1062 key.bit_nr = bit_nr;
1063 key.page_match = 0;
1064
Tim Chen11a19c72017-08-25 09:13:55 -07001065 bookmark.flags = 0;
1066 bookmark.private = NULL;
1067 bookmark.func = NULL;
1068 INIT_LIST_HEAD(&bookmark.entry);
1069
Nicholas Piggin62906022016-12-25 13:00:30 +10001070 spin_lock_irqsave(&q->lock, flags);
Tim Chen11a19c72017-08-25 09:13:55 -07001071 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1072
1073 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1074 /*
1075 * Take a breather from holding the lock,
1076 * allow pages that finish wake up asynchronously
1077 * to acquire the lock and remove themselves
1078 * from wait queue
1079 */
1080 spin_unlock_irqrestore(&q->lock, flags);
1081 cpu_relax();
1082 spin_lock_irqsave(&q->lock, flags);
1083 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1084 }
1085
Nicholas Piggin62906022016-12-25 13:00:30 +10001086 /*
1087 * It is possible for other pages to have collided on the waitqueue
1088 * hash, so in that case check for a page match. That prevents a long-
1089 * term waiter
1090 *
1091 * It is still possible to miss a case here, when we woke page waiters
1092 * and removed them from the waitqueue, but there are still other
1093 * page waiters.
1094 */
1095 if (!waitqueue_active(q) || !key.page_match) {
1096 ClearPageWaiters(page);
1097 /*
1098 * It's possible to miss clearing Waiters here, when we woke
1099 * our page waiters, but the hashed waitqueue has waiters for
1100 * other pages on it.
1101 *
1102 * That's okay, it's a rare case. The next waker will clear it.
1103 */
1104 }
1105 spin_unlock_irqrestore(&q->lock, flags);
1106}
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001107
1108static void wake_up_page(struct page *page, int bit)
1109{
1110 if (!PageWaiters(page))
1111 return;
1112 wake_up_page_bit(page, bit);
1113}
Nicholas Piggin62906022016-12-25 13:00:30 +10001114
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001115/*
1116 * A choice of three behaviors for wait_on_page_bit_common():
1117 */
1118enum behavior {
1119 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1120 * __lock_page() waiting on then setting PG_locked.
1121 */
1122 SHARED, /* Hold ref to page and check the bit when woken, like
1123 * wait_on_page_writeback() waiting on PG_writeback.
1124 */
1125 DROP, /* Drop ref to page before wait, no check when woken,
1126 * like put_and_wait_on_page_locked() on PG_locked.
1127 */
1128};
1129
Nicholas Piggin62906022016-12-25 13:00:30 +10001130static inline int wait_on_page_bit_common(wait_queue_head_t *q,
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001131 struct page *page, int bit_nr, int state, enum behavior behavior)
Nicholas Piggin62906022016-12-25 13:00:30 +10001132{
1133 struct wait_page_queue wait_page;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001134 wait_queue_entry_t *wait = &wait_page.wait;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001135 bool bit_is_set;
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001136 bool thrashing = false;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001137 bool delayacct = false;
Johannes Weinereb414682018-10-26 15:06:27 -07001138 unsigned long pflags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001139 int ret = 0;
1140
Johannes Weinereb414682018-10-26 15:06:27 -07001141 if (bit_nr == PG_locked &&
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001142 !PageUptodate(page) && PageWorkingset(page)) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001143 if (!PageSwapBacked(page)) {
Johannes Weinereb414682018-10-26 15:06:27 -07001144 delayacct_thrashing_start();
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001145 delayacct = true;
1146 }
Johannes Weinereb414682018-10-26 15:06:27 -07001147 psi_memstall_enter(&pflags);
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001148 thrashing = true;
1149 }
1150
Nicholas Piggin62906022016-12-25 13:00:30 +10001151 init_wait(wait);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001152 wait->flags = behavior == EXCLUSIVE ? WQ_FLAG_EXCLUSIVE : 0;
Nicholas Piggin62906022016-12-25 13:00:30 +10001153 wait->func = wake_page_function;
1154 wait_page.page = page;
1155 wait_page.bit_nr = bit_nr;
1156
1157 for (;;) {
1158 spin_lock_irq(&q->lock);
1159
Ingo Molnar2055da92017-06-20 12:06:46 +02001160 if (likely(list_empty(&wait->entry))) {
Linus Torvalds3510ca22017-08-27 13:55:12 -07001161 __add_wait_queue_entry_tail(q, wait);
Nicholas Piggin62906022016-12-25 13:00:30 +10001162 SetPageWaiters(page);
1163 }
1164
1165 set_current_state(state);
1166
1167 spin_unlock_irq(&q->lock);
1168
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001169 bit_is_set = test_bit(bit_nr, &page->flags);
1170 if (behavior == DROP)
1171 put_page(page);
Nicholas Piggin62906022016-12-25 13:00:30 +10001172
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001173 if (likely(bit_is_set))
1174 io_schedule();
1175
1176 if (behavior == EXCLUSIVE) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001177 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1178 break;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001179 } else if (behavior == SHARED) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001180 if (!test_bit(bit_nr, &page->flags))
1181 break;
1182 }
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001183
Davidlohr Buesofa45f112019-01-03 15:28:55 -08001184 if (signal_pending_state(state, current)) {
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001185 ret = -EINTR;
1186 break;
1187 }
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001188
1189 if (behavior == DROP) {
1190 /*
1191 * We can no longer safely access page->flags:
1192 * even if CONFIG_MEMORY_HOTREMOVE is not enabled,
1193 * there is a risk of waiting forever on a page reused
1194 * for something that keeps it locked indefinitely.
1195 * But best check for -EINTR above before breaking.
1196 */
1197 break;
1198 }
Nicholas Piggin62906022016-12-25 13:00:30 +10001199 }
1200
1201 finish_wait(q, wait);
1202
Johannes Weinereb414682018-10-26 15:06:27 -07001203 if (thrashing) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001204 if (delayacct)
Johannes Weinereb414682018-10-26 15:06:27 -07001205 delayacct_thrashing_end();
1206 psi_memstall_leave(&pflags);
1207 }
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001208
Nicholas Piggin62906022016-12-25 13:00:30 +10001209 /*
1210 * A signal could leave PageWaiters set. Clearing it here if
1211 * !waitqueue_active would be possible (by open-coding finish_wait),
1212 * but still fail to catch it in the case of wait hash collision. We
1213 * already can fail to clear wait hash collision cases, so don't
1214 * bother with signals either.
1215 */
1216
1217 return ret;
1218}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001219
Harvey Harrison920c7a52008-02-04 22:29:26 -08001220void wait_on_page_bit(struct page *page, int bit_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001221{
Nicholas Piggin62906022016-12-25 13:00:30 +10001222 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001223 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001224}
1225EXPORT_SYMBOL(wait_on_page_bit);
1226
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001227int wait_on_page_bit_killable(struct page *page, int bit_nr)
1228{
Nicholas Piggin62906022016-12-25 13:00:30 +10001229 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001230 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001231}
David Howells4343d002017-11-02 15:27:52 +00001232EXPORT_SYMBOL(wait_on_page_bit_killable);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001233
Linus Torvalds1da177e2005-04-16 15:20:36 -07001234/**
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001235 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1236 * @page: The page to wait for.
1237 *
1238 * The caller should hold a reference on @page. They expect the page to
1239 * become unlocked relatively soon, but do not wish to hold up migration
1240 * (for example) by holding the reference while waiting for the page to
1241 * come unlocked. After this function returns, the caller should not
1242 * dereference @page.
1243 */
1244void put_and_wait_on_page_locked(struct page *page)
1245{
1246 wait_queue_head_t *q;
1247
1248 page = compound_head(page);
1249 q = page_waitqueue(page);
1250 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1251}
1252
1253/**
David Howells385e1ca5f2009-04-03 16:42:39 +01001254 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
Randy Dunlap697f6192009-04-13 14:39:54 -07001255 * @page: Page defining the wait queue of interest
1256 * @waiter: Waiter to add to the queue
David Howells385e1ca5f2009-04-03 16:42:39 +01001257 *
1258 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1259 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001260void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
David Howells385e1ca5f2009-04-03 16:42:39 +01001261{
1262 wait_queue_head_t *q = page_waitqueue(page);
1263 unsigned long flags;
1264
1265 spin_lock_irqsave(&q->lock, flags);
Linus Torvalds9c3a8152017-08-28 16:45:40 -07001266 __add_wait_queue_entry_tail(q, waiter);
Nicholas Piggin62906022016-12-25 13:00:30 +10001267 SetPageWaiters(page);
David Howells385e1ca5f2009-04-03 16:42:39 +01001268 spin_unlock_irqrestore(&q->lock, flags);
1269}
1270EXPORT_SYMBOL_GPL(add_page_wait_queue);
1271
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001272#ifndef clear_bit_unlock_is_negative_byte
1273
1274/*
1275 * PG_waiters is the high bit in the same byte as PG_lock.
1276 *
1277 * On x86 (and on many other architectures), we can clear PG_lock and
1278 * test the sign bit at the same time. But if the architecture does
1279 * not support that special operation, we just do this all by hand
1280 * instead.
1281 *
1282 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1283 * being cleared, but a memory barrier should be unneccssary since it is
1284 * in the same byte as PG_locked.
1285 */
1286static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1287{
1288 clear_bit_unlock(nr, mem);
1289 /* smp_mb__after_atomic(); */
Olof Johansson98473f92016-12-29 14:16:07 -08001290 return test_bit(PG_waiters, mem);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001291}
1292
1293#endif
1294
David Howells385e1ca5f2009-04-03 16:42:39 +01001295/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001296 * unlock_page - unlock a locked page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001297 * @page: the page
1298 *
1299 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1300 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
Masanari Iidada3dae52014-09-09 01:27:23 +09001301 * mechanism between PageLocked pages and PageWriteback pages is shared.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001302 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1303 *
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001304 * Note that this depends on PG_waiters being the sign bit in the byte
1305 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1306 * clear the PG_locked bit and test PG_waiters at the same time fairly
1307 * portably (architectures that do LL/SC can test any bit, while x86 can
1308 * test the sign bit).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001309 */
Harvey Harrison920c7a52008-02-04 22:29:26 -08001310void unlock_page(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001311{
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001312 BUILD_BUG_ON(PG_waiters != 7);
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -08001313 page = compound_head(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001314 VM_BUG_ON_PAGE(!PageLocked(page), page);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001315 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1316 wake_up_page_bit(page, PG_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001317}
1318EXPORT_SYMBOL(unlock_page);
1319
Randy Dunlap485bb992006-06-23 02:03:49 -07001320/**
1321 * end_page_writeback - end writeback against a page
1322 * @page: the page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001323 */
1324void end_page_writeback(struct page *page)
1325{
Mel Gorman888cf2d2014-06-04 16:10:34 -07001326 /*
1327 * TestClearPageReclaim could be used here but it is an atomic
1328 * operation and overkill in this particular case. Failing to
1329 * shuffle a page marked for immediate reclaim is too mild to
1330 * justify taking an atomic operation penalty at the end of
1331 * ever page writeback.
1332 */
1333 if (PageReclaim(page)) {
1334 ClearPageReclaim(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001335 rotate_reclaimable_page(page);
Mel Gorman888cf2d2014-06-04 16:10:34 -07001336 }
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001337
1338 if (!test_clear_page_writeback(page))
1339 BUG();
1340
Peter Zijlstra4e857c52014-03-17 18:06:10 +01001341 smp_mb__after_atomic();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001342 wake_up_page(page, PG_writeback);
1343}
1344EXPORT_SYMBOL(end_page_writeback);
1345
Matthew Wilcox57d99842014-06-04 16:07:45 -07001346/*
1347 * After completing I/O on a page, call this routine to update the page
1348 * flags appropriately
1349 */
Jens Axboec11f0c02016-08-05 08:11:04 -06001350void page_endio(struct page *page, bool is_write, int err)
Matthew Wilcox57d99842014-06-04 16:07:45 -07001351{
Jens Axboec11f0c02016-08-05 08:11:04 -06001352 if (!is_write) {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001353 if (!err) {
1354 SetPageUptodate(page);
1355 } else {
1356 ClearPageUptodate(page);
1357 SetPageError(page);
1358 }
1359 unlock_page(page);
Mike Christieabf54542016-08-04 14:23:34 -06001360 } else {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001361 if (err) {
Minchan Kimdd8416c2017-02-24 14:59:59 -08001362 struct address_space *mapping;
1363
Matthew Wilcox57d99842014-06-04 16:07:45 -07001364 SetPageError(page);
Minchan Kimdd8416c2017-02-24 14:59:59 -08001365 mapping = page_mapping(page);
1366 if (mapping)
1367 mapping_set_error(mapping, err);
Matthew Wilcox57d99842014-06-04 16:07:45 -07001368 }
1369 end_page_writeback(page);
1370 }
1371}
1372EXPORT_SYMBOL_GPL(page_endio);
1373
Randy Dunlap485bb992006-06-23 02:03:49 -07001374/**
1375 * __lock_page - get a lock on the page, assuming we need to sleep to get it
Randy Dunlap87066752017-02-22 15:44:44 -08001376 * @__page: the page to lock
Linus Torvalds1da177e2005-04-16 15:20:36 -07001377 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001378void __lock_page(struct page *__page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001379{
Nicholas Piggin62906022016-12-25 13:00:30 +10001380 struct page *page = compound_head(__page);
1381 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001382 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1383 EXCLUSIVE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001384}
1385EXPORT_SYMBOL(__lock_page);
1386
Nicholas Piggin62906022016-12-25 13:00:30 +10001387int __lock_page_killable(struct page *__page)
Matthew Wilcox2687a352007-12-06 11:18:49 -05001388{
Nicholas Piggin62906022016-12-25 13:00:30 +10001389 struct page *page = compound_head(__page);
1390 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001391 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1392 EXCLUSIVE);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001393}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +03001394EXPORT_SYMBOL_GPL(__lock_page_killable);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001395
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001396/*
1397 * Return values:
1398 * 1 - page is locked; mmap_sem is still held.
1399 * 0 - page is not locked.
1400 * mmap_sem has been released (up_read()), unless flags had both
1401 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1402 * which case mmap_sem is still held.
1403 *
1404 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1405 * with the page locked and the mmap_sem unperturbed.
1406 */
Michel Lespinassed065bd82010-10-26 14:21:57 -07001407int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1408 unsigned int flags)
1409{
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001410 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1411 /*
1412 * CAUTION! In this case, mmap_sem is not released
1413 * even though return 0.
1414 */
1415 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1416 return 0;
1417
1418 up_read(&mm->mmap_sem);
1419 if (flags & FAULT_FLAG_KILLABLE)
1420 wait_on_page_locked_killable(page);
1421 else
Gleb Natapov318b2752011-03-22 16:30:51 -07001422 wait_on_page_locked(page);
Michel Lespinassed065bd82010-10-26 14:21:57 -07001423 return 0;
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001424 } else {
1425 if (flags & FAULT_FLAG_KILLABLE) {
1426 int ret;
1427
1428 ret = __lock_page_killable(page);
1429 if (ret) {
1430 up_read(&mm->mmap_sem);
1431 return 0;
1432 }
1433 } else
1434 __lock_page(page);
1435 return 1;
Michel Lespinassed065bd82010-10-26 14:21:57 -07001436 }
1437}
1438
Randy Dunlap485bb992006-06-23 02:03:49 -07001439/**
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001440 * page_cache_next_miss() - Find the next gap in the page cache.
1441 * @mapping: Mapping.
1442 * @index: Index.
1443 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001444 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001445 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1446 * gap with the lowest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001447 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001448 * This function may be called under the rcu_read_lock. However, this will
1449 * not atomically search a snapshot of the cache at a single point in time.
1450 * For example, if a gap is created at index 5, then subsequently a gap is
1451 * created at index 10, page_cache_next_miss covering both indices may
1452 * return 10 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001453 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001454 * Return: The index of the gap if found, otherwise an index outside the
1455 * range specified (in which case 'return - index >= max_scan' will be true).
1456 * In the rare case of index wrap-around, 0 will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001457 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001458pgoff_t page_cache_next_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001459 pgoff_t index, unsigned long max_scan)
1460{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001461 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001462
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001463 while (max_scan--) {
1464 void *entry = xas_next(&xas);
1465 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001466 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001467 if (xas.xa_index == 0)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001468 break;
1469 }
1470
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001471 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001472}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001473EXPORT_SYMBOL(page_cache_next_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001474
1475/**
Laurent Dufour2346a562019-05-13 17:21:29 -07001476 * page_cache_prev_miss() - Find the previous gap in the page cache.
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001477 * @mapping: Mapping.
1478 * @index: Index.
1479 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001480 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001481 * Search the range [max(index - max_scan + 1, 0), index] for the
1482 * gap with the highest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001483 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001484 * This function may be called under the rcu_read_lock. However, this will
1485 * not atomically search a snapshot of the cache at a single point in time.
1486 * For example, if a gap is created at index 10, then subsequently a gap is
1487 * created at index 5, page_cache_prev_miss() covering both indices may
1488 * return 5 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001489 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001490 * Return: The index of the gap if found, otherwise an index outside the
1491 * range specified (in which case 'index - return >= max_scan' will be true).
1492 * In the rare case of wrap-around, ULONG_MAX will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001493 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001494pgoff_t page_cache_prev_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001495 pgoff_t index, unsigned long max_scan)
1496{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001497 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001498
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001499 while (max_scan--) {
1500 void *entry = xas_prev(&xas);
1501 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001502 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001503 if (xas.xa_index == ULONG_MAX)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001504 break;
1505 }
1506
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001507 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001508}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001509EXPORT_SYMBOL(page_cache_prev_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001510
1511/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001512 * find_get_entry - find and get a page cache entry
Randy Dunlap485bb992006-06-23 02:03:49 -07001513 * @mapping: the address_space to search
Johannes Weiner0cd61442014-04-03 14:47:46 -07001514 * @offset: the page cache index
Randy Dunlap485bb992006-06-23 02:03:49 -07001515 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001516 * Looks up the page cache slot at @mapping & @offset. If there is a
1517 * page cache page, it is returned with an increased refcount.
1518 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001519 * If the slot holds a shadow entry of a previously evicted page, or a
1520 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001521 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001522 * Return: the found page or shadow entry, %NULL if nothing is found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001523 */
Johannes Weiner0cd61442014-04-03 14:47:46 -07001524struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001525{
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001526 XA_STATE(xas, &mapping->i_pages, offset);
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001527 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001528
Nick Piggina60637c2008-07-25 19:45:31 -07001529 rcu_read_lock();
1530repeat:
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001531 xas_reset(&xas);
1532 page = xas_load(&xas);
1533 if (xas_retry(&xas, page))
1534 goto repeat;
1535 /*
1536 * A shadow entry of a recently evicted page, or a swap entry from
1537 * shmem/tmpfs. Return it without attempting to raise page count.
1538 */
1539 if (!page || xa_is_value(page))
1540 goto out;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001541
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001542 if (!page_cache_get_speculative(page))
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001543 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001544
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001545 /*
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001546 * Has the page moved or been split?
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001547 * This is part of the lockless pagecache protocol. See
1548 * include/linux/pagemap.h for details.
1549 */
1550 if (unlikely(page != xas_reload(&xas))) {
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001551 put_page(page);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001552 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001553 }
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001554 page = find_subpage(page, offset);
Nick Piggin27d20fd2010-11-11 14:05:19 -08001555out:
Nick Piggina60637c2008-07-25 19:45:31 -07001556 rcu_read_unlock();
1557
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558 return page;
1559}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001560EXPORT_SYMBOL(find_get_entry);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001561
Randy Dunlap485bb992006-06-23 02:03:49 -07001562/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001563 * find_lock_entry - locate, pin and lock a page cache entry
1564 * @mapping: the address_space to search
1565 * @offset: the page cache index
1566 *
1567 * Looks up the page cache slot at @mapping & @offset. If there is a
1568 * page cache page, it is returned locked and with an increased
1569 * refcount.
1570 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001571 * If the slot holds a shadow entry of a previously evicted page, or a
1572 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001573 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001574 * find_lock_entry() may sleep.
Mike Rapoporta862f682019-03-05 15:48:42 -08001575 *
1576 * Return: the found page or shadow entry, %NULL if nothing is found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001577 */
1578struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001579{
1580 struct page *page;
1581
Linus Torvalds1da177e2005-04-16 15:20:36 -07001582repeat:
Johannes Weiner0cd61442014-04-03 14:47:46 -07001583 page = find_get_entry(mapping, offset);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001584 if (page && !xa_is_value(page)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001585 lock_page(page);
1586 /* Has the page been truncated? */
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001587 if (unlikely(page_mapping(page) != mapping)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001588 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001589 put_page(page);
Nick Piggina60637c2008-07-25 19:45:31 -07001590 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001591 }
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001592 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001593 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001594 return page;
1595}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001596EXPORT_SYMBOL(find_lock_entry);
1597
1598/**
Mel Gorman2457aec2014-06-04 16:10:31 -07001599 * pagecache_get_page - find and get a page reference
Johannes Weiner0cd61442014-04-03 14:47:46 -07001600 * @mapping: the address_space to search
1601 * @offset: the page index
Mel Gorman2457aec2014-06-04 16:10:31 -07001602 * @fgp_flags: PCG flags
Michal Hocko45f87de2014-12-29 20:30:35 +01001603 * @gfp_mask: gfp mask to use for the page cache data page allocation
Johannes Weiner0cd61442014-04-03 14:47:46 -07001604 *
Mel Gorman2457aec2014-06-04 16:10:31 -07001605 * Looks up the page cache slot at @mapping & @offset.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001606 *
Randy Dunlap75325182014-07-30 16:08:37 -07001607 * PCG flags modify how the page is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001608 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -03001609 * @fgp_flags can be:
1610 *
1611 * - FGP_ACCESSED: the page will be marked accessed
1612 * - FGP_LOCK: Page is return locked
1613 * - FGP_CREAT: If page is not present then a new page is allocated using
1614 * @gfp_mask and added to the page cache and the VM's LRU
1615 * list. The page is returned locked and with an increased
Mike Rapoporta862f682019-03-05 15:48:42 -08001616 * refcount.
Josef Bacika75d4c32019-03-13 11:44:14 -07001617 * - FGP_FOR_MMAP: Similar to FGP_CREAT, only we want to allow the caller to do
1618 * its own locking dance if the page is already in cache, or unlock the page
1619 * before returning if we had to add the page to pagecache.
Mel Gorman2457aec2014-06-04 16:10:31 -07001620 *
1621 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1622 * if the GFP flags specified for FGP_CREAT are atomic.
1623 *
1624 * If there is a page cache page, it is returned with an increased refcount.
Mike Rapoporta862f682019-03-05 15:48:42 -08001625 *
1626 * Return: the found page or %NULL otherwise.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001627 */
Mel Gorman2457aec2014-06-04 16:10:31 -07001628struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
Michal Hocko45f87de2014-12-29 20:30:35 +01001629 int fgp_flags, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630{
Nick Piggineb2be182007-10-16 01:24:57 -07001631 struct page *page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001632
Linus Torvalds1da177e2005-04-16 15:20:36 -07001633repeat:
Mel Gorman2457aec2014-06-04 16:10:31 -07001634 page = find_get_entry(mapping, offset);
Matthew Wilcox3159f942017-11-03 13:30:42 -04001635 if (xa_is_value(page))
Mel Gorman2457aec2014-06-04 16:10:31 -07001636 page = NULL;
1637 if (!page)
1638 goto no_page;
1639
1640 if (fgp_flags & FGP_LOCK) {
1641 if (fgp_flags & FGP_NOWAIT) {
1642 if (!trylock_page(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001643 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001644 return NULL;
1645 }
1646 } else {
1647 lock_page(page);
1648 }
1649
1650 /* Has the page been truncated? */
Song Liu31895432019-09-23 15:37:47 -07001651 if (unlikely(compound_head(page)->mapping != mapping)) {
Mel Gorman2457aec2014-06-04 16:10:31 -07001652 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001653 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001654 goto repeat;
1655 }
1656 VM_BUG_ON_PAGE(page->index != offset, page);
1657 }
1658
Kirill Tkhaic16eb002018-12-28 00:37:35 -08001659 if (fgp_flags & FGP_ACCESSED)
Mel Gorman2457aec2014-06-04 16:10:31 -07001660 mark_page_accessed(page);
1661
1662no_page:
1663 if (!page && (fgp_flags & FGP_CREAT)) {
1664 int err;
1665 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
Michal Hocko45f87de2014-12-29 20:30:35 +01001666 gfp_mask |= __GFP_WRITE;
1667 if (fgp_flags & FGP_NOFS)
1668 gfp_mask &= ~__GFP_FS;
Mel Gorman2457aec2014-06-04 16:10:31 -07001669
Michal Hocko45f87de2014-12-29 20:30:35 +01001670 page = __page_cache_alloc(gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001671 if (!page)
1672 return NULL;
Mel Gorman2457aec2014-06-04 16:10:31 -07001673
Josef Bacika75d4c32019-03-13 11:44:14 -07001674 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
Mel Gorman2457aec2014-06-04 16:10:31 -07001675 fgp_flags |= FGP_LOCK;
1676
Hugh Dickinseb39d612014-08-06 16:06:43 -07001677 /* Init accessed so avoid atomic mark_page_accessed later */
Mel Gorman2457aec2014-06-04 16:10:31 -07001678 if (fgp_flags & FGP_ACCESSED)
Hugh Dickinseb39d612014-08-06 16:06:43 -07001679 __SetPageReferenced(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001680
Matthew Wilcoxabc1be12018-04-20 14:56:20 -07001681 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001682 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001683 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07001684 page = NULL;
1685 if (err == -EEXIST)
1686 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001687 }
Josef Bacika75d4c32019-03-13 11:44:14 -07001688
1689 /*
1690 * add_to_page_cache_lru locks the page, and for mmap we expect
1691 * an unlocked page.
1692 */
1693 if (page && (fgp_flags & FGP_FOR_MMAP))
1694 unlock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001696
Linus Torvalds1da177e2005-04-16 15:20:36 -07001697 return page;
1698}
Mel Gorman2457aec2014-06-04 16:10:31 -07001699EXPORT_SYMBOL(pagecache_get_page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001700
1701/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001702 * find_get_entries - gang pagecache lookup
1703 * @mapping: The address_space to search
1704 * @start: The starting page cache index
1705 * @nr_entries: The maximum number of entries
1706 * @entries: Where the resulting entries are placed
1707 * @indices: The cache indices corresponding to the entries in @entries
1708 *
1709 * find_get_entries() will search for and return a group of up to
1710 * @nr_entries entries in the mapping. The entries are placed at
1711 * @entries. find_get_entries() takes a reference against any actual
1712 * pages it returns.
1713 *
1714 * The search returns a group of mapping-contiguous page cache entries
1715 * with ascending indexes. There may be holes in the indices due to
1716 * not-present pages.
1717 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001718 * Any shadow entries of evicted pages, or swap entries from
1719 * shmem/tmpfs, are included in the returned array.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001720 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001721 * Return: the number of pages and shadow entries which were found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001722 */
1723unsigned find_get_entries(struct address_space *mapping,
1724 pgoff_t start, unsigned int nr_entries,
1725 struct page **entries, pgoff_t *indices)
1726{
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001727 XA_STATE(xas, &mapping->i_pages, start);
1728 struct page *page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001729 unsigned int ret = 0;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001730
1731 if (!nr_entries)
1732 return 0;
1733
1734 rcu_read_lock();
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001735 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001736 if (xas_retry(&xas, page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001737 continue;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001738 /*
1739 * A shadow entry of a recently evicted page, a swap
1740 * entry from shmem/tmpfs or a DAX entry. Return it
1741 * without attempting to raise page count.
1742 */
1743 if (xa_is_value(page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001744 goto export;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001745
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001746 if (!page_cache_get_speculative(page))
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001747 goto retry;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001748
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001749 /* Has the page moved or been split? */
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001750 if (unlikely(page != xas_reload(&xas)))
1751 goto put_page;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001752 page = find_subpage(page, xas.xa_index);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001753
Johannes Weiner0cd61442014-04-03 14:47:46 -07001754export:
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001755 indices[ret] = xas.xa_index;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001756 entries[ret] = page;
1757 if (++ret == nr_entries)
1758 break;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001759 continue;
1760put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001761 put_page(page);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001762retry:
1763 xas_reset(&xas);
Johannes Weiner0cd61442014-04-03 14:47:46 -07001764 }
1765 rcu_read_unlock();
1766 return ret;
1767}
1768
1769/**
Jan Karab947cee2017-09-06 16:21:21 -07001770 * find_get_pages_range - gang pagecache lookup
Linus Torvalds1da177e2005-04-16 15:20:36 -07001771 * @mapping: The address_space to search
1772 * @start: The starting page index
Jan Karab947cee2017-09-06 16:21:21 -07001773 * @end: The final page index (inclusive)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001774 * @nr_pages: The maximum number of pages
1775 * @pages: Where the resulting pages are placed
1776 *
Jan Karab947cee2017-09-06 16:21:21 -07001777 * find_get_pages_range() will search for and return a group of up to @nr_pages
1778 * pages in the mapping starting at index @start and up to index @end
1779 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1780 * a reference against the returned pages.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001781 *
1782 * The search returns a group of mapping-contiguous pages with ascending
1783 * indexes. There may be holes in the indices due to not-present pages.
Jan Karad72dc8a2017-09-06 16:21:18 -07001784 * We also update @start to index the next page for the traversal.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001785 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001786 * Return: the number of pages which were found. If this number is
1787 * smaller than @nr_pages, the end of specified range has been
Jan Karab947cee2017-09-06 16:21:21 -07001788 * reached.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001789 */
Jan Karab947cee2017-09-06 16:21:21 -07001790unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1791 pgoff_t end, unsigned int nr_pages,
1792 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001793{
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001794 XA_STATE(xas, &mapping->i_pages, *start);
1795 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001796 unsigned ret = 0;
1797
1798 if (unlikely(!nr_pages))
1799 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001800
Nick Piggina60637c2008-07-25 19:45:31 -07001801 rcu_read_lock();
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001802 xas_for_each(&xas, page, end) {
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001803 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001804 continue;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001805 /* Skip over shadow, swap and DAX entries */
1806 if (xa_is_value(page))
Hugh Dickins8079b1c2011-08-03 16:21:28 -07001807 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001808
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001809 if (!page_cache_get_speculative(page))
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001810 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001811
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001812 /* Has the page moved or been split? */
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001813 if (unlikely(page != xas_reload(&xas)))
1814 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001815
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001816 pages[ret] = find_subpage(page, xas.xa_index);
Jan Karab947cee2017-09-06 16:21:21 -07001817 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001818 *start = xas.xa_index + 1;
Jan Karab947cee2017-09-06 16:21:21 -07001819 goto out;
1820 }
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001821 continue;
1822put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001823 put_page(page);
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001824retry:
1825 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001826 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001827
Jan Karab947cee2017-09-06 16:21:21 -07001828 /*
1829 * We come here when there is no page beyond @end. We take care to not
1830 * overflow the index @start as it confuses some of the callers. This
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001831 * breaks the iteration when there is a page at index -1 but that is
Jan Karab947cee2017-09-06 16:21:21 -07001832 * already broken anyway.
1833 */
1834 if (end == (pgoff_t)-1)
1835 *start = (pgoff_t)-1;
1836 else
1837 *start = end + 1;
1838out:
Nick Piggina60637c2008-07-25 19:45:31 -07001839 rcu_read_unlock();
Jan Karad72dc8a2017-09-06 16:21:18 -07001840
Linus Torvalds1da177e2005-04-16 15:20:36 -07001841 return ret;
1842}
1843
Jens Axboeebf43502006-04-27 08:46:01 +02001844/**
1845 * find_get_pages_contig - gang contiguous pagecache lookup
1846 * @mapping: The address_space to search
1847 * @index: The starting page index
1848 * @nr_pages: The maximum number of pages
1849 * @pages: Where the resulting pages are placed
1850 *
1851 * find_get_pages_contig() works exactly like find_get_pages(), except
1852 * that the returned number of pages are guaranteed to be contiguous.
1853 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001854 * Return: the number of pages which were found.
Jens Axboeebf43502006-04-27 08:46:01 +02001855 */
1856unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1857 unsigned int nr_pages, struct page **pages)
1858{
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001859 XA_STATE(xas, &mapping->i_pages, index);
1860 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001861 unsigned int ret = 0;
1862
1863 if (unlikely(!nr_pages))
1864 return 0;
Jens Axboeebf43502006-04-27 08:46:01 +02001865
Nick Piggina60637c2008-07-25 19:45:31 -07001866 rcu_read_lock();
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001867 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001868 if (xas_retry(&xas, page))
1869 continue;
1870 /*
1871 * If the entry has been swapped out, we can stop looking.
1872 * No current caller is looking for DAX entries.
1873 */
1874 if (xa_is_value(page))
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001875 break;
Hugh Dickins9d8aa4e2011-03-22 16:33:06 -07001876
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001877 if (!page_cache_get_speculative(page))
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001878 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001879
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001880 /* Has the page moved or been split? */
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001881 if (unlikely(page != xas_reload(&xas)))
1882 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001883
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001884 pages[ret] = find_subpage(page, xas.xa_index);
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001885 if (++ret == nr_pages)
1886 break;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001887 continue;
1888put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001889 put_page(page);
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001890retry:
1891 xas_reset(&xas);
Jens Axboeebf43502006-04-27 08:46:01 +02001892 }
Nick Piggina60637c2008-07-25 19:45:31 -07001893 rcu_read_unlock();
1894 return ret;
Jens Axboeebf43502006-04-27 08:46:01 +02001895}
David Howellsef71c152007-05-09 02:33:44 -07001896EXPORT_SYMBOL(find_get_pages_contig);
Jens Axboeebf43502006-04-27 08:46:01 +02001897
Randy Dunlap485bb992006-06-23 02:03:49 -07001898/**
Jan Kara72b045a2017-11-15 17:34:33 -08001899 * find_get_pages_range_tag - find and return pages in given range matching @tag
Randy Dunlap485bb992006-06-23 02:03:49 -07001900 * @mapping: the address_space to search
1901 * @index: the starting page index
Jan Kara72b045a2017-11-15 17:34:33 -08001902 * @end: The final page index (inclusive)
Randy Dunlap485bb992006-06-23 02:03:49 -07001903 * @tag: the tag index
1904 * @nr_pages: the maximum number of pages
1905 * @pages: where the resulting pages are placed
1906 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001907 * Like find_get_pages, except we only return pages which are tagged with
Randy Dunlap485bb992006-06-23 02:03:49 -07001908 * @tag. We update @index to index the next page for the traversal.
Mike Rapoporta862f682019-03-05 15:48:42 -08001909 *
1910 * Return: the number of pages which were found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001911 */
Jan Kara72b045a2017-11-15 17:34:33 -08001912unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001913 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
Jan Kara72b045a2017-11-15 17:34:33 -08001914 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001915{
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001916 XA_STATE(xas, &mapping->i_pages, *index);
1917 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001918 unsigned ret = 0;
1919
1920 if (unlikely(!nr_pages))
1921 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001922
Nick Piggina60637c2008-07-25 19:45:31 -07001923 rcu_read_lock();
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001924 xas_for_each_marked(&xas, page, end, tag) {
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001925 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001926 continue;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001927 /*
1928 * Shadow entries should never be tagged, but this iteration
1929 * is lockless so there is a window for page reclaim to evict
1930 * a page we saw tagged. Skip over it.
1931 */
1932 if (xa_is_value(page))
Johannes Weiner139b6a62014-05-06 12:50:05 -07001933 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001934
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001935 if (!page_cache_get_speculative(page))
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001936 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001937
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001938 /* Has the page moved or been split? */
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001939 if (unlikely(page != xas_reload(&xas)))
1940 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001941
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001942 pages[ret] = find_subpage(page, xas.xa_index);
Jan Kara72b045a2017-11-15 17:34:33 -08001943 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001944 *index = xas.xa_index + 1;
Jan Kara72b045a2017-11-15 17:34:33 -08001945 goto out;
1946 }
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001947 continue;
1948put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001949 put_page(page);
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001950retry:
1951 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001952 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001953
Jan Kara72b045a2017-11-15 17:34:33 -08001954 /*
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001955 * We come here when we got to @end. We take care to not overflow the
Jan Kara72b045a2017-11-15 17:34:33 -08001956 * index @index as it confuses some of the callers. This breaks the
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001957 * iteration when there is a page at index -1 but that is already
1958 * broken anyway.
Jan Kara72b045a2017-11-15 17:34:33 -08001959 */
1960 if (end == (pgoff_t)-1)
1961 *index = (pgoff_t)-1;
1962 else
1963 *index = end + 1;
1964out:
Nick Piggina60637c2008-07-25 19:45:31 -07001965 rcu_read_unlock();
1966
Linus Torvalds1da177e2005-04-16 15:20:36 -07001967 return ret;
1968}
Jan Kara72b045a2017-11-15 17:34:33 -08001969EXPORT_SYMBOL(find_get_pages_range_tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001970
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001971/*
1972 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1973 * a _large_ part of the i/o request. Imagine the worst scenario:
1974 *
1975 * ---R__________________________________________B__________
1976 * ^ reading here ^ bad block(assume 4k)
1977 *
1978 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1979 * => failing the whole request => read(R) => read(R+1) =>
1980 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1981 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1982 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1983 *
1984 * It is going insane. Fix it by quickly scaling down the readahead size.
1985 */
1986static void shrink_readahead_size_eio(struct file *filp,
1987 struct file_ra_state *ra)
1988{
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001989 ra->ra_pages /= 4;
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001990}
1991
Randy Dunlap485bb992006-06-23 02:03:49 -07001992/**
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02001993 * generic_file_buffered_read - generic file read routine
1994 * @iocb: the iocb to read
Al Viro6e58e792014-02-03 17:07:03 -05001995 * @iter: data destination
1996 * @written: already copied
Randy Dunlap485bb992006-06-23 02:03:49 -07001997 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001998 * This is a generic file read routine, and uses the
Randy Dunlap485bb992006-06-23 02:03:49 -07001999 * mapping->a_ops->readpage() function for the actual low-level stuff.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002000 *
2001 * This is really ugly. But the goto's actually try to clarify some
2002 * of the logic when it comes to error handling etc.
Mike Rapoporta862f682019-03-05 15:48:42 -08002003 *
2004 * Return:
2005 * * total number of bytes copied, including those the were already @written
2006 * * negative error code if nothing was copied
Linus Torvalds1da177e2005-04-16 15:20:36 -07002007 */
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002008static ssize_t generic_file_buffered_read(struct kiocb *iocb,
Al Viro6e58e792014-02-03 17:07:03 -05002009 struct iov_iter *iter, ssize_t written)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002010{
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002011 struct file *filp = iocb->ki_filp;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002012 struct address_space *mapping = filp->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002013 struct inode *inode = mapping->host;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002014 struct file_ra_state *ra = &filp->f_ra;
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002015 loff_t *ppos = &iocb->ki_pos;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002016 pgoff_t index;
2017 pgoff_t last_index;
2018 pgoff_t prev_index;
2019 unsigned long offset; /* offset into pagecache page */
Jan Karaec0f1632007-05-06 14:49:25 -07002020 unsigned int prev_offset;
Al Viro6e58e792014-02-03 17:07:03 -05002021 int error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002022
Wei Fangc2a97372016-10-07 17:01:52 -07002023 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
Linus Torvaldsd05c5f72016-12-14 12:45:25 -08002024 return 0;
Wei Fangc2a97372016-10-07 17:01:52 -07002025 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2026
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002027 index = *ppos >> PAGE_SHIFT;
2028 prev_index = ra->prev_pos >> PAGE_SHIFT;
2029 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2030 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2031 offset = *ppos & ~PAGE_MASK;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002032
Linus Torvalds1da177e2005-04-16 15:20:36 -07002033 for (;;) {
2034 struct page *page;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002035 pgoff_t end_index;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002036 loff_t isize;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002037 unsigned long nr, ret;
2038
Linus Torvalds1da177e2005-04-16 15:20:36 -07002039 cond_resched();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002040find_page:
Michal Hocko5abf1862017-02-03 13:13:29 -08002041 if (fatal_signal_pending(current)) {
2042 error = -EINTR;
2043 goto out;
2044 }
2045
Linus Torvalds1da177e2005-04-16 15:20:36 -07002046 page = find_get_page(mapping, index);
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002047 if (!page) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002048 if (iocb->ki_flags & IOCB_NOWAIT)
2049 goto would_block;
Rusty Russellcf914a72007-07-19 01:48:08 -07002050 page_cache_sync_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002051 ra, filp,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002052 index, last_index - index);
2053 page = find_get_page(mapping, index);
2054 if (unlikely(page == NULL))
2055 goto no_cached_page;
2056 }
2057 if (PageReadahead(page)) {
Rusty Russellcf914a72007-07-19 01:48:08 -07002058 page_cache_async_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002059 ra, filp, page,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002060 index, last_index - index);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002061 }
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002062 if (!PageUptodate(page)) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002063 if (iocb->ki_flags & IOCB_NOWAIT) {
2064 put_page(page);
2065 goto would_block;
2066 }
2067
Mel Gormanebded022016-03-15 14:55:39 -07002068 /*
2069 * See comment in do_read_cache_page on why
2070 * wait_on_page_locked is used to avoid unnecessarily
2071 * serialisations and why it's safe.
2072 */
Bart Van Asschec4b209a2016-10-07 16:58:33 -07002073 error = wait_on_page_locked_killable(page);
2074 if (unlikely(error))
2075 goto readpage_error;
Mel Gormanebded022016-03-15 14:55:39 -07002076 if (PageUptodate(page))
2077 goto page_ok;
2078
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002079 if (inode->i_blkbits == PAGE_SHIFT ||
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002080 !mapping->a_ops->is_partially_uptodate)
2081 goto page_not_up_to_date;
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002082 /* pipes can't handle partially uptodate pages */
David Howells00e23702018-10-22 13:07:28 +01002083 if (unlikely(iov_iter_is_pipe(iter)))
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002084 goto page_not_up_to_date;
Nick Piggin529ae9a2008-08-02 12:01:03 +02002085 if (!trylock_page(page))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002086 goto page_not_up_to_date;
Dave Hansen8d056cb2010-11-11 14:05:15 -08002087 /* Did it get truncated before we got the lock? */
2088 if (!page->mapping)
2089 goto page_not_up_to_date_locked;
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002090 if (!mapping->a_ops->is_partially_uptodate(page,
Al Viro6e58e792014-02-03 17:07:03 -05002091 offset, iter->count))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002092 goto page_not_up_to_date_locked;
2093 unlock_page(page);
2094 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002095page_ok:
NeilBrowna32ea1e2007-07-17 04:03:04 -07002096 /*
2097 * i_size must be checked after we know the page is Uptodate.
2098 *
2099 * Checking i_size after the check allows us to calculate
2100 * the correct value for "nr", which means the zero-filled
2101 * part of the page is not copied back to userspace (unless
2102 * another truncate extends the file - this is desired though).
2103 */
2104
2105 isize = i_size_read(inode);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002106 end_index = (isize - 1) >> PAGE_SHIFT;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002107 if (unlikely(!isize || index > end_index)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002108 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002109 goto out;
2110 }
2111
2112 /* nr is the maximum number of bytes to copy from this page */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002113 nr = PAGE_SIZE;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002114 if (index == end_index) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002115 nr = ((isize - 1) & ~PAGE_MASK) + 1;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002116 if (nr <= offset) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002117 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002118 goto out;
2119 }
2120 }
2121 nr = nr - offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002122
2123 /* If users can be writing to this page using arbitrary
2124 * virtual addresses, take care about potential aliasing
2125 * before reading the page on the kernel side.
2126 */
2127 if (mapping_writably_mapped(mapping))
2128 flush_dcache_page(page);
2129
2130 /*
Jan Karaec0f1632007-05-06 14:49:25 -07002131 * When a sequential read accesses a page several times,
2132 * only mark it as accessed the first time.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002133 */
Jan Karaec0f1632007-05-06 14:49:25 -07002134 if (prev_index != index || offset != prev_offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002135 mark_page_accessed(page);
2136 prev_index = index;
2137
2138 /*
2139 * Ok, we have the page, and it's up-to-date, so
2140 * now we can copy it to user space...
Linus Torvalds1da177e2005-04-16 15:20:36 -07002141 */
Al Viro6e58e792014-02-03 17:07:03 -05002142
2143 ret = copy_page_to_iter(page, offset, nr, iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002144 offset += ret;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002145 index += offset >> PAGE_SHIFT;
2146 offset &= ~PAGE_MASK;
Jan Kara6ce745e2007-05-06 14:49:26 -07002147 prev_offset = offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002148
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002149 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002150 written += ret;
2151 if (!iov_iter_count(iter))
2152 goto out;
2153 if (ret < nr) {
2154 error = -EFAULT;
2155 goto out;
2156 }
2157 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002158
2159page_not_up_to_date:
2160 /* Get exclusive access to the page ... */
Oleg Nesterov85462322008-06-08 21:20:43 +04002161 error = lock_page_killable(page);
2162 if (unlikely(error))
2163 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002164
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002165page_not_up_to_date_locked:
Nick Pigginda6052f2006-09-25 23:31:35 -07002166 /* Did it get truncated before we got the lock? */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002167 if (!page->mapping) {
2168 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002169 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002170 continue;
2171 }
2172
2173 /* Did somebody else fill it already? */
2174 if (PageUptodate(page)) {
2175 unlock_page(page);
2176 goto page_ok;
2177 }
2178
2179readpage:
Jeff Moyer91803b42010-05-26 11:49:40 -04002180 /*
2181 * A previous I/O error may have been due to temporary
2182 * failures, eg. multipath errors.
2183 * PG_error will be set again if readpage fails.
2184 */
2185 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002186 /* Start the actual read. The read will unlock the page. */
2187 error = mapping->a_ops->readpage(filp, page);
2188
Zach Brown994fc28c2005-12-15 14:28:17 -08002189 if (unlikely(error)) {
2190 if (error == AOP_TRUNCATED_PAGE) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002191 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002192 error = 0;
Zach Brown994fc28c2005-12-15 14:28:17 -08002193 goto find_page;
2194 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002195 goto readpage_error;
Zach Brown994fc28c2005-12-15 14:28:17 -08002196 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002197
2198 if (!PageUptodate(page)) {
Oleg Nesterov85462322008-06-08 21:20:43 +04002199 error = lock_page_killable(page);
2200 if (unlikely(error))
2201 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002202 if (!PageUptodate(page)) {
2203 if (page->mapping == NULL) {
2204 /*
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01002205 * invalidate_mapping_pages got it
Linus Torvalds1da177e2005-04-16 15:20:36 -07002206 */
2207 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002208 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002209 goto find_page;
2210 }
2211 unlock_page(page);
Fengguang Wu7ff81072007-10-16 01:24:35 -07002212 shrink_readahead_size_eio(filp, ra);
Oleg Nesterov85462322008-06-08 21:20:43 +04002213 error = -EIO;
2214 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002215 }
2216 unlock_page(page);
2217 }
2218
Linus Torvalds1da177e2005-04-16 15:20:36 -07002219 goto page_ok;
2220
2221readpage_error:
2222 /* UHHUH! A synchronous read error occurred. Report it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002223 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002224 goto out;
2225
2226no_cached_page:
2227 /*
2228 * Ok, it wasn't cached, so we need to create a new
2229 * page..
2230 */
Mel Gorman453f85d2017-11-15 17:38:03 -08002231 page = page_cache_alloc(mapping);
Nick Piggineb2be182007-10-16 01:24:57 -07002232 if (!page) {
Al Viro6e58e792014-02-03 17:07:03 -05002233 error = -ENOMEM;
Nick Piggineb2be182007-10-16 01:24:57 -07002234 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002235 }
Michal Hocko6afdb852015-06-24 16:58:06 -07002236 error = add_to_page_cache_lru(page, mapping, index,
Michal Hockoc62d2552015-11-06 16:28:49 -08002237 mapping_gfp_constraint(mapping, GFP_KERNEL));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002238 if (error) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002239 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002240 if (error == -EEXIST) {
2241 error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002242 goto find_page;
Al Viro6e58e792014-02-03 17:07:03 -05002243 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002244 goto out;
2245 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002246 goto readpage;
2247 }
2248
Milosz Tanski3239d832017-08-29 16:13:19 +02002249would_block:
2250 error = -EAGAIN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002251out:
Fengguang Wu7ff81072007-10-16 01:24:35 -07002252 ra->prev_pos = prev_index;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002253 ra->prev_pos <<= PAGE_SHIFT;
Fengguang Wu7ff81072007-10-16 01:24:35 -07002254 ra->prev_pos |= prev_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002255
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002256 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002257 file_accessed(filp);
Al Viro6e58e792014-02-03 17:07:03 -05002258 return written ? written : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002259}
2260
Randy Dunlap485bb992006-06-23 02:03:49 -07002261/**
Al Viro6abd2322014-04-04 14:20:57 -04002262 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002263 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002264 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002265 *
Al Viro6abd2322014-04-04 14:20:57 -04002266 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002267 * that can use the page cache directly.
Mike Rapoporta862f682019-03-05 15:48:42 -08002268 * Return:
2269 * * number of bytes copied, even for partial reads
2270 * * negative error code if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002271 */
2272ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002273generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002274{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002275 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002276 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002277
2278 if (!count)
2279 goto out; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002280
Al Viro2ba48ce2015-04-09 13:52:01 -04002281 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002282 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002283 struct address_space *mapping = file->f_mapping;
2284 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002285 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002286
Linus Torvalds1da177e2005-04-16 15:20:36 -07002287 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002288 if (iocb->ki_flags & IOCB_NOWAIT) {
2289 if (filemap_range_has_page(mapping, iocb->ki_pos,
2290 iocb->ki_pos + count - 1))
2291 return -EAGAIN;
2292 } else {
2293 retval = filemap_write_and_wait_range(mapping,
2294 iocb->ki_pos,
2295 iocb->ki_pos + count - 1);
2296 if (retval < 0)
2297 goto out;
2298 }
Al Viroed978a82014-03-05 22:53:04 -05002299
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002300 file_accessed(file);
2301
Al Viro5ecda132017-04-13 14:13:36 -04002302 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002303 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002304 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002305 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002306 }
Al Viro5b47d592017-05-08 13:54:47 -04002307 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002308
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002309 /*
2310 * Btrfs can have a short DIO read if we encounter
2311 * compressed extents, so if there was an error, or if
2312 * we've already read everything we wanted to, or if
2313 * there was a short read because we hit EOF, go ahead
2314 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002315 * the rest of the read. Buffered reads will not work for
2316 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002317 */
Al Viro5ecda132017-04-13 14:13:36 -04002318 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002319 IS_DAX(inode))
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002320 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002321 }
2322
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002323 retval = generic_file_buffered_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002324out:
2325 return retval;
2326}
Al Viroed978a82014-03-05 22:53:04 -05002327EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002328
Linus Torvalds1da177e2005-04-16 15:20:36 -07002329#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002330#define MMAP_LOTSAMISS (100)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002331static struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
2332 struct file *fpin)
2333{
2334 int flags = vmf->flags;
2335
2336 if (fpin)
2337 return fpin;
2338
2339 /*
2340 * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
2341 * anything, so we only pin the file and drop the mmap_sem if only
2342 * FAULT_FLAG_ALLOW_RETRY is set.
2343 */
2344 if ((flags & (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT)) ==
2345 FAULT_FLAG_ALLOW_RETRY) {
2346 fpin = get_file(vmf->vma->vm_file);
2347 up_read(&vmf->vma->vm_mm->mmap_sem);
2348 }
2349 return fpin;
2350}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002351
Linus Torvaldsef00e082009-06-16 15:31:25 -07002352/*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002353 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_sem
2354 * @vmf - the vm_fault for this fault.
2355 * @page - the page to lock.
2356 * @fpin - the pointer to the file we may pin (or is already pinned).
2357 *
2358 * This works similar to lock_page_or_retry in that it can drop the mmap_sem.
2359 * It differs in that it actually returns the page locked if it returns 1 and 0
2360 * if it couldn't lock the page. If we did have to drop the mmap_sem then fpin
2361 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002362 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002363static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2364 struct file **fpin)
2365{
2366 if (trylock_page(page))
2367 return 1;
2368
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002369 /*
2370 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2371 * the mmap_sem still held. That's how FAULT_FLAG_RETRY_NOWAIT
2372 * is supposed to work. We have way too many special cases..
2373 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002374 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2375 return 0;
2376
2377 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2378 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2379 if (__lock_page_killable(page)) {
2380 /*
2381 * We didn't have the right flags to drop the mmap_sem,
2382 * but all fault_handlers only check for fatal signals
2383 * if we return VM_FAULT_RETRY, so we need to drop the
2384 * mmap_sem here and return 0 if we don't have a fpin.
2385 */
2386 if (*fpin == NULL)
2387 up_read(&vmf->vma->vm_mm->mmap_sem);
2388 return 0;
2389 }
2390 } else
2391 __lock_page(page);
2392 return 1;
2393}
2394
2395
2396/*
2397 * Synchronous readahead happens when we don't even find a page in the page
2398 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2399 * to drop the mmap sem we return the file that was pinned in order for us to do
2400 * that. If we didn't pin a file then we return NULL. The file that is
2401 * returned needs to be fput()'ed when we're done with it.
2402 */
2403static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002404{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002405 struct file *file = vmf->vma->vm_file;
2406 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002407 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002408 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002409 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002410
2411 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002412 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002413 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002414 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002415 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002416
Josef Bacik2a1180f2019-03-13 11:44:18 -07002417 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002418 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang7ffc59b2009-06-16 15:31:38 -07002419 page_cache_sync_readahead(mapping, ra, file, offset,
2420 ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002421 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002422 }
2423
Andi Kleen207d04b2011-05-24 17:12:29 -07002424 /* Avoid banging the cache line if not needed */
2425 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002426 ra->mmap_miss++;
2427
2428 /*
2429 * Do we miss much more than hit in this file? If so,
2430 * stop bothering with read-ahead. It will only hurt.
2431 */
2432 if (ra->mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002433 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002434
Wu Fengguangd30a1102009-06-16 15:31:30 -07002435 /*
2436 * mmap read-around
2437 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002438 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002439 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2440 ra->size = ra->ra_pages;
2441 ra->async_size = ra->ra_pages / 4;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002442 ra_submit(ra, mapping, file);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002443 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002444}
2445
2446/*
2447 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002448 * so we want to possibly extend the readahead further. We return the file that
2449 * was pinned if we have to drop the mmap_sem in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002450 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002451static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2452 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002453{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002454 struct file *file = vmf->vma->vm_file;
2455 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002456 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002457 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002458 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002459
2460 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002461 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002462 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002463 if (ra->mmap_miss > 0)
2464 ra->mmap_miss--;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002465 if (PageReadahead(page)) {
2466 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002467 page_cache_async_readahead(mapping, ra, file,
2468 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002469 }
2470 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002471}
2472
Randy Dunlap485bb992006-06-23 02:03:49 -07002473/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002474 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002475 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002476 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002477 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002478 * mapped memory region to read in file data during a page fault.
2479 *
2480 * The goto's are kind of ugly, but this streamlines the normal case of having
2481 * it in the page cache, and handles the special cases reasonably without
2482 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002483 *
2484 * vma->vm_mm->mmap_sem must be held on entry.
2485 *
Yang Shia4985832019-07-11 20:55:29 -07002486 * If our return value has VM_FAULT_RETRY set, it's because the mmap_sem
2487 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002488 *
2489 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2490 * has not been released.
2491 *
2492 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002493 *
2494 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002495 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002496vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002497{
2498 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002499 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002500 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002501 struct address_space *mapping = file->f_mapping;
2502 struct file_ra_state *ra = &file->f_ra;
2503 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002504 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002505 pgoff_t max_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002506 struct page *page;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002507 vm_fault_t ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002508
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002509 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2510 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002511 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002512
Linus Torvalds1da177e2005-04-16 15:20:36 -07002513 /*
Johannes Weiner49426422013-10-16 13:46:59 -07002514 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07002515 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002516 page = find_get_page(mapping, offset);
Shaohua Li45cac652012-10-08 16:32:19 -07002517 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002518 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002519 * We found the page, so try async readahead before
2520 * waiting for the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002521 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002522 fpin = do_async_mmap_readahead(vmf, page);
Shaohua Li45cac652012-10-08 16:32:19 -07002523 } else if (!page) {
Linus Torvaldsef00e082009-06-16 15:31:25 -07002524 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002525 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07002526 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002527 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002528 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002529retry_find:
Josef Bacika75d4c32019-03-13 11:44:14 -07002530 page = pagecache_get_page(mapping, offset,
2531 FGP_CREAT|FGP_FOR_MMAP,
2532 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002533 if (!page) {
2534 if (fpin)
2535 goto out_retry;
Josef Bacika75d4c32019-03-13 11:44:14 -07002536 return vmf_error(-ENOMEM);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002537 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002538 }
2539
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002540 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2541 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07002542
2543 /* Did it get truncated? */
Song Liu585e5a72019-09-23 15:37:44 -07002544 if (unlikely(compound_head(page)->mapping != mapping)) {
Michel Lespinasseb522c942010-10-26 14:21:56 -07002545 unlock_page(page);
2546 put_page(page);
2547 goto retry_find;
2548 }
Song Liu520e5ba2019-09-23 15:37:50 -07002549 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07002550
Linus Torvalds1da177e2005-04-16 15:20:36 -07002551 /*
Nick Piggind00806b2007-07-19 01:46:57 -07002552 * We have a locked page in the page cache, now we need to check
2553 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002554 */
Nick Piggind00806b2007-07-19 01:46:57 -07002555 if (unlikely(!PageUptodate(page)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002556 goto page_not_uptodate;
2557
Linus Torvaldsef00e082009-06-16 15:31:25 -07002558 /*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002559 * We've made it this far and we had to drop our mmap_sem, now is the
2560 * time to return to the upper layer and have it re-find the vma and
2561 * redo the fault.
2562 */
2563 if (fpin) {
2564 unlock_page(page);
2565 goto out_retry;
2566 }
2567
2568 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002569 * Found the page and have a reference on it.
2570 * We must recheck i_size under page lock.
2571 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002572 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2573 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07002574 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002575 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07002576 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07002577 }
2578
Nick Piggind0217ac2007-07-19 01:47:03 -07002579 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07002580 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002581
Linus Torvalds1da177e2005-04-16 15:20:36 -07002582page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002583 /*
2584 * Umm, take care of errors if the page isn't up-to-date.
2585 * Try to re-read it _once_. We do this synchronously,
2586 * because there really aren't any performance issues here
2587 * and we need to check for errors.
2588 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002589 ClearPageError(page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002590 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Zach Brown994fc28c2005-12-15 14:28:17 -08002591 error = mapping->a_ops->readpage(file, page);
Miklos Szeredi3ef0f722008-05-14 16:05:37 -07002592 if (!error) {
2593 wait_on_page_locked(page);
2594 if (!PageUptodate(page))
2595 error = -EIO;
2596 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002597 if (fpin)
2598 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002599 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07002600
2601 if (!error || error == AOP_TRUNCATED_PAGE)
2602 goto retry_find;
2603
2604 /* Things didn't work out. Return zero to tell the mm layer so. */
2605 shrink_readahead_size_eio(file, ra);
Nick Piggind0217ac2007-07-19 01:47:03 -07002606 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002607
2608out_retry:
2609 /*
2610 * We dropped the mmap_sem, we need to return to the fault handler to
2611 * re-find the vma and come back and find our hopefully still populated
2612 * page.
2613 */
2614 if (page)
2615 put_page(page);
2616 if (fpin)
2617 fput(fpin);
2618 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07002619}
2620EXPORT_SYMBOL(filemap_fault);
2621
Jan Kara82b0f8c2016-12-14 15:06:58 -08002622void filemap_map_pages(struct vm_fault *vmf,
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002623 pgoff_t start_pgoff, pgoff_t end_pgoff)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002624{
Jan Kara82b0f8c2016-12-14 15:06:58 -08002625 struct file *file = vmf->vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002626 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002627 pgoff_t last_pgoff = start_pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002628 unsigned long max_idx;
Matthew Wilcox070e8072018-05-17 00:08:30 -04002629 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002630 struct page *page;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002631
2632 rcu_read_lock();
Matthew Wilcox070e8072018-05-17 00:08:30 -04002633 xas_for_each(&xas, page, end_pgoff) {
2634 if (xas_retry(&xas, page))
2635 continue;
2636 if (xa_is_value(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002637 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002638
Michal Hockoe0975b22018-12-28 00:38:36 -08002639 /*
2640 * Check for a locked page first, as a speculative
2641 * reference may adversely influence page migration.
2642 */
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002643 if (PageLocked(page))
Michal Hockoe0975b22018-12-28 00:38:36 -08002644 goto next;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002645 if (!page_cache_get_speculative(page))
Matthew Wilcox070e8072018-05-17 00:08:30 -04002646 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002647
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002648 /* Has the page moved or been split? */
Matthew Wilcox070e8072018-05-17 00:08:30 -04002649 if (unlikely(page != xas_reload(&xas)))
2650 goto skip;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002651 page = find_subpage(page, xas.xa_index);
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002652
2653 if (!PageUptodate(page) ||
2654 PageReadahead(page) ||
2655 PageHWPoison(page))
2656 goto skip;
2657 if (!trylock_page(page))
2658 goto skip;
2659
2660 if (page->mapping != mapping || !PageUptodate(page))
2661 goto unlock;
2662
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002663 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2664 if (page->index >= max_idx)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002665 goto unlock;
2666
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002667 if (file->f_ra.mmap_miss > 0)
2668 file->f_ra.mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002669
Matthew Wilcox070e8072018-05-17 00:08:30 -04002670 vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002671 if (vmf->pte)
Matthew Wilcox070e8072018-05-17 00:08:30 -04002672 vmf->pte += xas.xa_index - last_pgoff;
2673 last_pgoff = xas.xa_index;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002674 if (alloc_set_pte(vmf, NULL, page))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002675 goto unlock;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002676 unlock_page(page);
2677 goto next;
2678unlock:
2679 unlock_page(page);
2680skip:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002681 put_page(page);
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002682next:
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002683 /* Huge page is mapped? No need to proceed. */
Jan Kara82b0f8c2016-12-14 15:06:58 -08002684 if (pmd_trans_huge(*vmf->pmd))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002685 break;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002686 }
2687 rcu_read_unlock();
2688}
2689EXPORT_SYMBOL(filemap_map_pages);
2690
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002691vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02002692{
2693 struct page *page = vmf->page;
Dave Jiang11bac802017-02-24 14:56:41 -08002694 struct inode *inode = file_inode(vmf->vma->vm_file);
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002695 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02002696
Jan Kara14da9202012-06-12 16:20:37 +02002697 sb_start_pagefault(inode->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08002698 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002699 lock_page(page);
2700 if (page->mapping != inode->i_mapping) {
2701 unlock_page(page);
2702 ret = VM_FAULT_NOPAGE;
2703 goto out;
2704 }
Jan Kara14da9202012-06-12 16:20:37 +02002705 /*
2706 * We mark the page dirty already here so that when freeze is in
2707 * progress, we are guaranteed that writeback during freezing will
2708 * see the dirty page and writeprotect it again.
2709 */
2710 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08002711 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002712out:
Jan Kara14da9202012-06-12 16:20:37 +02002713 sb_end_pagefault(inode->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002714 return ret;
2715}
Jan Kara4fcf1c62012-06-12 16:20:29 +02002716
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04002717const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07002718 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002719 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02002720 .page_mkwrite = filemap_page_mkwrite,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002721};
2722
2723/* This is used for a general mmap of a disk file */
2724
2725int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2726{
2727 struct address_space *mapping = file->f_mapping;
2728
2729 if (!mapping->a_ops->readpage)
2730 return -ENOEXEC;
2731 file_accessed(file);
2732 vma->vm_ops = &generic_file_vm_ops;
2733 return 0;
2734}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002735
2736/*
2737 * This is for filesystems which do not implement ->writepage.
2738 */
2739int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2740{
2741 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2742 return -EINVAL;
2743 return generic_file_mmap(file, vma);
2744}
2745#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07002746vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann453972282018-04-13 15:35:27 -07002747{
Souptick Joarder4b96a372018-10-26 15:04:03 -07002748 return VM_FAULT_SIGBUS;
Arnd Bergmann453972282018-04-13 15:35:27 -07002749}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002750int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2751{
2752 return -ENOSYS;
2753}
2754int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2755{
2756 return -ENOSYS;
2757}
2758#endif /* CONFIG_MMU */
2759
Arnd Bergmann453972282018-04-13 15:35:27 -07002760EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002761EXPORT_SYMBOL(generic_file_mmap);
2762EXPORT_SYMBOL(generic_file_readonly_mmap);
2763
Sasha Levin67f9fd92014-04-03 14:48:18 -07002764static struct page *wait_on_page_read(struct page *page)
2765{
2766 if (!IS_ERR(page)) {
2767 wait_on_page_locked(page);
2768 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002769 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07002770 page = ERR_PTR(-EIO);
2771 }
2772 }
2773 return page;
2774}
2775
Mel Gorman32b63522016-03-15 14:55:36 -07002776static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07002777 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002778 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002779 void *data,
2780 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002781{
Nick Piggineb2be182007-10-16 01:24:57 -07002782 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002783 int err;
2784repeat:
2785 page = find_get_page(mapping, index);
2786 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08002787 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002788 if (!page)
2789 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002790 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002791 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002792 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07002793 if (err == -EEXIST)
2794 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05002795 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002796 return ERR_PTR(err);
2797 }
Mel Gorman32b63522016-03-15 14:55:36 -07002798
2799filler:
Christoph Hellwig6c45b452019-07-11 20:55:20 -07002800 if (filler)
2801 err = filler(data, page);
2802 else
2803 err = mapping->a_ops->readpage(data, page);
2804
Linus Torvalds1da177e2005-04-16 15:20:36 -07002805 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002806 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002807 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002808 }
Mel Gorman32b63522016-03-15 14:55:36 -07002809
2810 page = wait_on_page_read(page);
2811 if (IS_ERR(page))
2812 return page;
2813 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002814 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002815 if (PageUptodate(page))
2816 goto out;
2817
Mel Gormanebded022016-03-15 14:55:39 -07002818 /*
2819 * Page is not up to date and may be locked due one of the following
2820 * case a: Page is being filled and the page lock is held
2821 * case b: Read/write error clearing the page uptodate status
2822 * case c: Truncation in progress (page locked)
2823 * case d: Reclaim in progress
2824 *
2825 * Case a, the page will be up to date when the page is unlocked.
2826 * There is no need to serialise on the page lock here as the page
2827 * is pinned so the lock gives no additional protection. Even if the
2828 * the page is truncated, the data is still valid if PageUptodate as
2829 * it's a race vs truncate race.
2830 * Case b, the page will not be up to date
2831 * Case c, the page may be truncated but in itself, the data may still
2832 * be valid after IO completes as it's a read vs truncate race. The
2833 * operation must restart if the page is not uptodate on unlock but
2834 * otherwise serialising on page lock to stabilise the mapping gives
2835 * no additional guarantees to the caller as the page lock is
2836 * released before return.
2837 * Case d, similar to truncation. If reclaim holds the page lock, it
2838 * will be a race with remove_mapping that determines if the mapping
2839 * is valid on unlock but otherwise the data is valid and there is
2840 * no need to serialise with page lock.
2841 *
2842 * As the page lock gives no additional guarantee, we optimistically
2843 * wait on the page to be unlocked and check if it's up to date and
2844 * use the page if it is. Otherwise, the page lock is required to
2845 * distinguish between the different cases. The motivation is that we
2846 * avoid spurious serialisations and wakeups when multiple processes
2847 * wait on the same page for IO to complete.
2848 */
2849 wait_on_page_locked(page);
2850 if (PageUptodate(page))
2851 goto out;
2852
2853 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002854 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07002855
2856 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002857 if (!page->mapping) {
2858 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002859 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002860 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002861 }
Mel Gormanebded022016-03-15 14:55:39 -07002862
2863 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002864 if (PageUptodate(page)) {
2865 unlock_page(page);
2866 goto out;
2867 }
Mel Gorman32b63522016-03-15 14:55:36 -07002868 goto filler;
2869
David Howellsc855ff32007-05-09 13:42:20 +01002870out:
Nick Piggin6fe69002007-05-06 14:49:04 -07002871 mark_page_accessed(page);
2872 return page;
2873}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002874
2875/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07002876 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002877 * @mapping: the page's address_space
2878 * @index: the page index
2879 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002880 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002881 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002882 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07002883 * not set, try to fill the page and wait for it to become unlocked.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002884 *
2885 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002886 *
2887 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002888 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07002889struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002890 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002891 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002892 void *data)
2893{
Christoph Hellwigd322a8e2019-07-11 20:55:17 -07002894 return do_read_cache_page(mapping, index, filler, data,
2895 mapping_gfp_mask(mapping));
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002896}
Sasha Levin67f9fd92014-04-03 14:48:18 -07002897EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002898
2899/**
2900 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2901 * @mapping: the page's address_space
2902 * @index: the page index
2903 * @gfp: the page allocator flags to use if allocating
2904 *
2905 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002906 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002907 *
2908 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002909 *
2910 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002911 */
2912struct page *read_cache_page_gfp(struct address_space *mapping,
2913 pgoff_t index,
2914 gfp_t gfp)
2915{
Christoph Hellwig6c45b452019-07-11 20:55:20 -07002916 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002917}
2918EXPORT_SYMBOL(read_cache_page_gfp);
2919
Nick Piggin2f718ff2007-10-16 01:24:59 -07002920/*
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002921 * Don't operate on ranges the page cache doesn't support, and don't exceed the
2922 * LFS limits. If pos is under the limit it becomes a short access. If it
2923 * exceeds the limit we return -EFBIG.
2924 */
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002925static int generic_write_check_limits(struct file *file, loff_t pos,
2926 loff_t *count)
2927{
Amir Goldstein646955c2019-06-05 08:04:48 -07002928 struct inode *inode = file->f_mapping->host;
2929 loff_t max_size = inode->i_sb->s_maxbytes;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002930 loff_t limit = rlimit(RLIMIT_FSIZE);
2931
2932 if (limit != RLIM_INFINITY) {
2933 if (pos >= limit) {
2934 send_sig(SIGXFSZ, current, 0);
2935 return -EFBIG;
2936 }
2937 *count = min(*count, limit - pos);
2938 }
2939
Amir Goldstein646955c2019-06-05 08:04:48 -07002940 if (!(file->f_flags & O_LARGEFILE))
2941 max_size = MAX_NON_LFS;
2942
2943 if (unlikely(pos >= max_size))
2944 return -EFBIG;
2945
2946 *count = min(*count, max_size - pos);
2947
2948 return 0;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002949}
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
Darrick J. Wongdc617f22019-08-20 07:55:16 -07002965 if (IS_SWAPFILE(inode))
2966 return -ETXTBSY;
2967
Al Viro3309dd02015-04-09 12:55:47 -04002968 if (!iov_iter_count(from))
2969 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002970
Al Viro0fa6b002015-04-04 04:05:48 -04002971 /* FIXME: this is for backwards compatibility with 2.4 */
Al Viro2ba48ce2015-04-09 13:52:01 -04002972 if (iocb->ki_flags & IOCB_APPEND)
Al Viro3309dd02015-04-09 12:55:47 -04002973 iocb->ki_pos = i_size_read(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002974
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002975 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2976 return -EINVAL;
2977
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002978 count = iov_iter_count(from);
2979 ret = generic_write_check_limits(file, iocb->ki_pos, &count);
2980 if (ret)
2981 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002982
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002983 iov_iter_truncate(from, count);
Al Viro3309dd02015-04-09 12:55:47 -04002984 return iov_iter_count(from);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002985}
2986EXPORT_SYMBOL(generic_write_checks);
2987
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11002988/*
2989 * Performs necessary checks before doing a clone.
2990 *
Amir Goldstein646955c2019-06-05 08:04:48 -07002991 * Can adjust amount of bytes to clone via @req_count argument.
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11002992 * Returns appropriate error code that caller should return or
2993 * zero in case the clone should be allowed.
2994 */
2995int generic_remap_checks(struct file *file_in, loff_t pos_in,
2996 struct file *file_out, loff_t pos_out,
Darrick J. Wong42ec3d42018-10-30 10:41:49 +11002997 loff_t *req_count, unsigned int remap_flags)
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11002998{
2999 struct inode *inode_in = file_in->f_mapping->host;
3000 struct inode *inode_out = file_out->f_mapping->host;
3001 uint64_t count = *req_count;
3002 uint64_t bcount;
3003 loff_t size_in, size_out;
3004 loff_t bs = inode_out->i_sb->s_blocksize;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003005 int ret;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003006
3007 /* The start of both ranges must be aligned to an fs block. */
3008 if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_out, bs))
3009 return -EINVAL;
3010
3011 /* Ensure offsets don't wrap. */
3012 if (pos_in + count < pos_in || pos_out + count < pos_out)
3013 return -EINVAL;
3014
3015 size_in = i_size_read(inode_in);
3016 size_out = i_size_read(inode_out);
3017
3018 /* Dedupe requires both ranges to be within EOF. */
Darrick J. Wong3d281932018-10-30 10:41:34 +11003019 if ((remap_flags & REMAP_FILE_DEDUP) &&
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003020 (pos_in >= size_in || pos_in + count > size_in ||
3021 pos_out >= size_out || pos_out + count > size_out))
3022 return -EINVAL;
3023
3024 /* Ensure the infile range is within the infile. */
3025 if (pos_in >= size_in)
3026 return -EINVAL;
3027 count = min(count, size_in - (uint64_t)pos_in);
3028
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003029 ret = generic_write_check_limits(file_out, pos_out, &count);
3030 if (ret)
3031 return ret;
3032
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003033 /*
3034 * If the user wanted us to link to the infile's EOF, round up to the
3035 * next block boundary for this check.
3036 *
3037 * Otherwise, make sure the count is also block-aligned, having
3038 * already confirmed the starting offsets' block alignment.
3039 */
3040 if (pos_in + count == size_in) {
3041 bcount = ALIGN(size_in, bs) - pos_in;
3042 } else {
3043 if (!IS_ALIGNED(count, bs))
Darrick J. Wongeca36542018-10-30 10:42:10 +11003044 count = ALIGN_DOWN(count, bs);
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003045 bcount = count;
3046 }
3047
3048 /* Don't allow overlapped cloning within the same file. */
3049 if (inode_in == inode_out &&
3050 pos_out + bcount > pos_in &&
3051 pos_out < pos_in + bcount)
3052 return -EINVAL;
3053
Darrick J. Wongeca36542018-10-30 10:42:10 +11003054 /*
3055 * We shortened the request but the caller can't deal with that, so
3056 * bounce the request back to userspace.
3057 */
3058 if (*req_count != count && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003059 return -EINVAL;
3060
Darrick J. Wongeca36542018-10-30 10:42:10 +11003061 *req_count = count;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003062 return 0;
3063}
3064
Amir Goldsteina3171352019-06-05 08:04:48 -07003065
3066/*
3067 * Performs common checks before doing a file copy/clone
3068 * from @file_in to @file_out.
3069 */
3070int generic_file_rw_checks(struct file *file_in, struct file *file_out)
3071{
3072 struct inode *inode_in = file_inode(file_in);
3073 struct inode *inode_out = file_inode(file_out);
3074
3075 /* Don't copy dirs, pipes, sockets... */
3076 if (S_ISDIR(inode_in->i_mode) || S_ISDIR(inode_out->i_mode))
3077 return -EISDIR;
3078 if (!S_ISREG(inode_in->i_mode) || !S_ISREG(inode_out->i_mode))
3079 return -EINVAL;
3080
3081 if (!(file_in->f_mode & FMODE_READ) ||
3082 !(file_out->f_mode & FMODE_WRITE) ||
3083 (file_out->f_flags & O_APPEND))
3084 return -EBADF;
3085
3086 return 0;
3087}
3088
Amir Goldstein96e6e8f2019-06-05 08:04:49 -07003089/*
3090 * Performs necessary checks before doing a file copy
3091 *
3092 * Can adjust amount of bytes to copy via @req_count argument.
3093 * Returns appropriate error code that caller should return or
3094 * zero in case the copy should be allowed.
3095 */
3096int generic_copy_file_checks(struct file *file_in, loff_t pos_in,
3097 struct file *file_out, loff_t pos_out,
3098 size_t *req_count, unsigned int flags)
3099{
3100 struct inode *inode_in = file_inode(file_in);
3101 struct inode *inode_out = file_inode(file_out);
3102 uint64_t count = *req_count;
3103 loff_t size_in;
3104 int ret;
3105
3106 ret = generic_file_rw_checks(file_in, file_out);
3107 if (ret)
3108 return ret;
3109
3110 /* Don't touch certain kinds of inodes */
3111 if (IS_IMMUTABLE(inode_out))
3112 return -EPERM;
3113
3114 if (IS_SWAPFILE(inode_in) || IS_SWAPFILE(inode_out))
3115 return -ETXTBSY;
3116
3117 /* Ensure offsets don't wrap. */
3118 if (pos_in + count < pos_in || pos_out + count < pos_out)
3119 return -EOVERFLOW;
3120
3121 /* Shorten the copy to EOF */
3122 size_in = i_size_read(inode_in);
3123 if (pos_in >= size_in)
3124 count = 0;
3125 else
3126 count = min(count, size_in - (uint64_t)pos_in);
3127
3128 ret = generic_write_check_limits(file_out, pos_out, &count);
3129 if (ret)
3130 return ret;
3131
3132 /* Don't allow overlapped copying within the same file. */
3133 if (inode_in == inode_out &&
3134 pos_out + count > pos_in &&
3135 pos_out < pos_in + count)
3136 return -EINVAL;
3137
3138 *req_count = count;
3139 return 0;
3140}
3141
Nick Pigginafddba42007-10-16 01:25:01 -07003142int pagecache_write_begin(struct file *file, struct address_space *mapping,
3143 loff_t pos, unsigned len, unsigned flags,
3144 struct page **pagep, void **fsdata)
3145{
3146 const struct address_space_operations *aops = mapping->a_ops;
3147
Nick Piggin4e02ed42008-10-29 14:00:55 -07003148 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003149 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003150}
3151EXPORT_SYMBOL(pagecache_write_begin);
3152
3153int pagecache_write_end(struct file *file, struct address_space *mapping,
3154 loff_t pos, unsigned len, unsigned copied,
3155 struct page *page, void *fsdata)
3156{
3157 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003158
Nick Piggin4e02ed42008-10-29 14:00:55 -07003159 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003160}
3161EXPORT_SYMBOL(pagecache_write_end);
3162
Linus Torvalds1da177e2005-04-16 15:20:36 -07003163ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003164generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003165{
3166 struct file *file = iocb->ki_filp;
3167 struct address_space *mapping = file->f_mapping;
3168 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003169 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003170 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003171 size_t write_len;
3172 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003173
Al Viro0c949332014-03-22 06:51:37 -04003174 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003175 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003176
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003177 if (iocb->ki_flags & IOCB_NOWAIT) {
3178 /* If there are pages to writeback, return */
3179 if (filemap_range_has_page(inode->i_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003180 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003181 return -EAGAIN;
3182 } else {
3183 written = filemap_write_and_wait_range(mapping, pos,
3184 pos + write_len - 1);
3185 if (written)
3186 goto out;
3187 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003188
3189 /*
3190 * After a write we want buffered reads to be sure to go to disk to get
3191 * the new data. We invalidate clean cached page from the region we're
3192 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003193 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003194 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003195 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003196 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003197 /*
3198 * If a page can not be invalidated, return 0 to fall back
3199 * to buffered write.
3200 */
3201 if (written) {
3202 if (written == -EBUSY)
3203 return 0;
3204 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003205 }
3206
Al Viro639a93a52017-04-13 14:10:15 -04003207 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003208
3209 /*
3210 * Finally, try again to invalidate clean pages which might have been
3211 * cached by non-direct readahead, or faulted in by get_user_pages()
3212 * if the source of the write was an mmap'ed region of the file
3213 * we're writing. Either one is a pretty crazy thing to do,
3214 * so we don't support it 100%. If this invalidation
3215 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003216 *
3217 * Most of the time we do not need this since dio_complete() will do
3218 * the invalidation for us. However there are some file systems that
3219 * do not end up with dio_complete() being called, so let's not break
3220 * them by removing it completely
Christoph Hellwiga969e902008-07-23 21:27:04 -07003221 */
Lukas Czerner332391a2017-09-21 08:16:29 -06003222 if (mapping->nrpages)
3223 invalidate_inode_pages2_range(mapping,
3224 pos >> PAGE_SHIFT, end);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003225
Linus Torvalds1da177e2005-04-16 15:20:36 -07003226 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003227 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003228 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003229 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3230 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003231 mark_inode_dirty(inode);
3232 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003233 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003234 }
Al Viro639a93a52017-04-13 14:10:15 -04003235 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003236out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003237 return written;
3238}
3239EXPORT_SYMBOL(generic_file_direct_write);
3240
Nick Piggineb2be182007-10-16 01:24:57 -07003241/*
3242 * Find or create a page at the given pagecache position. Return the locked
3243 * page. This function is specifically for buffered writes.
3244 */
Nick Piggin54566b22009-01-04 12:00:53 -08003245struct page *grab_cache_page_write_begin(struct address_space *mapping,
3246 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003247{
Nick Piggineb2be182007-10-16 01:24:57 -07003248 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003249 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003250
Nick Piggin54566b22009-01-04 12:00:53 -08003251 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003252 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003253
Mel Gorman2457aec2014-06-04 16:10:31 -07003254 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003255 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003256 if (page)
3257 wait_for_stable_page(page);
3258
Nick Piggineb2be182007-10-16 01:24:57 -07003259 return page;
3260}
Nick Piggin54566b22009-01-04 12:00:53 -08003261EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003262
Al Viro3b93f912014-02-11 21:34:08 -05003263ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003264 struct iov_iter *i, loff_t pos)
3265{
3266 struct address_space *mapping = file->f_mapping;
3267 const struct address_space_operations *a_ops = mapping->a_ops;
3268 long status = 0;
3269 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003270 unsigned int flags = 0;
3271
Nick Pigginafddba42007-10-16 01:25:01 -07003272 do {
3273 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003274 unsigned long offset; /* Offset into pagecache page */
3275 unsigned long bytes; /* Bytes to write to page */
3276 size_t copied; /* Bytes copied from user */
3277 void *fsdata;
3278
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003279 offset = (pos & (PAGE_SIZE - 1));
3280 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003281 iov_iter_count(i));
3282
3283again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003284 /*
3285 * Bring in the user page that we will copy from _first_.
3286 * Otherwise there's a nasty deadlock on copying from the
3287 * same page as we're writing to, without it being marked
3288 * up-to-date.
3289 *
3290 * Not only is this an optimisation, but it is also required
3291 * to check that the address is actually valid, when atomic
3292 * usercopies are used, below.
3293 */
3294 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3295 status = -EFAULT;
3296 break;
3297 }
3298
Jan Kara296291c2015-10-22 13:32:21 -07003299 if (fatal_signal_pending(current)) {
3300 status = -EINTR;
3301 break;
3302 }
3303
Nick Piggin674b8922007-10-16 01:25:03 -07003304 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003305 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003306 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003307 break;
3308
anfei zhou931e80e2010-02-02 13:44:02 -08003309 if (mapping_writably_mapped(mapping))
3310 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003311
Nick Pigginafddba42007-10-16 01:25:01 -07003312 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
Nick Pigginafddba42007-10-16 01:25:01 -07003313 flush_dcache_page(page);
3314
3315 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3316 page, fsdata);
3317 if (unlikely(status < 0))
3318 break;
3319 copied = status;
3320
3321 cond_resched();
3322
Nick Piggin124d3b72008-02-02 15:01:17 +01003323 iov_iter_advance(i, copied);
Nick Pigginafddba42007-10-16 01:25:01 -07003324 if (unlikely(copied == 0)) {
3325 /*
3326 * If we were unable to copy any data at all, we must
3327 * fall back to a single segment length write.
3328 *
3329 * If we didn't fallback here, we could livelock
3330 * because not all segments in the iov can be copied at
3331 * once without a pagefault.
3332 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003333 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003334 iov_iter_single_seg_count(i));
3335 goto again;
3336 }
Nick Pigginafddba42007-10-16 01:25:01 -07003337 pos += copied;
3338 written += copied;
3339
3340 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003341 } while (iov_iter_count(i));
3342
3343 return written ? written : status;
3344}
Al Viro3b93f912014-02-11 21:34:08 -05003345EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003346
Jan Karae4dd9de2009-08-17 18:10:06 +02003347/**
Al Viro81742022014-04-03 03:17:43 -04003348 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003349 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003350 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003351 *
3352 * This function does all the work needed for actually writing data to a
3353 * file. It does all basic checks, removes SUID from the file, updates
3354 * modification times and calls proper subroutines depending on whether we
3355 * do direct IO or a standard buffered write.
3356 *
3357 * It expects i_mutex to be grabbed unless we work on a block device or similar
3358 * object which does not need locking at all.
3359 *
3360 * This function does *not* take care of syncing data in case of O_SYNC write.
3361 * A caller has to handle it. This is mainly due to the fact that we want to
3362 * avoid syncing under i_mutex.
Mike Rapoporta862f682019-03-05 15:48:42 -08003363 *
3364 * Return:
3365 * * number of bytes written, even for truncated writes
3366 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003367 */
Al Viro81742022014-04-03 03:17:43 -04003368ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003369{
3370 struct file *file = iocb->ki_filp;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003371 struct address_space * mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003372 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003373 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003374 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003375 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003376
Linus Torvalds1da177e2005-04-16 15:20:36 -07003377 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003378 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003379 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003380 if (err)
3381 goto out;
3382
Josef Bacikc3b2da32012-03-26 09:59:21 -04003383 err = file_update_time(file);
3384 if (err)
3385 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003386
Al Viro2ba48ce2015-04-09 13:52:01 -04003387 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003388 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003389
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003390 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003391 /*
3392 * If the write stopped short of completing, fall back to
3393 * buffered writes. Some filesystems do this for writes to
3394 * holes, for example. For DAX files, a buffered write will
3395 * not succeed (even if it did, DAX does not handle dirty
3396 * page-cache pages correctly).
3397 */
Al Viro0b8def92015-04-07 10:22:53 -04003398 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003399 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003400
Al Viro0b8def92015-04-07 10:22:53 -04003401 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003402 /*
Al Viro3b93f912014-02-11 21:34:08 -05003403 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003404 * then we want to return the number of bytes which were
3405 * direct-written, or the error code if that was zero. Note
3406 * that this differs from normal direct-io semantics, which
3407 * will return -EFOO even if some bytes were written.
3408 */
Al Viro60bb4522014-08-08 12:39:16 -04003409 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003410 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003411 goto out;
3412 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003413 /*
3414 * We need to ensure that the page cache pages are written to
3415 * disk and invalidated to preserve the expected O_DIRECT
3416 * semantics.
3417 */
Al Viro3b93f912014-02-11 21:34:08 -05003418 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003419 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003420 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003421 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003422 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003423 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003424 pos >> PAGE_SHIFT,
3425 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003426 } else {
3427 /*
3428 * We don't know how much we wrote, so just return
3429 * the number of bytes which were direct-written
3430 */
3431 }
3432 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003433 written = generic_perform_write(file, from, iocb->ki_pos);
3434 if (likely(written > 0))
3435 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003436 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003437out:
3438 current->backing_dev_info = NULL;
3439 return written ? written : err;
3440}
Al Viro81742022014-04-03 03:17:43 -04003441EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003442
Jan Karae4dd9de2009-08-17 18:10:06 +02003443/**
Al Viro81742022014-04-03 03:17:43 -04003444 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003445 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003446 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003447 *
Al Viro81742022014-04-03 03:17:43 -04003448 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003449 * filesystems. It takes care of syncing the file in case of O_SYNC file
3450 * and acquires i_mutex as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003451 * Return:
3452 * * negative error code if no data has been written at all of
3453 * vfs_fsync_range() failed for a synchronous write
3454 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003455 */
Al Viro81742022014-04-03 03:17:43 -04003456ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003457{
3458 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003459 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003460 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003461
Al Viro59551022016-01-22 15:40:57 -05003462 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003463 ret = generic_write_checks(iocb, from);
3464 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003465 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003466 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003467
Christoph Hellwige2592212016-04-07 08:52:01 -07003468 if (ret > 0)
3469 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003470 return ret;
3471}
Al Viro81742022014-04-03 03:17:43 -04003472EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003473
David Howellscf9a2ae2006-08-29 19:05:54 +01003474/**
3475 * try_to_release_page() - release old fs-specific metadata on a page
3476 *
3477 * @page: the page which the kernel is trying to free
3478 * @gfp_mask: memory allocation flags (and I/O mode)
3479 *
3480 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003481 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003482 *
David Howells266cf652009-04-03 16:42:36 +01003483 * This may also be called if PG_fscache is set on a page, indicating that the
3484 * page is known to the local caching routines.
3485 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003486 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003487 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003488 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003489 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003490 */
3491int try_to_release_page(struct page *page, gfp_t gfp_mask)
3492{
3493 struct address_space * const mapping = page->mapping;
3494
3495 BUG_ON(!PageLocked(page));
3496 if (PageWriteback(page))
3497 return 0;
3498
3499 if (mapping && mapping->a_ops->releasepage)
3500 return mapping->a_ops->releasepage(page, gfp_mask);
3501 return try_to_free_buffers(page);
3502}
3503
3504EXPORT_SYMBOL(try_to_release_page);