blob: 6dd9a2274c805ad670959418f0caf27292c16bc4 [file] [log] [blame]
Thomas Gleixner457c8992019-05-19 13:08:55 +01001// SPDX-License-Identifier: GPL-2.0-only
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
3 * linux/mm/filemap.c
4 *
5 * Copyright (C) 1994-1999 Linus Torvalds
6 */
7
8/*
9 * This file handles the generic file mmap semantics used by
10 * most "normal" filesystems (but you don't /have/ to use this:
11 * the NFS filesystem used to do this differently, for example)
12 */
Paul Gortmakerb95f1b312011-10-16 02:01:52 -040013#include <linux/export.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070014#include <linux/compiler.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080015#include <linux/dax.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070016#include <linux/fs.h>
Ingo Molnar3f07c012017-02-08 18:51:30 +010017#include <linux/sched/signal.h>
Hiro Yoshiokac22ce142006-06-23 02:04:16 -070018#include <linux/uaccess.h>
Randy.Dunlapc59ede72006-01-11 12:17:46 -080019#include <linux/capability.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070020#include <linux/kernel_stat.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090021#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070022#include <linux/mm.h>
23#include <linux/swap.h>
24#include <linux/mman.h>
25#include <linux/pagemap.h>
26#include <linux/file.h>
27#include <linux/uio.h>
Josef Bacikcfcbfb12019-05-13 17:21:04 -070028#include <linux/error-injection.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070029#include <linux/hash.h>
30#include <linux/writeback.h>
Linus Torvalds53253382007-10-18 14:47:32 -070031#include <linux/backing-dev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/pagevec.h>
33#include <linux/blkdev.h>
34#include <linux/security.h>
Paul Jackson44110fe2006-03-24 03:16:04 -080035#include <linux/cpuset.h>
Johannes Weiner00501b52014-08-08 14:19:20 -070036#include <linux/hugetlb.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080037#include <linux/memcontrol.h>
Dan Magenheimerc515e1f2011-05-26 10:01:43 -060038#include <linux/cleancache.h>
Mel Gormanc7df8ad2017-11-15 17:37:41 -080039#include <linux/shmem_fs.h>
Kirill A. Shutemovf1820362014-04-07 15:37:19 -070040#include <linux/rmap.h>
Johannes Weinerb1d29ba2018-10-26 15:06:08 -070041#include <linux/delayacct.h>
Johannes Weinereb414682018-10-26 15:06:27 -070042#include <linux/psi.h>
Nick Piggin0f8053a2006-03-22 00:08:33 -080043#include "internal.h"
44
Robert Jarzmikfe0bfaa2013-04-29 15:06:10 -070045#define CREATE_TRACE_POINTS
46#include <trace/events/filemap.h>
47
Linus Torvalds1da177e2005-04-16 15:20:36 -070048/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070049 * FIXME: remove all knowledge of the buffer layer from the core VM
50 */
Jan Kara148f9482009-08-17 19:52:36 +020051#include <linux/buffer_head.h> /* for try_to_free_buffers */
Linus Torvalds1da177e2005-04-16 15:20:36 -070052
Linus Torvalds1da177e2005-04-16 15:20:36 -070053#include <asm/mman.h>
54
55/*
56 * Shared mappings implemented 30.11.1994. It's not fully working yet,
57 * though.
58 *
59 * Shared mappings now work. 15.8.1995 Bruno.
60 *
61 * finished 'unifying' the page and buffer cache and SMP-threaded the
62 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
63 *
64 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
65 */
66
67/*
68 * Lock ordering:
69 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080070 * ->i_mmap_rwsem (truncate_pagecache)
Linus Torvalds1da177e2005-04-16 15:20:36 -070071 * ->private_lock (__free_pte->__set_page_dirty_buffers)
Hugh Dickins5d337b92005-09-03 15:54:41 -070072 * ->swap_lock (exclusive_swap_page, others)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070073 * ->i_pages lock
Linus Torvalds1da177e2005-04-16 15:20:36 -070074 *
Jes Sorensen1b1dcc12006-01-09 15:59:24 -080075 * ->i_mutex
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080076 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
Linus Torvalds1da177e2005-04-16 15:20:36 -070077 *
78 * ->mmap_sem
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080079 * ->i_mmap_rwsem
Hugh Dickinsb8072f02005-10-29 18:16:41 -070080 * ->page_table_lock or pte_lock (various, mainly in memory.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070081 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
Linus Torvalds1da177e2005-04-16 15:20:36 -070082 *
83 * ->mmap_sem
84 * ->lock_page (access_process_vm)
85 *
Al Viroccad2362014-02-11 22:36:48 -050086 * ->i_mutex (generic_perform_write)
Nick Piggin82591e62006-10-19 23:29:10 -070087 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
Linus Torvalds1da177e2005-04-16 15:20:36 -070088 *
Christoph Hellwigf758eea2011-04-21 18:19:44 -060089 * bdi->wb.list_lock
Dave Chinnera66979a2011-03-22 22:23:41 +110090 * sb_lock (fs/fs-writeback.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070091 * ->i_pages lock (__sync_single_inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -070092 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080093 * ->i_mmap_rwsem
Linus Torvalds1da177e2005-04-16 15:20:36 -070094 * ->anon_vma.lock (vma_adjust)
95 *
96 * ->anon_vma.lock
Hugh Dickinsb8072f02005-10-29 18:16:41 -070097 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
Linus Torvalds1da177e2005-04-16 15:20:36 -070098 *
Hugh Dickinsb8072f02005-10-29 18:16:41 -070099 * ->page_table_lock or pte_lock
Hugh Dickins5d337b92005-09-03 15:54:41 -0700100 * ->swap_lock (try_to_unmap_one)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700101 * ->private_lock (try_to_unmap_one)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700102 * ->i_pages lock (try_to_unmap_one)
Andrey Ryabininf4b7e272019-03-05 15:49:39 -0800103 * ->pgdat->lru_lock (follow_page->mark_page_accessed)
104 * ->pgdat->lru_lock (check_pte_range->isolate_lru_page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700105 * ->private_lock (page_remove_rmap->set_page_dirty)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700106 * ->i_pages lock (page_remove_rmap->set_page_dirty)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600107 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100108 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
Johannes Weiner81f8c3a2016-03-15 14:57:04 -0700109 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600110 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100111 * ->inode->i_lock (zap_pte_range->set_page_dirty)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700112 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
113 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -0800114 * ->i_mmap_rwsem
Andi Kleen9a3c5312012-03-21 16:34:09 -0700115 * ->tasklist_lock (memory_failure, collect_procs_ao)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700116 */
117
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500118static void page_cache_delete(struct address_space *mapping,
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700119 struct page *page, void *shadow)
120{
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500121 XA_STATE(xas, &mapping->i_pages, page->index);
122 unsigned int nr = 1;
Kirill A. Shutemovc70b6472016-12-12 16:43:17 -0800123
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500124 mapping_set_update(&xas, mapping);
125
126 /* hugetlb pages are represented by a single entry in the xarray */
127 if (!PageHuge(page)) {
128 xas_set_order(&xas, page->index, compound_order(page));
129 nr = 1U << compound_order(page);
130 }
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700131
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700132 VM_BUG_ON_PAGE(!PageLocked(page), page);
133 VM_BUG_ON_PAGE(PageTail(page), page);
134 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
Johannes Weiner449dd692014-04-03 14:47:56 -0700135
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500136 xas_store(&xas, shadow);
137 xas_init_marks(&xas);
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200138
Jan Kara23006382017-11-15 17:37:26 -0800139 page->mapping = NULL;
140 /* Leave page->index set: truncation lookup relies upon it */
141
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200142 if (shadow) {
143 mapping->nrexceptional += nr;
144 /*
145 * Make sure the nrexceptional update is committed before
146 * the nrpages update so that final truncate racing
147 * with reclaim does not see both counters 0 at the
148 * same time and miss a shadow entry.
149 */
150 smp_wmb();
151 }
152 mapping->nrpages -= nr;
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700153}
154
Jan Kara5ecc4d82017-11-15 17:37:29 -0800155static void unaccount_page_cache_page(struct address_space *mapping,
156 struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700157{
Jan Kara5ecc4d82017-11-15 17:37:29 -0800158 int nr;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700159
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600160 /*
161 * if we're uptodate, flush out into the cleancache, otherwise
162 * invalidate any existing cleancache entries. We can't leave
163 * stale data around in the cleancache once our page is gone
164 */
165 if (PageUptodate(page) && PageMappedToDisk(page))
166 cleancache_put_page(page);
167 else
Dan Magenheimer31677602011-09-21 11:56:28 -0400168 cleancache_invalidate_page(mapping, page);
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600169
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700170 VM_BUG_ON_PAGE(PageTail(page), page);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800171 VM_BUG_ON_PAGE(page_mapped(page), page);
172 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
173 int mapcount;
174
175 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
176 current->comm, page_to_pfn(page));
177 dump_page(page, "still mapped when deleted");
178 dump_stack();
179 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
180
181 mapcount = page_mapcount(page);
182 if (mapping_exiting(mapping) &&
183 page_count(page) >= mapcount + 2) {
184 /*
185 * All vmas have already been torn down, so it's
186 * a good bet that actually the page is unmapped,
187 * and we'd prefer not to leak it: if we're wrong,
188 * some other bad page check should catch it later.
189 */
190 page_mapcount_reset(page);
Joonsoo Kim6d061f92016-05-19 17:10:46 -0700191 page_ref_sub(page, mapcount);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800192 }
193 }
194
Jan Kara76253fb2017-11-15 17:37:22 -0800195 /* hugetlb pages do not participate in page cache accounting. */
Jan Kara5ecc4d82017-11-15 17:37:29 -0800196 if (PageHuge(page))
197 return;
Jan Kara76253fb2017-11-15 17:37:22 -0800198
Jan Kara5ecc4d82017-11-15 17:37:29 -0800199 nr = hpage_nr_pages(page);
200
201 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
202 if (PageSwapBacked(page)) {
203 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
204 if (PageTransHuge(page))
205 __dec_node_page_state(page, NR_SHMEM_THPS);
206 } else {
207 VM_BUG_ON_PAGE(PageTransHuge(page), page);
Jan Kara76253fb2017-11-15 17:37:22 -0800208 }
Jan Kara5ecc4d82017-11-15 17:37:29 -0800209
210 /*
211 * At this point page must be either written or cleaned by
212 * truncate. Dirty page here signals a bug and loss of
213 * unwritten data.
214 *
215 * This fixes dirty accounting after removing the page entirely
216 * but leaves PageDirty set: it has no effect for truncated
217 * page and anyway will be cleared before returning page into
218 * buddy allocator.
219 */
220 if (WARN_ON_ONCE(PageDirty(page)))
221 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
222}
223
224/*
225 * Delete a page from the page cache and free it. Caller has to make
226 * sure the page is locked and that nobody else uses it - or that usage
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700227 * is safe. The caller must hold the i_pages lock.
Jan Kara5ecc4d82017-11-15 17:37:29 -0800228 */
229void __delete_from_page_cache(struct page *page, void *shadow)
230{
231 struct address_space *mapping = page->mapping;
232
233 trace_mm_filemap_delete_from_page_cache(page);
234
235 unaccount_page_cache_page(mapping, page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500236 page_cache_delete(mapping, page, shadow);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700237}
238
Jan Kara59c66c52017-11-15 17:37:18 -0800239static void page_cache_free_page(struct address_space *mapping,
240 struct page *page)
241{
242 void (*freepage)(struct page *);
243
244 freepage = mapping->a_ops->freepage;
245 if (freepage)
246 freepage(page);
247
248 if (PageTransHuge(page) && !PageHuge(page)) {
249 page_ref_sub(page, HPAGE_PMD_NR);
250 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
251 } else {
252 put_page(page);
253 }
254}
255
Minchan Kim702cfbf2011-03-22 16:32:43 -0700256/**
257 * delete_from_page_cache - delete page from page cache
258 * @page: the page which the kernel is trying to remove from page cache
259 *
260 * This must be called only on pages that have been verified to be in the page
261 * cache and locked. It will never put the page into the free list, the caller
262 * has a reference on the page.
263 */
264void delete_from_page_cache(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700265{
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700266 struct address_space *mapping = page_mapping(page);
Greg Thelenc4843a72015-05-22 17:13:16 -0400267 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700268
Matt Mackallcd7619d2005-05-01 08:59:01 -0700269 BUG_ON(!PageLocked(page));
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700270 xa_lock_irqsave(&mapping->i_pages, flags);
Johannes Weiner62cccb82016-03-15 14:57:22 -0700271 __delete_from_page_cache(page, NULL);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700272 xa_unlock_irqrestore(&mapping->i_pages, flags);
Linus Torvalds6072d132010-12-01 13:35:19 -0500273
Jan Kara59c66c52017-11-15 17:37:18 -0800274 page_cache_free_page(mapping, page);
Minchan Kim97cecb52011-03-22 16:30:53 -0700275}
276EXPORT_SYMBOL(delete_from_page_cache);
277
Jan Karaaa65c292017-11-15 17:37:33 -0800278/*
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500279 * page_cache_delete_batch - delete several pages from page cache
Jan Karaaa65c292017-11-15 17:37:33 -0800280 * @mapping: the mapping to which pages belong
281 * @pvec: pagevec with pages to delete
282 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700283 * The function walks over mapping->i_pages and removes pages passed in @pvec
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700284 * from the mapping. The function expects @pvec to be sorted by page index.
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700285 * It tolerates holes in @pvec (mapping entries at those indices are not
Jan Karaaa65c292017-11-15 17:37:33 -0800286 * modified). The function expects only THP head pages to be present in the
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700287 * @pvec and takes care to delete all corresponding tail pages from the
288 * mapping as well.
Jan Karaaa65c292017-11-15 17:37:33 -0800289 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700290 * The function expects the i_pages lock to be held.
Jan Karaaa65c292017-11-15 17:37:33 -0800291 */
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500292static void page_cache_delete_batch(struct address_space *mapping,
Jan Karaaa65c292017-11-15 17:37:33 -0800293 struct pagevec *pvec)
294{
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500295 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
Jan Karaaa65c292017-11-15 17:37:33 -0800296 int total_pages = 0;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700297 int i = 0, tail_pages = 0;
Jan Karaaa65c292017-11-15 17:37:33 -0800298 struct page *page;
Jan Karaaa65c292017-11-15 17:37:33 -0800299
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500300 mapping_set_update(&xas, mapping);
301 xas_for_each(&xas, page, ULONG_MAX) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700302 if (i >= pagevec_count(pvec) && !tail_pages)
Jan Karaaa65c292017-11-15 17:37:33 -0800303 break;
Matthew Wilcox3159f942017-11-03 13:30:42 -0400304 if (xa_is_value(page))
Jan Karaaa65c292017-11-15 17:37:33 -0800305 continue;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700306 if (!tail_pages) {
307 /*
308 * Some page got inserted in our range? Skip it. We
309 * have our pages locked so they are protected from
310 * being removed.
311 */
312 if (page != pvec->pages[i]) {
313 VM_BUG_ON_PAGE(page->index >
314 pvec->pages[i]->index, page);
315 continue;
316 }
317 WARN_ON_ONCE(!PageLocked(page));
318 if (PageTransHuge(page) && !PageHuge(page))
319 tail_pages = HPAGE_PMD_NR - 1;
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700320 page->mapping = NULL;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700321 /*
322 * Leave page->index set: truncation lookup relies
323 * upon it
324 */
Matthew Wilcox5fd4ca22019-05-13 17:16:44 -0700325 i++;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700326 } else {
327 VM_BUG_ON_PAGE(page->index + HPAGE_PMD_NR - tail_pages
328 != pvec->pages[i]->index, page);
329 tail_pages--;
330 }
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500331 xas_store(&xas, NULL);
Jan Karaaa65c292017-11-15 17:37:33 -0800332 total_pages++;
333 }
334 mapping->nrpages -= total_pages;
335}
336
337void delete_from_page_cache_batch(struct address_space *mapping,
338 struct pagevec *pvec)
339{
340 int i;
341 unsigned long flags;
342
343 if (!pagevec_count(pvec))
344 return;
345
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700346 xa_lock_irqsave(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800347 for (i = 0; i < pagevec_count(pvec); i++) {
348 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
349
350 unaccount_page_cache_page(mapping, pvec->pages[i]);
351 }
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500352 page_cache_delete_batch(mapping, pvec);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700353 xa_unlock_irqrestore(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800354
355 for (i = 0; i < pagevec_count(pvec); i++)
356 page_cache_free_page(mapping, pvec->pages[i]);
357}
358
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200359int filemap_check_errors(struct address_space *mapping)
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700360{
361 int ret = 0;
362 /* Check for outstanding write errors */
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700363 if (test_bit(AS_ENOSPC, &mapping->flags) &&
364 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700365 ret = -ENOSPC;
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700366 if (test_bit(AS_EIO, &mapping->flags) &&
367 test_and_clear_bit(AS_EIO, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700368 ret = -EIO;
369 return ret;
370}
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200371EXPORT_SYMBOL(filemap_check_errors);
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700372
Jeff Layton76341ca2017-07-06 07:02:22 -0400373static int filemap_check_and_keep_errors(struct address_space *mapping)
374{
375 /* Check for outstanding write errors */
376 if (test_bit(AS_EIO, &mapping->flags))
377 return -EIO;
378 if (test_bit(AS_ENOSPC, &mapping->flags))
379 return -ENOSPC;
380 return 0;
381}
382
Linus Torvalds1da177e2005-04-16 15:20:36 -0700383/**
Randy Dunlap485bb992006-06-23 02:03:49 -0700384 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
Martin Waitz67be2dd2005-05-01 08:59:26 -0700385 * @mapping: address space structure to write
386 * @start: offset in bytes where the range starts
Andrew Morton469eb4d2006-03-24 03:17:45 -0800387 * @end: offset in bytes where the range ends (inclusive)
Martin Waitz67be2dd2005-05-01 08:59:26 -0700388 * @sync_mode: enable synchronous operation
Linus Torvalds1da177e2005-04-16 15:20:36 -0700389 *
Randy Dunlap485bb992006-06-23 02:03:49 -0700390 * Start writeback against all of a mapping's dirty pages that lie
391 * within the byte offsets <start, end> inclusive.
392 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700393 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
Randy Dunlap485bb992006-06-23 02:03:49 -0700394 * opposed to a regular memory cleansing writeback. The difference between
Linus Torvalds1da177e2005-04-16 15:20:36 -0700395 * these two operations is that if a dirty page/buffer is encountered, it must
396 * be waited upon, and not just skipped over.
Mike Rapoporta862f682019-03-05 15:48:42 -0800397 *
398 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700399 */
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800400int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
401 loff_t end, int sync_mode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700402{
403 int ret;
404 struct writeback_control wbc = {
405 .sync_mode = sync_mode,
Nick Piggin05fe4782009-01-06 14:39:08 -0800406 .nr_to_write = LONG_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700407 .range_start = start,
408 .range_end = end,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700409 };
410
411 if (!mapping_cap_writeback_dirty(mapping))
412 return 0;
413
Tejun Heob16b1de2015-06-02 08:39:48 -0600414 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700415 ret = do_writepages(mapping, &wbc);
Tejun Heob16b1de2015-06-02 08:39:48 -0600416 wbc_detach_inode(&wbc);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417 return ret;
418}
419
420static inline int __filemap_fdatawrite(struct address_space *mapping,
421 int sync_mode)
422{
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700423 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700424}
425
426int filemap_fdatawrite(struct address_space *mapping)
427{
428 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
429}
430EXPORT_SYMBOL(filemap_fdatawrite);
431
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400432int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800433 loff_t end)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700434{
435 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
436}
Jan Karaf4c0a0f2008-07-11 19:27:31 -0400437EXPORT_SYMBOL(filemap_fdatawrite_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700438
Randy Dunlap485bb992006-06-23 02:03:49 -0700439/**
440 * filemap_flush - mostly a non-blocking flush
441 * @mapping: target address_space
442 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700443 * This is a mostly non-blocking flush. Not suitable for data-integrity
444 * purposes - I/O may not be started against all dirty pages.
Mike Rapoporta862f682019-03-05 15:48:42 -0800445 *
446 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700447 */
448int filemap_flush(struct address_space *mapping)
449{
450 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
451}
452EXPORT_SYMBOL(filemap_flush);
453
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500454/**
455 * filemap_range_has_page - check if a page exists in range.
456 * @mapping: address space within which to check
457 * @start_byte: offset in bytes where the range starts
458 * @end_byte: offset in bytes where the range ends (inclusive)
459 *
460 * Find at least one page in the range supplied, usually used to check if
461 * direct writing in this range will trigger a writeback.
Mike Rapoporta862f682019-03-05 15:48:42 -0800462 *
463 * Return: %true if at least one page exists in the specified range,
464 * %false otherwise.
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500465 */
466bool filemap_range_has_page(struct address_space *mapping,
467 loff_t start_byte, loff_t end_byte)
468{
Jan Karaf7b68042017-09-06 16:21:40 -0700469 struct page *page;
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500470 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
471 pgoff_t max = end_byte >> PAGE_SHIFT;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500472
473 if (end_byte < start_byte)
474 return false;
475
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500476 rcu_read_lock();
477 for (;;) {
478 page = xas_find(&xas, max);
479 if (xas_retry(&xas, page))
480 continue;
481 /* Shadow entries don't count */
482 if (xa_is_value(page))
483 continue;
484 /*
485 * We don't need to try to pin this page; we're about to
486 * release the RCU lock anyway. It is enough to know that
487 * there was a page here recently.
488 */
489 break;
490 }
491 rcu_read_unlock();
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500492
Matthew Wilcox8fa8e532018-01-16 06:26:49 -0500493 return page != NULL;
Goldwyn Rodrigues7fc9e472017-06-20 07:05:41 -0500494}
495EXPORT_SYMBOL(filemap_range_has_page);
496
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400497static void __filemap_fdatawait_range(struct address_space *mapping,
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800498 loff_t start_byte, loff_t end_byte)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700499{
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300500 pgoff_t index = start_byte >> PAGE_SHIFT;
501 pgoff_t end = end_byte >> PAGE_SHIFT;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700502 struct pagevec pvec;
503 int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700504
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200505 if (end_byte < start_byte)
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400506 return;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700507
Mel Gorman86679822017-11-15 17:37:52 -0800508 pagevec_init(&pvec);
Jan Kara312e9d22017-11-15 17:35:05 -0800509 while (index <= end) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700510 unsigned i;
511
Jan Kara312e9d22017-11-15 17:35:05 -0800512 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
Jan Kara67fd7072017-11-15 17:35:19 -0800513 end, PAGECACHE_TAG_WRITEBACK);
Jan Kara312e9d22017-11-15 17:35:05 -0800514 if (!nr_pages)
515 break;
516
Linus Torvalds1da177e2005-04-16 15:20:36 -0700517 for (i = 0; i < nr_pages; i++) {
518 struct page *page = pvec.pages[i];
519
Linus Torvalds1da177e2005-04-16 15:20:36 -0700520 wait_on_page_writeback(page);
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400521 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700522 }
523 pagevec_release(&pvec);
524 cond_resched();
525 }
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800526}
527
528/**
529 * filemap_fdatawait_range - wait for writeback to complete
530 * @mapping: address space structure to wait for
531 * @start_byte: offset in bytes where the range starts
532 * @end_byte: offset in bytes where the range ends (inclusive)
533 *
534 * Walk the list of under-writeback pages of the given address space
535 * in the given range and wait for all of them. Check error status of
536 * the address space and return it.
537 *
538 * Since the error status of the address space is cleared by this function,
539 * callers are responsible for checking the return value and handling and/or
540 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800541 *
542 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800543 */
544int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
545 loff_t end_byte)
546{
Jeff Layton5e8fcc12017-07-06 07:02:24 -0400547 __filemap_fdatawait_range(mapping, start_byte, end_byte);
548 return filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700549}
Jan Karad3bccb6f2009-08-17 19:30:27 +0200550EXPORT_SYMBOL(filemap_fdatawait_range);
551
552/**
Jeff Laytona823e452017-07-28 07:24:43 -0400553 * file_fdatawait_range - wait for writeback to complete
554 * @file: file pointing to address space structure to wait for
555 * @start_byte: offset in bytes where the range starts
556 * @end_byte: offset in bytes where the range ends (inclusive)
557 *
558 * Walk the list of under-writeback pages of the address space that file
559 * refers to, in the given range and wait for all of them. Check error
560 * status of the address space vs. the file->f_wb_err cursor and return it.
561 *
562 * Since the error status of the file is advanced by this function,
563 * callers are responsible for checking the return value and handling and/or
564 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800565 *
566 * Return: error status of the address space vs. the file->f_wb_err cursor.
Jeff Laytona823e452017-07-28 07:24:43 -0400567 */
568int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
569{
570 struct address_space *mapping = file->f_mapping;
571
572 __filemap_fdatawait_range(mapping, start_byte, end_byte);
573 return file_check_and_advance_wb_err(file);
574}
575EXPORT_SYMBOL(file_fdatawait_range);
576
577/**
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800578 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
579 * @mapping: address space structure to wait for
580 *
581 * Walk the list of under-writeback pages of the given address space
582 * and wait for all of them. Unlike filemap_fdatawait(), this function
583 * does not clear error status of the address space.
584 *
585 * Use this function if callers don't handle errors themselves. Expected
586 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
587 * fsfreeze(8)
Mike Rapoporta862f682019-03-05 15:48:42 -0800588 *
589 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800590 */
Jeff Layton76341ca2017-07-06 07:02:22 -0400591int filemap_fdatawait_keep_errors(struct address_space *mapping)
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800592{
Jeff Laytonffb959b2017-07-31 10:29:38 -0400593 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
Jeff Layton76341ca2017-07-06 07:02:22 -0400594 return filemap_check_and_keep_errors(mapping);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800595}
Jeff Layton76341ca2017-07-06 07:02:22 -0400596EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800597
Jeff Layton9326c9b2017-07-26 10:21:11 -0400598static bool mapping_needs_writeback(struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700599{
Jeff Layton9326c9b2017-07-26 10:21:11 -0400600 return (!dax_mapping(mapping) && mapping->nrpages) ||
601 (dax_mapping(mapping) && mapping->nrexceptional);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700602}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700603
604int filemap_write_and_wait(struct address_space *mapping)
605{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800606 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700607
Jeff Layton9326c9b2017-07-26 10:21:11 -0400608 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800609 err = filemap_fdatawrite(mapping);
610 /*
611 * Even if the above returned error, the pages may be
612 * written partially (e.g. -ENOSPC), so we wait for it.
613 * But the -EIO is special case, it may indicate the worst
614 * thing (e.g. bug) happened, so we avoid waiting for it.
615 */
616 if (err != -EIO) {
617 int err2 = filemap_fdatawait(mapping);
618 if (!err)
619 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400620 } else {
621 /* Clear any previously stored errors */
622 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800623 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700624 } else {
625 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800627 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700628}
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800629EXPORT_SYMBOL(filemap_write_and_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700630
Randy Dunlap485bb992006-06-23 02:03:49 -0700631/**
632 * filemap_write_and_wait_range - write out & wait on a file range
633 * @mapping: the address_space for the pages
634 * @lstart: offset in bytes where the range starts
635 * @lend: offset in bytes where the range ends (inclusive)
636 *
Andrew Morton469eb4d2006-03-24 03:17:45 -0800637 * Write out and wait upon file offsets lstart->lend, inclusive.
638 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -0300639 * Note that @lend is inclusive (describes the last byte to be written) so
Andrew Morton469eb4d2006-03-24 03:17:45 -0800640 * that this function can be used to write to the very end-of-file (end = -1).
Mike Rapoporta862f682019-03-05 15:48:42 -0800641 *
642 * Return: error status of the address space.
Andrew Morton469eb4d2006-03-24 03:17:45 -0800643 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700644int filemap_write_and_wait_range(struct address_space *mapping,
645 loff_t lstart, loff_t lend)
646{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800647 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700648
Jeff Layton9326c9b2017-07-26 10:21:11 -0400649 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800650 err = __filemap_fdatawrite_range(mapping, lstart, lend,
651 WB_SYNC_ALL);
652 /* See comment of filemap_write_and_wait() */
653 if (err != -EIO) {
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200654 int err2 = filemap_fdatawait_range(mapping,
655 lstart, lend);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800656 if (!err)
657 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400658 } else {
659 /* Clear any previously stored errors */
660 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800661 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700662 } else {
663 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700664 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800665 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700666}
Chris Masonf6995582009-04-15 13:22:37 -0400667EXPORT_SYMBOL(filemap_write_and_wait_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700668
Jeff Layton5660e132017-07-06 07:02:25 -0400669void __filemap_set_wb_err(struct address_space *mapping, int err)
670{
Jeff Layton3acdfd22017-07-24 06:22:15 -0400671 errseq_t eseq = errseq_set(&mapping->wb_err, err);
Jeff Layton5660e132017-07-06 07:02:25 -0400672
673 trace_filemap_set_wb_err(mapping, eseq);
674}
675EXPORT_SYMBOL(__filemap_set_wb_err);
676
677/**
678 * file_check_and_advance_wb_err - report wb error (if any) that was previously
679 * and advance wb_err to current one
680 * @file: struct file on which the error is being reported
681 *
682 * When userland calls fsync (or something like nfsd does the equivalent), we
683 * want to report any writeback errors that occurred since the last fsync (or
684 * since the file was opened if there haven't been any).
685 *
686 * Grab the wb_err from the mapping. If it matches what we have in the file,
687 * then just quickly return 0. The file is all caught up.
688 *
689 * If it doesn't match, then take the mapping value, set the "seen" flag in
690 * it and try to swap it into place. If it works, or another task beat us
691 * to it with the new value, then update the f_wb_err and return the error
692 * portion. The error at this point must be reported via proper channels
693 * (a'la fsync, or NFS COMMIT operation, etc.).
694 *
695 * While we handle mapping->wb_err with atomic operations, the f_wb_err
696 * value is protected by the f_lock since we must ensure that it reflects
697 * the latest value swapped in for this file descriptor.
Mike Rapoporta862f682019-03-05 15:48:42 -0800698 *
699 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400700 */
701int file_check_and_advance_wb_err(struct file *file)
702{
703 int err = 0;
704 errseq_t old = READ_ONCE(file->f_wb_err);
705 struct address_space *mapping = file->f_mapping;
706
707 /* Locklessly handle the common case where nothing has changed */
708 if (errseq_check(&mapping->wb_err, old)) {
709 /* Something changed, must use slow path */
710 spin_lock(&file->f_lock);
711 old = file->f_wb_err;
712 err = errseq_check_and_advance(&mapping->wb_err,
713 &file->f_wb_err);
714 trace_file_check_and_advance_wb_err(file, old);
715 spin_unlock(&file->f_lock);
716 }
Jeff Laytonf4e222c2017-10-03 16:15:25 -0700717
718 /*
719 * We're mostly using this function as a drop in replacement for
720 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
721 * that the legacy code would have had on these flags.
722 */
723 clear_bit(AS_EIO, &mapping->flags);
724 clear_bit(AS_ENOSPC, &mapping->flags);
Jeff Layton5660e132017-07-06 07:02:25 -0400725 return err;
726}
727EXPORT_SYMBOL(file_check_and_advance_wb_err);
728
729/**
730 * file_write_and_wait_range - write out & wait on a file range
731 * @file: file pointing to address_space with pages
732 * @lstart: offset in bytes where the range starts
733 * @lend: offset in bytes where the range ends (inclusive)
734 *
735 * Write out and wait upon file offsets lstart->lend, inclusive.
736 *
737 * Note that @lend is inclusive (describes the last byte to be written) so
738 * that this function can be used to write to the very end-of-file (end = -1).
739 *
740 * After writing out and waiting on the data, we check and advance the
741 * f_wb_err cursor to the latest value, and return any errors detected there.
Mike Rapoporta862f682019-03-05 15:48:42 -0800742 *
743 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400744 */
745int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
746{
747 int err = 0, err2;
748 struct address_space *mapping = file->f_mapping;
749
Jeff Layton9326c9b2017-07-26 10:21:11 -0400750 if (mapping_needs_writeback(mapping)) {
Jeff Layton5660e132017-07-06 07:02:25 -0400751 err = __filemap_fdatawrite_range(mapping, lstart, lend,
752 WB_SYNC_ALL);
753 /* See comment of filemap_write_and_wait() */
754 if (err != -EIO)
755 __filemap_fdatawait_range(mapping, lstart, lend);
756 }
757 err2 = file_check_and_advance_wb_err(file);
758 if (!err)
759 err = err2;
760 return err;
761}
762EXPORT_SYMBOL(file_write_and_wait_range);
763
Randy Dunlap485bb992006-06-23 02:03:49 -0700764/**
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700765 * replace_page_cache_page - replace a pagecache page with a new one
766 * @old: page to be replaced
767 * @new: page to replace with
768 * @gfp_mask: allocation mode
769 *
770 * This function replaces a page in the pagecache with a new one. On
771 * success it acquires the pagecache reference for the new page and
772 * drops it for the old page. Both the old and new pages must be
773 * locked. This function does not add the new page to the LRU, the
774 * caller must do that.
775 *
Matthew Wilcox74d60952017-11-17 10:01:45 -0500776 * The remove + add is atomic. This function cannot fail.
Mike Rapoporta862f682019-03-05 15:48:42 -0800777 *
778 * Return: %0
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700779 */
780int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
781{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500782 struct address_space *mapping = old->mapping;
783 void (*freepage)(struct page *) = mapping->a_ops->freepage;
784 pgoff_t offset = old->index;
785 XA_STATE(xas, &mapping->i_pages, offset);
786 unsigned long flags;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700787
Sasha Levin309381fea2014-01-23 15:52:54 -0800788 VM_BUG_ON_PAGE(!PageLocked(old), old);
789 VM_BUG_ON_PAGE(!PageLocked(new), new);
790 VM_BUG_ON_PAGE(new->mapping, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700791
Matthew Wilcox74d60952017-11-17 10:01:45 -0500792 get_page(new);
793 new->mapping = mapping;
794 new->index = offset;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700795
Matthew Wilcox74d60952017-11-17 10:01:45 -0500796 xas_lock_irqsave(&xas, flags);
797 xas_store(&xas, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700798
Matthew Wilcox74d60952017-11-17 10:01:45 -0500799 old->mapping = NULL;
800 /* hugetlb pages do not participate in page cache accounting. */
801 if (!PageHuge(old))
802 __dec_node_page_state(new, NR_FILE_PAGES);
803 if (!PageHuge(new))
804 __inc_node_page_state(new, NR_FILE_PAGES);
805 if (PageSwapBacked(old))
806 __dec_node_page_state(new, NR_SHMEM);
807 if (PageSwapBacked(new))
808 __inc_node_page_state(new, NR_SHMEM);
809 xas_unlock_irqrestore(&xas, flags);
810 mem_cgroup_migrate(old, new);
811 if (freepage)
812 freepage(old);
813 put_page(old);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700814
Matthew Wilcox74d60952017-11-17 10:01:45 -0500815 return 0;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700816}
817EXPORT_SYMBOL_GPL(replace_page_cache_page);
818
Johannes Weinera5289102014-04-03 14:47:51 -0700819static int __add_to_page_cache_locked(struct page *page,
820 struct address_space *mapping,
821 pgoff_t offset, gfp_t gfp_mask,
822 void **shadowp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700823{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500824 XA_STATE(xas, &mapping->i_pages, offset);
Johannes Weiner00501b52014-08-08 14:19:20 -0700825 int huge = PageHuge(page);
826 struct mem_cgroup *memcg;
Nick Piggine2867812008-07-25 19:45:30 -0700827 int error;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500828 void *old;
Nick Piggine2867812008-07-25 19:45:30 -0700829
Sasha Levin309381fea2014-01-23 15:52:54 -0800830 VM_BUG_ON_PAGE(!PageLocked(page), page);
831 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500832 mapping_set_update(&xas, mapping);
Nick Piggine2867812008-07-25 19:45:30 -0700833
Johannes Weiner00501b52014-08-08 14:19:20 -0700834 if (!huge) {
835 error = mem_cgroup_try_charge(page, current->mm,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800836 gfp_mask, &memcg, false);
Johannes Weiner00501b52014-08-08 14:19:20 -0700837 if (error)
838 return error;
839 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700840
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300841 get_page(page);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700842 page->mapping = mapping;
843 page->index = offset;
844
Matthew Wilcox74d60952017-11-17 10:01:45 -0500845 do {
846 xas_lock_irq(&xas);
847 old = xas_load(&xas);
848 if (old && !xa_is_value(old))
849 xas_set_err(&xas, -EEXIST);
850 xas_store(&xas, page);
851 if (xas_error(&xas))
852 goto unlock;
Michal Hocko4165b9b2015-06-24 16:57:24 -0700853
Matthew Wilcox74d60952017-11-17 10:01:45 -0500854 if (xa_is_value(old)) {
855 mapping->nrexceptional--;
856 if (shadowp)
857 *shadowp = old;
858 }
859 mapping->nrpages++;
860
861 /* hugetlb pages do not participate in page cache accounting */
862 if (!huge)
863 __inc_node_page_state(page, NR_FILE_PAGES);
864unlock:
865 xas_unlock_irq(&xas);
866 } while (xas_nomem(&xas, gfp_mask & GFP_RECLAIM_MASK));
867
868 if (xas_error(&xas))
869 goto error;
870
Johannes Weiner00501b52014-08-08 14:19:20 -0700871 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800872 mem_cgroup_commit_charge(page, memcg, false, false);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700873 trace_mm_filemap_add_to_page_cache(page);
874 return 0;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500875error:
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700876 page->mapping = NULL;
877 /* Leave page->index set: truncation relies upon it */
Johannes Weiner00501b52014-08-08 14:19:20 -0700878 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800879 mem_cgroup_cancel_charge(page, memcg, false);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300880 put_page(page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500881 return xas_error(&xas);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700882}
Josef Bacikcfcbfb12019-05-13 17:21:04 -0700883ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
Johannes Weinera5289102014-04-03 14:47:51 -0700884
885/**
886 * add_to_page_cache_locked - add a locked page to the pagecache
887 * @page: page to add
888 * @mapping: the page's address_space
889 * @offset: page index
890 * @gfp_mask: page allocation mode
891 *
892 * This function is used to add a page to the pagecache. It must be locked.
893 * This function does not add the page to the LRU. The caller must do that.
Mike Rapoporta862f682019-03-05 15:48:42 -0800894 *
895 * Return: %0 on success, negative error code otherwise.
Johannes Weinera5289102014-04-03 14:47:51 -0700896 */
897int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
898 pgoff_t offset, gfp_t gfp_mask)
899{
900 return __add_to_page_cache_locked(page, mapping, offset,
901 gfp_mask, NULL);
902}
Nick Piggine2867812008-07-25 19:45:30 -0700903EXPORT_SYMBOL(add_to_page_cache_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904
905int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
Al Viro6daa0e22005-10-21 03:18:50 -0400906 pgoff_t offset, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700907{
Johannes Weinera5289102014-04-03 14:47:51 -0700908 void *shadow = NULL;
Rik van Riel4f98a2f2008-10-18 20:26:32 -0700909 int ret;
910
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800911 __SetPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700912 ret = __add_to_page_cache_locked(page, mapping, offset,
913 gfp_mask, &shadow);
914 if (unlikely(ret))
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800915 __ClearPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700916 else {
917 /*
918 * The page might have been evicted from cache only
919 * recently, in which case it should be activated like
920 * any other repeatedly accessed page.
Rik van Rielf0281a02016-05-20 16:56:25 -0700921 * The exception is pages getting rewritten; evicting other
922 * data from the working set, only to cache data that will
923 * get overwritten with something else, is a waste of memory.
Johannes Weinera5289102014-04-03 14:47:51 -0700924 */
Johannes Weiner1899ad12018-10-26 15:06:04 -0700925 WARN_ON_ONCE(PageActive(page));
926 if (!(gfp_mask & __GFP_WRITE) && shadow)
927 workingset_refault(page, shadow);
Johannes Weinera5289102014-04-03 14:47:51 -0700928 lru_cache_add(page);
929 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700930 return ret;
931}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +0300932EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933
Paul Jackson44110fe2006-03-24 03:16:04 -0800934#ifdef CONFIG_NUMA
Nick Piggin2ae88142006-10-28 10:38:23 -0700935struct page *__page_cache_alloc(gfp_t gfp)
Paul Jackson44110fe2006-03-24 03:16:04 -0800936{
Miao Xiec0ff7452010-05-24 14:32:08 -0700937 int n;
938 struct page *page;
939
Paul Jackson44110fe2006-03-24 03:16:04 -0800940 if (cpuset_do_page_mem_spread()) {
Mel Gormancc9a6c82012-03-21 16:34:11 -0700941 unsigned int cpuset_mems_cookie;
942 do {
Mel Gormand26914d2014-04-03 14:47:24 -0700943 cpuset_mems_cookie = read_mems_allowed_begin();
Mel Gormancc9a6c82012-03-21 16:34:11 -0700944 n = cpuset_mem_spread_node();
Vlastimil Babka96db8002015-09-08 15:03:50 -0700945 page = __alloc_pages_node(n, gfp, 0);
Mel Gormand26914d2014-04-03 14:47:24 -0700946 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
Mel Gormancc9a6c82012-03-21 16:34:11 -0700947
Miao Xiec0ff7452010-05-24 14:32:08 -0700948 return page;
Paul Jackson44110fe2006-03-24 03:16:04 -0800949 }
Nick Piggin2ae88142006-10-28 10:38:23 -0700950 return alloc_pages(gfp, 0);
Paul Jackson44110fe2006-03-24 03:16:04 -0800951}
Nick Piggin2ae88142006-10-28 10:38:23 -0700952EXPORT_SYMBOL(__page_cache_alloc);
Paul Jackson44110fe2006-03-24 03:16:04 -0800953#endif
954
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955/*
956 * In order to wait for pages to become available there must be
957 * waitqueues associated with pages. By using a hash table of
958 * waitqueues where the bucket discipline is to maintain all
959 * waiters on the same queue and wake all when any of the pages
960 * become available, and for the woken contexts to check to be
961 * sure the appropriate page became available, this saves space
962 * at a cost of "thundering herd" phenomena during rare hash
963 * collisions.
964 */
Nicholas Piggin62906022016-12-25 13:00:30 +1000965#define PAGE_WAIT_TABLE_BITS 8
966#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
967static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
968
969static wait_queue_head_t *page_waitqueue(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700970{
Nicholas Piggin62906022016-12-25 13:00:30 +1000971 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700972}
Nicholas Piggin62906022016-12-25 13:00:30 +1000973
974void __init pagecache_init(void)
975{
976 int i;
977
978 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
979 init_waitqueue_head(&page_wait_table[i]);
980
981 page_writeback_init();
982}
983
Linus Torvalds3510ca22017-08-27 13:55:12 -0700984/* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
Nicholas Piggin62906022016-12-25 13:00:30 +1000985struct wait_page_key {
986 struct page *page;
987 int bit_nr;
988 int page_match;
989};
990
991struct wait_page_queue {
992 struct page *page;
993 int bit_nr;
Ingo Molnarac6424b2017-06-20 12:06:13 +0200994 wait_queue_entry_t wait;
Nicholas Piggin62906022016-12-25 13:00:30 +1000995};
996
Ingo Molnarac6424b2017-06-20 12:06:13 +0200997static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
Nicholas Piggin62906022016-12-25 13:00:30 +1000998{
999 struct wait_page_key *key = arg;
1000 struct wait_page_queue *wait_page
1001 = container_of(wait, struct wait_page_queue, wait);
1002
1003 if (wait_page->page != key->page)
1004 return 0;
1005 key->page_match = 1;
1006
1007 if (wait_page->bit_nr != key->bit_nr)
1008 return 0;
Linus Torvalds3510ca22017-08-27 13:55:12 -07001009
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001010 /*
1011 * Stop walking if it's locked.
1012 * Is this safe if put_and_wait_on_page_locked() is in use?
1013 * Yes: the waker must hold a reference to this page, and if PG_locked
1014 * has now already been set by another task, that task must also hold
1015 * a reference to the *same usage* of this page; so there is no need
1016 * to walk on to wake even the put_and_wait_on_page_locked() callers.
1017 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001018 if (test_bit(key->bit_nr, &key->page->flags))
Linus Torvalds3510ca22017-08-27 13:55:12 -07001019 return -1;
Nicholas Piggin62906022016-12-25 13:00:30 +10001020
1021 return autoremove_wake_function(wait, mode, sync, key);
1022}
1023
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001024static void wake_up_page_bit(struct page *page, int bit_nr)
Nicholas Piggin62906022016-12-25 13:00:30 +10001025{
1026 wait_queue_head_t *q = page_waitqueue(page);
1027 struct wait_page_key key;
1028 unsigned long flags;
Tim Chen11a19c72017-08-25 09:13:55 -07001029 wait_queue_entry_t bookmark;
Nicholas Piggin62906022016-12-25 13:00:30 +10001030
1031 key.page = page;
1032 key.bit_nr = bit_nr;
1033 key.page_match = 0;
1034
Tim Chen11a19c72017-08-25 09:13:55 -07001035 bookmark.flags = 0;
1036 bookmark.private = NULL;
1037 bookmark.func = NULL;
1038 INIT_LIST_HEAD(&bookmark.entry);
1039
Nicholas Piggin62906022016-12-25 13:00:30 +10001040 spin_lock_irqsave(&q->lock, flags);
Tim Chen11a19c72017-08-25 09:13:55 -07001041 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1042
1043 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1044 /*
1045 * Take a breather from holding the lock,
1046 * allow pages that finish wake up asynchronously
1047 * to acquire the lock and remove themselves
1048 * from wait queue
1049 */
1050 spin_unlock_irqrestore(&q->lock, flags);
1051 cpu_relax();
1052 spin_lock_irqsave(&q->lock, flags);
1053 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1054 }
1055
Nicholas Piggin62906022016-12-25 13:00:30 +10001056 /*
1057 * It is possible for other pages to have collided on the waitqueue
1058 * hash, so in that case check for a page match. That prevents a long-
1059 * term waiter
1060 *
1061 * It is still possible to miss a case here, when we woke page waiters
1062 * and removed them from the waitqueue, but there are still other
1063 * page waiters.
1064 */
1065 if (!waitqueue_active(q) || !key.page_match) {
1066 ClearPageWaiters(page);
1067 /*
1068 * It's possible to miss clearing Waiters here, when we woke
1069 * our page waiters, but the hashed waitqueue has waiters for
1070 * other pages on it.
1071 *
1072 * That's okay, it's a rare case. The next waker will clear it.
1073 */
1074 }
1075 spin_unlock_irqrestore(&q->lock, flags);
1076}
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001077
1078static void wake_up_page(struct page *page, int bit)
1079{
1080 if (!PageWaiters(page))
1081 return;
1082 wake_up_page_bit(page, bit);
1083}
Nicholas Piggin62906022016-12-25 13:00:30 +10001084
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001085/*
1086 * A choice of three behaviors for wait_on_page_bit_common():
1087 */
1088enum behavior {
1089 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1090 * __lock_page() waiting on then setting PG_locked.
1091 */
1092 SHARED, /* Hold ref to page and check the bit when woken, like
1093 * wait_on_page_writeback() waiting on PG_writeback.
1094 */
1095 DROP, /* Drop ref to page before wait, no check when woken,
1096 * like put_and_wait_on_page_locked() on PG_locked.
1097 */
1098};
1099
Nicholas Piggin62906022016-12-25 13:00:30 +10001100static inline int wait_on_page_bit_common(wait_queue_head_t *q,
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001101 struct page *page, int bit_nr, int state, enum behavior behavior)
Nicholas Piggin62906022016-12-25 13:00:30 +10001102{
1103 struct wait_page_queue wait_page;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001104 wait_queue_entry_t *wait = &wait_page.wait;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001105 bool bit_is_set;
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001106 bool thrashing = false;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001107 bool delayacct = false;
Johannes Weinereb414682018-10-26 15:06:27 -07001108 unsigned long pflags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001109 int ret = 0;
1110
Johannes Weinereb414682018-10-26 15:06:27 -07001111 if (bit_nr == PG_locked &&
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001112 !PageUptodate(page) && PageWorkingset(page)) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001113 if (!PageSwapBacked(page)) {
Johannes Weinereb414682018-10-26 15:06:27 -07001114 delayacct_thrashing_start();
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001115 delayacct = true;
1116 }
Johannes Weinereb414682018-10-26 15:06:27 -07001117 psi_memstall_enter(&pflags);
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001118 thrashing = true;
1119 }
1120
Nicholas Piggin62906022016-12-25 13:00:30 +10001121 init_wait(wait);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001122 wait->flags = behavior == EXCLUSIVE ? WQ_FLAG_EXCLUSIVE : 0;
Nicholas Piggin62906022016-12-25 13:00:30 +10001123 wait->func = wake_page_function;
1124 wait_page.page = page;
1125 wait_page.bit_nr = bit_nr;
1126
1127 for (;;) {
1128 spin_lock_irq(&q->lock);
1129
Ingo Molnar2055da92017-06-20 12:06:46 +02001130 if (likely(list_empty(&wait->entry))) {
Linus Torvalds3510ca22017-08-27 13:55:12 -07001131 __add_wait_queue_entry_tail(q, wait);
Nicholas Piggin62906022016-12-25 13:00:30 +10001132 SetPageWaiters(page);
1133 }
1134
1135 set_current_state(state);
1136
1137 spin_unlock_irq(&q->lock);
1138
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001139 bit_is_set = test_bit(bit_nr, &page->flags);
1140 if (behavior == DROP)
1141 put_page(page);
Nicholas Piggin62906022016-12-25 13:00:30 +10001142
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001143 if (likely(bit_is_set))
1144 io_schedule();
1145
1146 if (behavior == EXCLUSIVE) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001147 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1148 break;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001149 } else if (behavior == SHARED) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001150 if (!test_bit(bit_nr, &page->flags))
1151 break;
1152 }
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001153
Davidlohr Buesofa45f112019-01-03 15:28:55 -08001154 if (signal_pending_state(state, current)) {
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001155 ret = -EINTR;
1156 break;
1157 }
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001158
1159 if (behavior == DROP) {
1160 /*
1161 * We can no longer safely access page->flags:
1162 * even if CONFIG_MEMORY_HOTREMOVE is not enabled,
1163 * there is a risk of waiting forever on a page reused
1164 * for something that keeps it locked indefinitely.
1165 * But best check for -EINTR above before breaking.
1166 */
1167 break;
1168 }
Nicholas Piggin62906022016-12-25 13:00:30 +10001169 }
1170
1171 finish_wait(q, wait);
1172
Johannes Weinereb414682018-10-26 15:06:27 -07001173 if (thrashing) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001174 if (delayacct)
Johannes Weinereb414682018-10-26 15:06:27 -07001175 delayacct_thrashing_end();
1176 psi_memstall_leave(&pflags);
1177 }
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001178
Nicholas Piggin62906022016-12-25 13:00:30 +10001179 /*
1180 * A signal could leave PageWaiters set. Clearing it here if
1181 * !waitqueue_active would be possible (by open-coding finish_wait),
1182 * but still fail to catch it in the case of wait hash collision. We
1183 * already can fail to clear wait hash collision cases, so don't
1184 * bother with signals either.
1185 */
1186
1187 return ret;
1188}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001189
Harvey Harrison920c7a52008-02-04 22:29:26 -08001190void wait_on_page_bit(struct page *page, int bit_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001191{
Nicholas Piggin62906022016-12-25 13:00:30 +10001192 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001193 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001194}
1195EXPORT_SYMBOL(wait_on_page_bit);
1196
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001197int wait_on_page_bit_killable(struct page *page, int bit_nr)
1198{
Nicholas Piggin62906022016-12-25 13:00:30 +10001199 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001200 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001201}
David Howells4343d002017-11-02 15:27:52 +00001202EXPORT_SYMBOL(wait_on_page_bit_killable);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001203
Linus Torvalds1da177e2005-04-16 15:20:36 -07001204/**
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001205 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1206 * @page: The page to wait for.
1207 *
1208 * The caller should hold a reference on @page. They expect the page to
1209 * become unlocked relatively soon, but do not wish to hold up migration
1210 * (for example) by holding the reference while waiting for the page to
1211 * come unlocked. After this function returns, the caller should not
1212 * dereference @page.
1213 */
1214void put_and_wait_on_page_locked(struct page *page)
1215{
1216 wait_queue_head_t *q;
1217
1218 page = compound_head(page);
1219 q = page_waitqueue(page);
1220 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1221}
1222
1223/**
David Howells385e1ca5f2009-04-03 16:42:39 +01001224 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
Randy Dunlap697f6192009-04-13 14:39:54 -07001225 * @page: Page defining the wait queue of interest
1226 * @waiter: Waiter to add to the queue
David Howells385e1ca5f2009-04-03 16:42:39 +01001227 *
1228 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1229 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001230void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
David Howells385e1ca5f2009-04-03 16:42:39 +01001231{
1232 wait_queue_head_t *q = page_waitqueue(page);
1233 unsigned long flags;
1234
1235 spin_lock_irqsave(&q->lock, flags);
Linus Torvalds9c3a8152017-08-28 16:45:40 -07001236 __add_wait_queue_entry_tail(q, waiter);
Nicholas Piggin62906022016-12-25 13:00:30 +10001237 SetPageWaiters(page);
David Howells385e1ca5f2009-04-03 16:42:39 +01001238 spin_unlock_irqrestore(&q->lock, flags);
1239}
1240EXPORT_SYMBOL_GPL(add_page_wait_queue);
1241
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001242#ifndef clear_bit_unlock_is_negative_byte
1243
1244/*
1245 * PG_waiters is the high bit in the same byte as PG_lock.
1246 *
1247 * On x86 (and on many other architectures), we can clear PG_lock and
1248 * test the sign bit at the same time. But if the architecture does
1249 * not support that special operation, we just do this all by hand
1250 * instead.
1251 *
1252 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1253 * being cleared, but a memory barrier should be unneccssary since it is
1254 * in the same byte as PG_locked.
1255 */
1256static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1257{
1258 clear_bit_unlock(nr, mem);
1259 /* smp_mb__after_atomic(); */
Olof Johansson98473f92016-12-29 14:16:07 -08001260 return test_bit(PG_waiters, mem);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001261}
1262
1263#endif
1264
David Howells385e1ca5f2009-04-03 16:42:39 +01001265/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001266 * unlock_page - unlock a locked page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001267 * @page: the page
1268 *
1269 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1270 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
Masanari Iidada3dae52014-09-09 01:27:23 +09001271 * mechanism between PageLocked pages and PageWriteback pages is shared.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001272 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1273 *
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001274 * Note that this depends on PG_waiters being the sign bit in the byte
1275 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1276 * clear the PG_locked bit and test PG_waiters at the same time fairly
1277 * portably (architectures that do LL/SC can test any bit, while x86 can
1278 * test the sign bit).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001279 */
Harvey Harrison920c7a52008-02-04 22:29:26 -08001280void unlock_page(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001281{
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001282 BUILD_BUG_ON(PG_waiters != 7);
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -08001283 page = compound_head(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001284 VM_BUG_ON_PAGE(!PageLocked(page), page);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001285 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1286 wake_up_page_bit(page, PG_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001287}
1288EXPORT_SYMBOL(unlock_page);
1289
Randy Dunlap485bb992006-06-23 02:03:49 -07001290/**
1291 * end_page_writeback - end writeback against a page
1292 * @page: the page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001293 */
1294void end_page_writeback(struct page *page)
1295{
Mel Gorman888cf2d2014-06-04 16:10:34 -07001296 /*
1297 * TestClearPageReclaim could be used here but it is an atomic
1298 * operation and overkill in this particular case. Failing to
1299 * shuffle a page marked for immediate reclaim is too mild to
1300 * justify taking an atomic operation penalty at the end of
1301 * ever page writeback.
1302 */
1303 if (PageReclaim(page)) {
1304 ClearPageReclaim(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001305 rotate_reclaimable_page(page);
Mel Gorman888cf2d2014-06-04 16:10:34 -07001306 }
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001307
1308 if (!test_clear_page_writeback(page))
1309 BUG();
1310
Peter Zijlstra4e857c52014-03-17 18:06:10 +01001311 smp_mb__after_atomic();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001312 wake_up_page(page, PG_writeback);
1313}
1314EXPORT_SYMBOL(end_page_writeback);
1315
Matthew Wilcox57d99842014-06-04 16:07:45 -07001316/*
1317 * After completing I/O on a page, call this routine to update the page
1318 * flags appropriately
1319 */
Jens Axboec11f0c02016-08-05 08:11:04 -06001320void page_endio(struct page *page, bool is_write, int err)
Matthew Wilcox57d99842014-06-04 16:07:45 -07001321{
Jens Axboec11f0c02016-08-05 08:11:04 -06001322 if (!is_write) {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001323 if (!err) {
1324 SetPageUptodate(page);
1325 } else {
1326 ClearPageUptodate(page);
1327 SetPageError(page);
1328 }
1329 unlock_page(page);
Mike Christieabf54542016-08-04 14:23:34 -06001330 } else {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001331 if (err) {
Minchan Kimdd8416c2017-02-24 14:59:59 -08001332 struct address_space *mapping;
1333
Matthew Wilcox57d99842014-06-04 16:07:45 -07001334 SetPageError(page);
Minchan Kimdd8416c2017-02-24 14:59:59 -08001335 mapping = page_mapping(page);
1336 if (mapping)
1337 mapping_set_error(mapping, err);
Matthew Wilcox57d99842014-06-04 16:07:45 -07001338 }
1339 end_page_writeback(page);
1340 }
1341}
1342EXPORT_SYMBOL_GPL(page_endio);
1343
Randy Dunlap485bb992006-06-23 02:03:49 -07001344/**
1345 * __lock_page - get a lock on the page, assuming we need to sleep to get it
Randy Dunlap87066752017-02-22 15:44:44 -08001346 * @__page: the page to lock
Linus Torvalds1da177e2005-04-16 15:20:36 -07001347 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001348void __lock_page(struct page *__page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001349{
Nicholas Piggin62906022016-12-25 13:00:30 +10001350 struct page *page = compound_head(__page);
1351 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001352 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1353 EXCLUSIVE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001354}
1355EXPORT_SYMBOL(__lock_page);
1356
Nicholas Piggin62906022016-12-25 13:00:30 +10001357int __lock_page_killable(struct page *__page)
Matthew Wilcox2687a352007-12-06 11:18:49 -05001358{
Nicholas Piggin62906022016-12-25 13:00:30 +10001359 struct page *page = compound_head(__page);
1360 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001361 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1362 EXCLUSIVE);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001363}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +03001364EXPORT_SYMBOL_GPL(__lock_page_killable);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001365
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001366/*
1367 * Return values:
1368 * 1 - page is locked; mmap_sem is still held.
1369 * 0 - page is not locked.
1370 * mmap_sem has been released (up_read()), unless flags had both
1371 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1372 * which case mmap_sem is still held.
1373 *
1374 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1375 * with the page locked and the mmap_sem unperturbed.
1376 */
Michel Lespinassed065bd82010-10-26 14:21:57 -07001377int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1378 unsigned int flags)
1379{
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001380 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1381 /*
1382 * CAUTION! In this case, mmap_sem is not released
1383 * even though return 0.
1384 */
1385 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1386 return 0;
1387
1388 up_read(&mm->mmap_sem);
1389 if (flags & FAULT_FLAG_KILLABLE)
1390 wait_on_page_locked_killable(page);
1391 else
Gleb Natapov318b2752011-03-22 16:30:51 -07001392 wait_on_page_locked(page);
Michel Lespinassed065bd82010-10-26 14:21:57 -07001393 return 0;
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001394 } else {
1395 if (flags & FAULT_FLAG_KILLABLE) {
1396 int ret;
1397
1398 ret = __lock_page_killable(page);
1399 if (ret) {
1400 up_read(&mm->mmap_sem);
1401 return 0;
1402 }
1403 } else
1404 __lock_page(page);
1405 return 1;
Michel Lespinassed065bd82010-10-26 14:21:57 -07001406 }
1407}
1408
Randy Dunlap485bb992006-06-23 02:03:49 -07001409/**
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001410 * page_cache_next_miss() - Find the next gap in the page cache.
1411 * @mapping: Mapping.
1412 * @index: Index.
1413 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001414 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001415 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1416 * gap with the lowest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001417 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001418 * This function may be called under the rcu_read_lock. However, this will
1419 * not atomically search a snapshot of the cache at a single point in time.
1420 * For example, if a gap is created at index 5, then subsequently a gap is
1421 * created at index 10, page_cache_next_miss covering both indices may
1422 * return 10 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001423 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001424 * Return: The index of the gap if found, otherwise an index outside the
1425 * range specified (in which case 'return - index >= max_scan' will be true).
1426 * In the rare case of index wrap-around, 0 will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001427 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001428pgoff_t page_cache_next_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001429 pgoff_t index, unsigned long max_scan)
1430{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001431 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001432
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001433 while (max_scan--) {
1434 void *entry = xas_next(&xas);
1435 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001436 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001437 if (xas.xa_index == 0)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001438 break;
1439 }
1440
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001441 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001442}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001443EXPORT_SYMBOL(page_cache_next_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001444
1445/**
Laurent Dufour2346a562019-05-13 17:21:29 -07001446 * page_cache_prev_miss() - Find the previous gap in the page cache.
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001447 * @mapping: Mapping.
1448 * @index: Index.
1449 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001450 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001451 * Search the range [max(index - max_scan + 1, 0), index] for the
1452 * gap with the highest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001453 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001454 * This function may be called under the rcu_read_lock. However, this will
1455 * not atomically search a snapshot of the cache at a single point in time.
1456 * For example, if a gap is created at index 10, then subsequently a gap is
1457 * created at index 5, page_cache_prev_miss() covering both indices may
1458 * return 5 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001459 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001460 * Return: The index of the gap if found, otherwise an index outside the
1461 * range specified (in which case 'index - return >= max_scan' will be true).
1462 * In the rare case of wrap-around, ULONG_MAX will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001463 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001464pgoff_t page_cache_prev_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001465 pgoff_t index, unsigned long max_scan)
1466{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001467 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001468
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001469 while (max_scan--) {
1470 void *entry = xas_prev(&xas);
1471 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001472 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001473 if (xas.xa_index == ULONG_MAX)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001474 break;
1475 }
1476
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001477 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001478}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001479EXPORT_SYMBOL(page_cache_prev_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001480
1481/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001482 * find_get_entry - find and get a page cache entry
Randy Dunlap485bb992006-06-23 02:03:49 -07001483 * @mapping: the address_space to search
Johannes Weiner0cd61442014-04-03 14:47:46 -07001484 * @offset: the page cache index
Randy Dunlap485bb992006-06-23 02:03:49 -07001485 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001486 * Looks up the page cache slot at @mapping & @offset. If there is a
1487 * page cache page, it is returned with an increased refcount.
1488 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001489 * If the slot holds a shadow entry of a previously evicted page, or a
1490 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001491 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001492 * Return: the found page or shadow entry, %NULL if nothing is found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001493 */
Johannes Weiner0cd61442014-04-03 14:47:46 -07001494struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001495{
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001496 XA_STATE(xas, &mapping->i_pages, offset);
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001497 struct page *head, *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001498
Nick Piggina60637c2008-07-25 19:45:31 -07001499 rcu_read_lock();
1500repeat:
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001501 xas_reset(&xas);
1502 page = xas_load(&xas);
1503 if (xas_retry(&xas, page))
1504 goto repeat;
1505 /*
1506 * A shadow entry of a recently evicted page, or a swap entry from
1507 * shmem/tmpfs. Return it without attempting to raise page count.
1508 */
1509 if (!page || xa_is_value(page))
1510 goto out;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001511
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001512 head = compound_head(page);
1513 if (!page_cache_get_speculative(head))
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001514 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001515
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001516 /* The page was split under us? */
1517 if (compound_head(page) != head) {
1518 put_page(head);
1519 goto repeat;
1520 }
1521
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001522 /*
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001523 * Has the page moved?
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001524 * This is part of the lockless pagecache protocol. See
1525 * include/linux/pagemap.h for details.
1526 */
1527 if (unlikely(page != xas_reload(&xas))) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001528 put_page(head);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001529 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001530 }
Nick Piggin27d20fd2010-11-11 14:05:19 -08001531out:
Nick Piggina60637c2008-07-25 19:45:31 -07001532 rcu_read_unlock();
1533
Linus Torvalds1da177e2005-04-16 15:20:36 -07001534 return page;
1535}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001536EXPORT_SYMBOL(find_get_entry);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001537
Randy Dunlap485bb992006-06-23 02:03:49 -07001538/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001539 * find_lock_entry - locate, pin and lock a page cache entry
1540 * @mapping: the address_space to search
1541 * @offset: the page cache index
1542 *
1543 * Looks up the page cache slot at @mapping & @offset. If there is a
1544 * page cache page, it is returned locked and with an increased
1545 * refcount.
1546 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001547 * If the slot holds a shadow entry of a previously evicted page, or a
1548 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001549 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001550 * find_lock_entry() may sleep.
Mike Rapoporta862f682019-03-05 15:48:42 -08001551 *
1552 * Return: the found page or shadow entry, %NULL if nothing is found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001553 */
1554struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001555{
1556 struct page *page;
1557
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558repeat:
Johannes Weiner0cd61442014-04-03 14:47:46 -07001559 page = find_get_entry(mapping, offset);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001560 if (page && !xa_is_value(page)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001561 lock_page(page);
1562 /* Has the page been truncated? */
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001563 if (unlikely(page_mapping(page) != mapping)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001564 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001565 put_page(page);
Nick Piggina60637c2008-07-25 19:45:31 -07001566 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001567 }
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001568 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001569 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001570 return page;
1571}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001572EXPORT_SYMBOL(find_lock_entry);
1573
1574/**
Mel Gorman2457aec2014-06-04 16:10:31 -07001575 * pagecache_get_page - find and get a page reference
Johannes Weiner0cd61442014-04-03 14:47:46 -07001576 * @mapping: the address_space to search
1577 * @offset: the page index
Mel Gorman2457aec2014-06-04 16:10:31 -07001578 * @fgp_flags: PCG flags
Michal Hocko45f87de2014-12-29 20:30:35 +01001579 * @gfp_mask: gfp mask to use for the page cache data page allocation
Johannes Weiner0cd61442014-04-03 14:47:46 -07001580 *
Mel Gorman2457aec2014-06-04 16:10:31 -07001581 * Looks up the page cache slot at @mapping & @offset.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001582 *
Randy Dunlap75325182014-07-30 16:08:37 -07001583 * PCG flags modify how the page is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001584 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -03001585 * @fgp_flags can be:
1586 *
1587 * - FGP_ACCESSED: the page will be marked accessed
1588 * - FGP_LOCK: Page is return locked
1589 * - FGP_CREAT: If page is not present then a new page is allocated using
1590 * @gfp_mask and added to the page cache and the VM's LRU
1591 * list. The page is returned locked and with an increased
Mike Rapoporta862f682019-03-05 15:48:42 -08001592 * refcount.
Josef Bacika75d4c32019-03-13 11:44:14 -07001593 * - FGP_FOR_MMAP: Similar to FGP_CREAT, only we want to allow the caller to do
1594 * its own locking dance if the page is already in cache, or unlock the page
1595 * before returning if we had to add the page to pagecache.
Mel Gorman2457aec2014-06-04 16:10:31 -07001596 *
1597 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1598 * if the GFP flags specified for FGP_CREAT are atomic.
1599 *
1600 * If there is a page cache page, it is returned with an increased refcount.
Mike Rapoporta862f682019-03-05 15:48:42 -08001601 *
1602 * Return: the found page or %NULL otherwise.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001603 */
Mel Gorman2457aec2014-06-04 16:10:31 -07001604struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
Michal Hocko45f87de2014-12-29 20:30:35 +01001605 int fgp_flags, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001606{
Nick Piggineb2be182007-10-16 01:24:57 -07001607 struct page *page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001608
Linus Torvalds1da177e2005-04-16 15:20:36 -07001609repeat:
Mel Gorman2457aec2014-06-04 16:10:31 -07001610 page = find_get_entry(mapping, offset);
Matthew Wilcox3159f942017-11-03 13:30:42 -04001611 if (xa_is_value(page))
Mel Gorman2457aec2014-06-04 16:10:31 -07001612 page = NULL;
1613 if (!page)
1614 goto no_page;
1615
1616 if (fgp_flags & FGP_LOCK) {
1617 if (fgp_flags & FGP_NOWAIT) {
1618 if (!trylock_page(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001619 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001620 return NULL;
1621 }
1622 } else {
1623 lock_page(page);
1624 }
1625
1626 /* Has the page been truncated? */
1627 if (unlikely(page->mapping != mapping)) {
1628 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001629 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001630 goto repeat;
1631 }
1632 VM_BUG_ON_PAGE(page->index != offset, page);
1633 }
1634
Kirill Tkhaic16eb002018-12-28 00:37:35 -08001635 if (fgp_flags & FGP_ACCESSED)
Mel Gorman2457aec2014-06-04 16:10:31 -07001636 mark_page_accessed(page);
1637
1638no_page:
1639 if (!page && (fgp_flags & FGP_CREAT)) {
1640 int err;
1641 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
Michal Hocko45f87de2014-12-29 20:30:35 +01001642 gfp_mask |= __GFP_WRITE;
1643 if (fgp_flags & FGP_NOFS)
1644 gfp_mask &= ~__GFP_FS;
Mel Gorman2457aec2014-06-04 16:10:31 -07001645
Michal Hocko45f87de2014-12-29 20:30:35 +01001646 page = __page_cache_alloc(gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001647 if (!page)
1648 return NULL;
Mel Gorman2457aec2014-06-04 16:10:31 -07001649
Josef Bacika75d4c32019-03-13 11:44:14 -07001650 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
Mel Gorman2457aec2014-06-04 16:10:31 -07001651 fgp_flags |= FGP_LOCK;
1652
Hugh Dickinseb39d612014-08-06 16:06:43 -07001653 /* Init accessed so avoid atomic mark_page_accessed later */
Mel Gorman2457aec2014-06-04 16:10:31 -07001654 if (fgp_flags & FGP_ACCESSED)
Hugh Dickinseb39d612014-08-06 16:06:43 -07001655 __SetPageReferenced(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001656
Matthew Wilcoxabc1be12018-04-20 14:56:20 -07001657 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001658 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001659 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07001660 page = NULL;
1661 if (err == -EEXIST)
1662 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001663 }
Josef Bacika75d4c32019-03-13 11:44:14 -07001664
1665 /*
1666 * add_to_page_cache_lru locks the page, and for mmap we expect
1667 * an unlocked page.
1668 */
1669 if (page && (fgp_flags & FGP_FOR_MMAP))
1670 unlock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001671 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001672
Linus Torvalds1da177e2005-04-16 15:20:36 -07001673 return page;
1674}
Mel Gorman2457aec2014-06-04 16:10:31 -07001675EXPORT_SYMBOL(pagecache_get_page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001676
1677/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001678 * find_get_entries - gang pagecache lookup
1679 * @mapping: The address_space to search
1680 * @start: The starting page cache index
1681 * @nr_entries: The maximum number of entries
1682 * @entries: Where the resulting entries are placed
1683 * @indices: The cache indices corresponding to the entries in @entries
1684 *
1685 * find_get_entries() will search for and return a group of up to
1686 * @nr_entries entries in the mapping. The entries are placed at
1687 * @entries. find_get_entries() takes a reference against any actual
1688 * pages it returns.
1689 *
1690 * The search returns a group of mapping-contiguous page cache entries
1691 * with ascending indexes. There may be holes in the indices due to
1692 * not-present pages.
1693 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001694 * Any shadow entries of evicted pages, or swap entries from
1695 * shmem/tmpfs, are included in the returned array.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001696 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001697 * Return: the number of pages and shadow entries which were found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001698 */
1699unsigned find_get_entries(struct address_space *mapping,
1700 pgoff_t start, unsigned int nr_entries,
1701 struct page **entries, pgoff_t *indices)
1702{
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001703 XA_STATE(xas, &mapping->i_pages, start);
1704 struct page *page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001705 unsigned int ret = 0;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001706
1707 if (!nr_entries)
1708 return 0;
1709
1710 rcu_read_lock();
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001711 xas_for_each(&xas, page, ULONG_MAX) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001712 struct page *head;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001713 if (xas_retry(&xas, page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001714 continue;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001715 /*
1716 * A shadow entry of a recently evicted page, a swap
1717 * entry from shmem/tmpfs or a DAX entry. Return it
1718 * without attempting to raise page count.
1719 */
1720 if (xa_is_value(page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001721 goto export;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001722
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001723 head = compound_head(page);
1724 if (!page_cache_get_speculative(head))
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001725 goto retry;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001726
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001727 /* The page was split under us? */
1728 if (compound_head(page) != head)
1729 goto put_page;
1730
1731 /* Has the page moved? */
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001732 if (unlikely(page != xas_reload(&xas)))
1733 goto put_page;
1734
Johannes Weiner0cd61442014-04-03 14:47:46 -07001735export:
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001736 indices[ret] = xas.xa_index;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001737 entries[ret] = page;
1738 if (++ret == nr_entries)
1739 break;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001740 continue;
1741put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001742 put_page(head);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001743retry:
1744 xas_reset(&xas);
Johannes Weiner0cd61442014-04-03 14:47:46 -07001745 }
1746 rcu_read_unlock();
1747 return ret;
1748}
1749
1750/**
Jan Karab947cee2017-09-06 16:21:21 -07001751 * find_get_pages_range - gang pagecache lookup
Linus Torvalds1da177e2005-04-16 15:20:36 -07001752 * @mapping: The address_space to search
1753 * @start: The starting page index
Jan Karab947cee2017-09-06 16:21:21 -07001754 * @end: The final page index (inclusive)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001755 * @nr_pages: The maximum number of pages
1756 * @pages: Where the resulting pages are placed
1757 *
Jan Karab947cee2017-09-06 16:21:21 -07001758 * find_get_pages_range() will search for and return a group of up to @nr_pages
1759 * pages in the mapping starting at index @start and up to index @end
1760 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1761 * a reference against the returned pages.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001762 *
1763 * The search returns a group of mapping-contiguous pages with ascending
1764 * indexes. There may be holes in the indices due to not-present pages.
Jan Karad72dc8a2017-09-06 16:21:18 -07001765 * We also update @start to index the next page for the traversal.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001766 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001767 * Return: the number of pages which were found. If this number is
1768 * smaller than @nr_pages, the end of specified range has been
Jan Karab947cee2017-09-06 16:21:21 -07001769 * reached.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001770 */
Jan Karab947cee2017-09-06 16:21:21 -07001771unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1772 pgoff_t end, unsigned int nr_pages,
1773 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001774{
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001775 XA_STATE(xas, &mapping->i_pages, *start);
1776 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001777 unsigned ret = 0;
1778
1779 if (unlikely(!nr_pages))
1780 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001781
Nick Piggina60637c2008-07-25 19:45:31 -07001782 rcu_read_lock();
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001783 xas_for_each(&xas, page, end) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001784 struct page *head;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001785 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001786 continue;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001787 /* Skip over shadow, swap and DAX entries */
1788 if (xa_is_value(page))
Hugh Dickins8079b1c2011-08-03 16:21:28 -07001789 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001790
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001791 head = compound_head(page);
1792 if (!page_cache_get_speculative(head))
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001793 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001794
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001795 /* The page was split under us? */
1796 if (compound_head(page) != head)
1797 goto put_page;
1798
1799 /* Has the page moved? */
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001800 if (unlikely(page != xas_reload(&xas)))
1801 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001802
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001803 pages[ret] = page;
Jan Karab947cee2017-09-06 16:21:21 -07001804 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001805 *start = xas.xa_index + 1;
Jan Karab947cee2017-09-06 16:21:21 -07001806 goto out;
1807 }
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001808 continue;
1809put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001810 put_page(head);
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001811retry:
1812 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001813 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001814
Jan Karab947cee2017-09-06 16:21:21 -07001815 /*
1816 * We come here when there is no page beyond @end. We take care to not
1817 * overflow the index @start as it confuses some of the callers. This
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001818 * breaks the iteration when there is a page at index -1 but that is
Jan Karab947cee2017-09-06 16:21:21 -07001819 * already broken anyway.
1820 */
1821 if (end == (pgoff_t)-1)
1822 *start = (pgoff_t)-1;
1823 else
1824 *start = end + 1;
1825out:
Nick Piggina60637c2008-07-25 19:45:31 -07001826 rcu_read_unlock();
Jan Karad72dc8a2017-09-06 16:21:18 -07001827
Linus Torvalds1da177e2005-04-16 15:20:36 -07001828 return ret;
1829}
1830
Jens Axboeebf43502006-04-27 08:46:01 +02001831/**
1832 * find_get_pages_contig - gang contiguous pagecache lookup
1833 * @mapping: The address_space to search
1834 * @index: The starting page index
1835 * @nr_pages: The maximum number of pages
1836 * @pages: Where the resulting pages are placed
1837 *
1838 * find_get_pages_contig() works exactly like find_get_pages(), except
1839 * that the returned number of pages are guaranteed to be contiguous.
1840 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001841 * Return: the number of pages which were found.
Jens Axboeebf43502006-04-27 08:46:01 +02001842 */
1843unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1844 unsigned int nr_pages, struct page **pages)
1845{
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001846 XA_STATE(xas, &mapping->i_pages, index);
1847 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001848 unsigned int ret = 0;
1849
1850 if (unlikely(!nr_pages))
1851 return 0;
Jens Axboeebf43502006-04-27 08:46:01 +02001852
Nick Piggina60637c2008-07-25 19:45:31 -07001853 rcu_read_lock();
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001854 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001855 struct page *head;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001856 if (xas_retry(&xas, page))
1857 continue;
1858 /*
1859 * If the entry has been swapped out, we can stop looking.
1860 * No current caller is looking for DAX entries.
1861 */
1862 if (xa_is_value(page))
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001863 break;
Hugh Dickins9d8aa4e2011-03-22 16:33:06 -07001864
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001865 head = compound_head(page);
1866 if (!page_cache_get_speculative(head))
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001867 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001868
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001869 /* The page was split under us? */
1870 if (compound_head(page) != head)
1871 goto put_page;
1872
1873 /* Has the page moved? */
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001874 if (unlikely(page != xas_reload(&xas)))
1875 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001876
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001877 pages[ret] = page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001878 if (++ret == nr_pages)
1879 break;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001880 continue;
1881put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001882 put_page(head);
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001883retry:
1884 xas_reset(&xas);
Jens Axboeebf43502006-04-27 08:46:01 +02001885 }
Nick Piggina60637c2008-07-25 19:45:31 -07001886 rcu_read_unlock();
1887 return ret;
Jens Axboeebf43502006-04-27 08:46:01 +02001888}
David Howellsef71c152007-05-09 02:33:44 -07001889EXPORT_SYMBOL(find_get_pages_contig);
Jens Axboeebf43502006-04-27 08:46:01 +02001890
Randy Dunlap485bb992006-06-23 02:03:49 -07001891/**
Jan Kara72b045a2017-11-15 17:34:33 -08001892 * find_get_pages_range_tag - find and return pages in given range matching @tag
Randy Dunlap485bb992006-06-23 02:03:49 -07001893 * @mapping: the address_space to search
1894 * @index: the starting page index
Jan Kara72b045a2017-11-15 17:34:33 -08001895 * @end: The final page index (inclusive)
Randy Dunlap485bb992006-06-23 02:03:49 -07001896 * @tag: the tag index
1897 * @nr_pages: the maximum number of pages
1898 * @pages: where the resulting pages are placed
1899 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001900 * Like find_get_pages, except we only return pages which are tagged with
Randy Dunlap485bb992006-06-23 02:03:49 -07001901 * @tag. We update @index to index the next page for the traversal.
Mike Rapoporta862f682019-03-05 15:48:42 -08001902 *
1903 * Return: the number of pages which were found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001904 */
Jan Kara72b045a2017-11-15 17:34:33 -08001905unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001906 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
Jan Kara72b045a2017-11-15 17:34:33 -08001907 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001908{
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001909 XA_STATE(xas, &mapping->i_pages, *index);
1910 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001911 unsigned ret = 0;
1912
1913 if (unlikely(!nr_pages))
1914 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001915
Nick Piggina60637c2008-07-25 19:45:31 -07001916 rcu_read_lock();
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001917 xas_for_each_marked(&xas, page, end, tag) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001918 struct page *head;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001919 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001920 continue;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001921 /*
1922 * Shadow entries should never be tagged, but this iteration
1923 * is lockless so there is a window for page reclaim to evict
1924 * a page we saw tagged. Skip over it.
1925 */
1926 if (xa_is_value(page))
Johannes Weiner139b6a62014-05-06 12:50:05 -07001927 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001928
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001929 head = compound_head(page);
1930 if (!page_cache_get_speculative(head))
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001931 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001932
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001933 /* The page was split under us? */
1934 if (compound_head(page) != head)
1935 goto put_page;
1936
1937 /* Has the page moved? */
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001938 if (unlikely(page != xas_reload(&xas)))
1939 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001940
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001941 pages[ret] = page;
Jan Kara72b045a2017-11-15 17:34:33 -08001942 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001943 *index = xas.xa_index + 1;
Jan Kara72b045a2017-11-15 17:34:33 -08001944 goto out;
1945 }
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001946 continue;
1947put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001948 put_page(head);
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001949retry:
1950 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001951 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001952
Jan Kara72b045a2017-11-15 17:34:33 -08001953 /*
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001954 * We come here when we got to @end. We take care to not overflow the
Jan Kara72b045a2017-11-15 17:34:33 -08001955 * index @index as it confuses some of the callers. This breaks the
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001956 * iteration when there is a page at index -1 but that is already
1957 * broken anyway.
Jan Kara72b045a2017-11-15 17:34:33 -08001958 */
1959 if (end == (pgoff_t)-1)
1960 *index = (pgoff_t)-1;
1961 else
1962 *index = end + 1;
1963out:
Nick Piggina60637c2008-07-25 19:45:31 -07001964 rcu_read_unlock();
1965
Linus Torvalds1da177e2005-04-16 15:20:36 -07001966 return ret;
1967}
Jan Kara72b045a2017-11-15 17:34:33 -08001968EXPORT_SYMBOL(find_get_pages_range_tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001969
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001970/*
1971 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1972 * a _large_ part of the i/o request. Imagine the worst scenario:
1973 *
1974 * ---R__________________________________________B__________
1975 * ^ reading here ^ bad block(assume 4k)
1976 *
1977 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1978 * => failing the whole request => read(R) => read(R+1) =>
1979 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1980 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1981 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1982 *
1983 * It is going insane. Fix it by quickly scaling down the readahead size.
1984 */
1985static void shrink_readahead_size_eio(struct file *filp,
1986 struct file_ra_state *ra)
1987{
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001988 ra->ra_pages /= 4;
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001989}
1990
Randy Dunlap485bb992006-06-23 02:03:49 -07001991/**
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02001992 * generic_file_buffered_read - generic file read routine
1993 * @iocb: the iocb to read
Al Viro6e58e792014-02-03 17:07:03 -05001994 * @iter: data destination
1995 * @written: already copied
Randy Dunlap485bb992006-06-23 02:03:49 -07001996 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001997 * This is a generic file read routine, and uses the
Randy Dunlap485bb992006-06-23 02:03:49 -07001998 * mapping->a_ops->readpage() function for the actual low-level stuff.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001999 *
2000 * This is really ugly. But the goto's actually try to clarify some
2001 * of the logic when it comes to error handling etc.
Mike Rapoporta862f682019-03-05 15:48:42 -08002002 *
2003 * Return:
2004 * * total number of bytes copied, including those the were already @written
2005 * * negative error code if nothing was copied
Linus Torvalds1da177e2005-04-16 15:20:36 -07002006 */
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002007static ssize_t generic_file_buffered_read(struct kiocb *iocb,
Al Viro6e58e792014-02-03 17:07:03 -05002008 struct iov_iter *iter, ssize_t written)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002009{
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002010 struct file *filp = iocb->ki_filp;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002011 struct address_space *mapping = filp->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002012 struct inode *inode = mapping->host;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002013 struct file_ra_state *ra = &filp->f_ra;
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002014 loff_t *ppos = &iocb->ki_pos;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002015 pgoff_t index;
2016 pgoff_t last_index;
2017 pgoff_t prev_index;
2018 unsigned long offset; /* offset into pagecache page */
Jan Karaec0f1632007-05-06 14:49:25 -07002019 unsigned int prev_offset;
Al Viro6e58e792014-02-03 17:07:03 -05002020 int error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002021
Wei Fangc2a97372016-10-07 17:01:52 -07002022 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
Linus Torvaldsd05c5f72016-12-14 12:45:25 -08002023 return 0;
Wei Fangc2a97372016-10-07 17:01:52 -07002024 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2025
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002026 index = *ppos >> PAGE_SHIFT;
2027 prev_index = ra->prev_pos >> PAGE_SHIFT;
2028 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2029 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2030 offset = *ppos & ~PAGE_MASK;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002031
Linus Torvalds1da177e2005-04-16 15:20:36 -07002032 for (;;) {
2033 struct page *page;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002034 pgoff_t end_index;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002035 loff_t isize;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002036 unsigned long nr, ret;
2037
Linus Torvalds1da177e2005-04-16 15:20:36 -07002038 cond_resched();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002039find_page:
Michal Hocko5abf1862017-02-03 13:13:29 -08002040 if (fatal_signal_pending(current)) {
2041 error = -EINTR;
2042 goto out;
2043 }
2044
Linus Torvalds1da177e2005-04-16 15:20:36 -07002045 page = find_get_page(mapping, index);
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002046 if (!page) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002047 if (iocb->ki_flags & IOCB_NOWAIT)
2048 goto would_block;
Rusty Russellcf914a72007-07-19 01:48:08 -07002049 page_cache_sync_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002050 ra, filp,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002051 index, last_index - index);
2052 page = find_get_page(mapping, index);
2053 if (unlikely(page == NULL))
2054 goto no_cached_page;
2055 }
2056 if (PageReadahead(page)) {
Rusty Russellcf914a72007-07-19 01:48:08 -07002057 page_cache_async_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002058 ra, filp, page,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002059 index, last_index - index);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002060 }
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002061 if (!PageUptodate(page)) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002062 if (iocb->ki_flags & IOCB_NOWAIT) {
2063 put_page(page);
2064 goto would_block;
2065 }
2066
Mel Gormanebded022016-03-15 14:55:39 -07002067 /*
2068 * See comment in do_read_cache_page on why
2069 * wait_on_page_locked is used to avoid unnecessarily
2070 * serialisations and why it's safe.
2071 */
Bart Van Asschec4b209a2016-10-07 16:58:33 -07002072 error = wait_on_page_locked_killable(page);
2073 if (unlikely(error))
2074 goto readpage_error;
Mel Gormanebded022016-03-15 14:55:39 -07002075 if (PageUptodate(page))
2076 goto page_ok;
2077
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002078 if (inode->i_blkbits == PAGE_SHIFT ||
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002079 !mapping->a_ops->is_partially_uptodate)
2080 goto page_not_up_to_date;
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002081 /* pipes can't handle partially uptodate pages */
David Howells00e23702018-10-22 13:07:28 +01002082 if (unlikely(iov_iter_is_pipe(iter)))
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002083 goto page_not_up_to_date;
Nick Piggin529ae9a2008-08-02 12:01:03 +02002084 if (!trylock_page(page))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002085 goto page_not_up_to_date;
Dave Hansen8d056cb2010-11-11 14:05:15 -08002086 /* Did it get truncated before we got the lock? */
2087 if (!page->mapping)
2088 goto page_not_up_to_date_locked;
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002089 if (!mapping->a_ops->is_partially_uptodate(page,
Al Viro6e58e792014-02-03 17:07:03 -05002090 offset, iter->count))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002091 goto page_not_up_to_date_locked;
2092 unlock_page(page);
2093 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002094page_ok:
NeilBrowna32ea1e2007-07-17 04:03:04 -07002095 /*
2096 * i_size must be checked after we know the page is Uptodate.
2097 *
2098 * Checking i_size after the check allows us to calculate
2099 * the correct value for "nr", which means the zero-filled
2100 * part of the page is not copied back to userspace (unless
2101 * another truncate extends the file - this is desired though).
2102 */
2103
2104 isize = i_size_read(inode);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002105 end_index = (isize - 1) >> PAGE_SHIFT;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002106 if (unlikely(!isize || index > end_index)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002107 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002108 goto out;
2109 }
2110
2111 /* nr is the maximum number of bytes to copy from this page */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002112 nr = PAGE_SIZE;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002113 if (index == end_index) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002114 nr = ((isize - 1) & ~PAGE_MASK) + 1;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002115 if (nr <= offset) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002116 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002117 goto out;
2118 }
2119 }
2120 nr = nr - offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002121
2122 /* If users can be writing to this page using arbitrary
2123 * virtual addresses, take care about potential aliasing
2124 * before reading the page on the kernel side.
2125 */
2126 if (mapping_writably_mapped(mapping))
2127 flush_dcache_page(page);
2128
2129 /*
Jan Karaec0f1632007-05-06 14:49:25 -07002130 * When a sequential read accesses a page several times,
2131 * only mark it as accessed the first time.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002132 */
Jan Karaec0f1632007-05-06 14:49:25 -07002133 if (prev_index != index || offset != prev_offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002134 mark_page_accessed(page);
2135 prev_index = index;
2136
2137 /*
2138 * Ok, we have the page, and it's up-to-date, so
2139 * now we can copy it to user space...
Linus Torvalds1da177e2005-04-16 15:20:36 -07002140 */
Al Viro6e58e792014-02-03 17:07:03 -05002141
2142 ret = copy_page_to_iter(page, offset, nr, iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002143 offset += ret;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002144 index += offset >> PAGE_SHIFT;
2145 offset &= ~PAGE_MASK;
Jan Kara6ce745e2007-05-06 14:49:26 -07002146 prev_offset = offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002147
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002148 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002149 written += ret;
2150 if (!iov_iter_count(iter))
2151 goto out;
2152 if (ret < nr) {
2153 error = -EFAULT;
2154 goto out;
2155 }
2156 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002157
2158page_not_up_to_date:
2159 /* Get exclusive access to the page ... */
Oleg Nesterov85462322008-06-08 21:20:43 +04002160 error = lock_page_killable(page);
2161 if (unlikely(error))
2162 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002163
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002164page_not_up_to_date_locked:
Nick Pigginda6052f2006-09-25 23:31:35 -07002165 /* Did it get truncated before we got the lock? */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002166 if (!page->mapping) {
2167 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002168 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002169 continue;
2170 }
2171
2172 /* Did somebody else fill it already? */
2173 if (PageUptodate(page)) {
2174 unlock_page(page);
2175 goto page_ok;
2176 }
2177
2178readpage:
Jeff Moyer91803b42010-05-26 11:49:40 -04002179 /*
2180 * A previous I/O error may have been due to temporary
2181 * failures, eg. multipath errors.
2182 * PG_error will be set again if readpage fails.
2183 */
2184 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002185 /* Start the actual read. The read will unlock the page. */
2186 error = mapping->a_ops->readpage(filp, page);
2187
Zach Brown994fc28c2005-12-15 14:28:17 -08002188 if (unlikely(error)) {
2189 if (error == AOP_TRUNCATED_PAGE) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002190 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002191 error = 0;
Zach Brown994fc28c2005-12-15 14:28:17 -08002192 goto find_page;
2193 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002194 goto readpage_error;
Zach Brown994fc28c2005-12-15 14:28:17 -08002195 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002196
2197 if (!PageUptodate(page)) {
Oleg Nesterov85462322008-06-08 21:20:43 +04002198 error = lock_page_killable(page);
2199 if (unlikely(error))
2200 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002201 if (!PageUptodate(page)) {
2202 if (page->mapping == NULL) {
2203 /*
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01002204 * invalidate_mapping_pages got it
Linus Torvalds1da177e2005-04-16 15:20:36 -07002205 */
2206 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002207 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002208 goto find_page;
2209 }
2210 unlock_page(page);
Fengguang Wu7ff81072007-10-16 01:24:35 -07002211 shrink_readahead_size_eio(filp, ra);
Oleg Nesterov85462322008-06-08 21:20:43 +04002212 error = -EIO;
2213 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002214 }
2215 unlock_page(page);
2216 }
2217
Linus Torvalds1da177e2005-04-16 15:20:36 -07002218 goto page_ok;
2219
2220readpage_error:
2221 /* UHHUH! A synchronous read error occurred. Report it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002222 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002223 goto out;
2224
2225no_cached_page:
2226 /*
2227 * Ok, it wasn't cached, so we need to create a new
2228 * page..
2229 */
Mel Gorman453f85d2017-11-15 17:38:03 -08002230 page = page_cache_alloc(mapping);
Nick Piggineb2be182007-10-16 01:24:57 -07002231 if (!page) {
Al Viro6e58e792014-02-03 17:07:03 -05002232 error = -ENOMEM;
Nick Piggineb2be182007-10-16 01:24:57 -07002233 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002234 }
Michal Hocko6afdb852015-06-24 16:58:06 -07002235 error = add_to_page_cache_lru(page, mapping, index,
Michal Hockoc62d2552015-11-06 16:28:49 -08002236 mapping_gfp_constraint(mapping, GFP_KERNEL));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002237 if (error) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002238 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002239 if (error == -EEXIST) {
2240 error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002241 goto find_page;
Al Viro6e58e792014-02-03 17:07:03 -05002242 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002243 goto out;
2244 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002245 goto readpage;
2246 }
2247
Milosz Tanski3239d832017-08-29 16:13:19 +02002248would_block:
2249 error = -EAGAIN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002250out:
Fengguang Wu7ff81072007-10-16 01:24:35 -07002251 ra->prev_pos = prev_index;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002252 ra->prev_pos <<= PAGE_SHIFT;
Fengguang Wu7ff81072007-10-16 01:24:35 -07002253 ra->prev_pos |= prev_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002254
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002255 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002256 file_accessed(filp);
Al Viro6e58e792014-02-03 17:07:03 -05002257 return written ? written : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002258}
2259
Randy Dunlap485bb992006-06-23 02:03:49 -07002260/**
Al Viro6abd2322014-04-04 14:20:57 -04002261 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002262 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002263 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002264 *
Al Viro6abd2322014-04-04 14:20:57 -04002265 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002266 * that can use the page cache directly.
Mike Rapoporta862f682019-03-05 15:48:42 -08002267 * Return:
2268 * * number of bytes copied, even for partial reads
2269 * * negative error code if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002270 */
2271ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002272generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002273{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002274 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002275 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002276
2277 if (!count)
2278 goto out; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002279
Al Viro2ba48ce2015-04-09 13:52:01 -04002280 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002281 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002282 struct address_space *mapping = file->f_mapping;
2283 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002284 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002285
Linus Torvalds1da177e2005-04-16 15:20:36 -07002286 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002287 if (iocb->ki_flags & IOCB_NOWAIT) {
2288 if (filemap_range_has_page(mapping, iocb->ki_pos,
2289 iocb->ki_pos + count - 1))
2290 return -EAGAIN;
2291 } else {
2292 retval = filemap_write_and_wait_range(mapping,
2293 iocb->ki_pos,
2294 iocb->ki_pos + count - 1);
2295 if (retval < 0)
2296 goto out;
2297 }
Al Viroed978a82014-03-05 22:53:04 -05002298
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002299 file_accessed(file);
2300
Al Viro5ecda132017-04-13 14:13:36 -04002301 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002302 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002303 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002304 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002305 }
Al Viro5b47d592017-05-08 13:54:47 -04002306 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002307
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002308 /*
2309 * Btrfs can have a short DIO read if we encounter
2310 * compressed extents, so if there was an error, or if
2311 * we've already read everything we wanted to, or if
2312 * there was a short read because we hit EOF, go ahead
2313 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002314 * the rest of the read. Buffered reads will not work for
2315 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002316 */
Al Viro5ecda132017-04-13 14:13:36 -04002317 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002318 IS_DAX(inode))
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002319 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002320 }
2321
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002322 retval = generic_file_buffered_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002323out:
2324 return retval;
2325}
Al Viroed978a82014-03-05 22:53:04 -05002326EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002327
Linus Torvalds1da177e2005-04-16 15:20:36 -07002328#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002329#define MMAP_LOTSAMISS (100)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002330static struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
2331 struct file *fpin)
2332{
2333 int flags = vmf->flags;
2334
2335 if (fpin)
2336 return fpin;
2337
2338 /*
2339 * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
2340 * anything, so we only pin the file and drop the mmap_sem if only
2341 * FAULT_FLAG_ALLOW_RETRY is set.
2342 */
2343 if ((flags & (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT)) ==
2344 FAULT_FLAG_ALLOW_RETRY) {
2345 fpin = get_file(vmf->vma->vm_file);
2346 up_read(&vmf->vma->vm_mm->mmap_sem);
2347 }
2348 return fpin;
2349}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002350
Linus Torvaldsef00e082009-06-16 15:31:25 -07002351/*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002352 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_sem
2353 * @vmf - the vm_fault for this fault.
2354 * @page - the page to lock.
2355 * @fpin - the pointer to the file we may pin (or is already pinned).
2356 *
2357 * This works similar to lock_page_or_retry in that it can drop the mmap_sem.
2358 * It differs in that it actually returns the page locked if it returns 1 and 0
2359 * if it couldn't lock the page. If we did have to drop the mmap_sem then fpin
2360 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002361 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002362static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2363 struct file **fpin)
2364{
2365 if (trylock_page(page))
2366 return 1;
2367
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002368 /*
2369 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2370 * the mmap_sem still held. That's how FAULT_FLAG_RETRY_NOWAIT
2371 * is supposed to work. We have way too many special cases..
2372 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002373 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2374 return 0;
2375
2376 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2377 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2378 if (__lock_page_killable(page)) {
2379 /*
2380 * We didn't have the right flags to drop the mmap_sem,
2381 * but all fault_handlers only check for fatal signals
2382 * if we return VM_FAULT_RETRY, so we need to drop the
2383 * mmap_sem here and return 0 if we don't have a fpin.
2384 */
2385 if (*fpin == NULL)
2386 up_read(&vmf->vma->vm_mm->mmap_sem);
2387 return 0;
2388 }
2389 } else
2390 __lock_page(page);
2391 return 1;
2392}
2393
2394
2395/*
2396 * Synchronous readahead happens when we don't even find a page in the page
2397 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2398 * to drop the mmap sem we return the file that was pinned in order for us to do
2399 * that. If we didn't pin a file then we return NULL. The file that is
2400 * returned needs to be fput()'ed when we're done with it.
2401 */
2402static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002403{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002404 struct file *file = vmf->vma->vm_file;
2405 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002406 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002407 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002408 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002409
2410 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002411 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002412 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002413 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002414 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002415
Josef Bacik2a1180f2019-03-13 11:44:18 -07002416 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002417 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang7ffc59b2009-06-16 15:31:38 -07002418 page_cache_sync_readahead(mapping, ra, file, offset,
2419 ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002420 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002421 }
2422
Andi Kleen207d04b2011-05-24 17:12:29 -07002423 /* Avoid banging the cache line if not needed */
2424 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002425 ra->mmap_miss++;
2426
2427 /*
2428 * Do we miss much more than hit in this file? If so,
2429 * stop bothering with read-ahead. It will only hurt.
2430 */
2431 if (ra->mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002432 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002433
Wu Fengguangd30a1102009-06-16 15:31:30 -07002434 /*
2435 * mmap read-around
2436 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002437 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002438 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2439 ra->size = ra->ra_pages;
2440 ra->async_size = ra->ra_pages / 4;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002441 ra_submit(ra, mapping, file);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002442 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002443}
2444
2445/*
2446 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002447 * so we want to possibly extend the readahead further. We return the file that
2448 * was pinned if we have to drop the mmap_sem in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002449 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002450static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2451 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002452{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002453 struct file *file = vmf->vma->vm_file;
2454 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002455 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002456 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002457 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002458
2459 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002460 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002461 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002462 if (ra->mmap_miss > 0)
2463 ra->mmap_miss--;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002464 if (PageReadahead(page)) {
2465 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002466 page_cache_async_readahead(mapping, ra, file,
2467 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002468 }
2469 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002470}
2471
Randy Dunlap485bb992006-06-23 02:03:49 -07002472/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002473 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002474 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002475 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002476 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002477 * mapped memory region to read in file data during a page fault.
2478 *
2479 * The goto's are kind of ugly, but this streamlines the normal case of having
2480 * it in the page cache, and handles the special cases reasonably without
2481 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002482 *
2483 * vma->vm_mm->mmap_sem must be held on entry.
2484 *
2485 * If our return value has VM_FAULT_RETRY set, it's because
2486 * lock_page_or_retry() returned 0.
2487 * The mmap_sem has usually been released in this case.
2488 * See __lock_page_or_retry() for the exception.
2489 *
2490 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2491 * has not been released.
2492 *
2493 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002494 *
2495 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002496 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002497vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002498{
2499 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002500 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002501 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002502 struct address_space *mapping = file->f_mapping;
2503 struct file_ra_state *ra = &file->f_ra;
2504 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002505 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002506 pgoff_t max_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002507 struct page *page;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002508 vm_fault_t ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002509
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002510 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2511 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002512 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002513
Linus Torvalds1da177e2005-04-16 15:20:36 -07002514 /*
Johannes Weiner49426422013-10-16 13:46:59 -07002515 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07002516 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002517 page = find_get_page(mapping, offset);
Shaohua Li45cac652012-10-08 16:32:19 -07002518 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002519 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002520 * We found the page, so try async readahead before
2521 * waiting for the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002522 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002523 fpin = do_async_mmap_readahead(vmf, page);
Shaohua Li45cac652012-10-08 16:32:19 -07002524 } else if (!page) {
Linus Torvaldsef00e082009-06-16 15:31:25 -07002525 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002526 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07002527 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002528 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002529 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002530retry_find:
Josef Bacika75d4c32019-03-13 11:44:14 -07002531 page = pagecache_get_page(mapping, offset,
2532 FGP_CREAT|FGP_FOR_MMAP,
2533 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002534 if (!page) {
2535 if (fpin)
2536 goto out_retry;
Josef Bacika75d4c32019-03-13 11:44:14 -07002537 return vmf_error(-ENOMEM);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002538 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002539 }
2540
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002541 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2542 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07002543
2544 /* Did it get truncated? */
2545 if (unlikely(page->mapping != mapping)) {
2546 unlock_page(page);
2547 put_page(page);
2548 goto retry_find;
2549 }
Sasha Levin309381fea2014-01-23 15:52:54 -08002550 VM_BUG_ON_PAGE(page->index != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07002551
Linus Torvalds1da177e2005-04-16 15:20:36 -07002552 /*
Nick Piggind00806b2007-07-19 01:46:57 -07002553 * We have a locked page in the page cache, now we need to check
2554 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002555 */
Nick Piggind00806b2007-07-19 01:46:57 -07002556 if (unlikely(!PageUptodate(page)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002557 goto page_not_uptodate;
2558
Linus Torvaldsef00e082009-06-16 15:31:25 -07002559 /*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002560 * We've made it this far and we had to drop our mmap_sem, now is the
2561 * time to return to the upper layer and have it re-find the vma and
2562 * redo the fault.
2563 */
2564 if (fpin) {
2565 unlock_page(page);
2566 goto out_retry;
2567 }
2568
2569 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002570 * Found the page and have a reference on it.
2571 * We must recheck i_size under page lock.
2572 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002573 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2574 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07002575 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002576 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07002577 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07002578 }
2579
Nick Piggind0217ac2007-07-19 01:47:03 -07002580 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07002581 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002582
Linus Torvalds1da177e2005-04-16 15:20:36 -07002583page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002584 /*
2585 * Umm, take care of errors if the page isn't up-to-date.
2586 * Try to re-read it _once_. We do this synchronously,
2587 * because there really aren't any performance issues here
2588 * and we need to check for errors.
2589 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002590 ClearPageError(page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002591 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Zach Brown994fc28c2005-12-15 14:28:17 -08002592 error = mapping->a_ops->readpage(file, page);
Miklos Szeredi3ef0f722008-05-14 16:05:37 -07002593 if (!error) {
2594 wait_on_page_locked(page);
2595 if (!PageUptodate(page))
2596 error = -EIO;
2597 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002598 if (fpin)
2599 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002600 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07002601
2602 if (!error || error == AOP_TRUNCATED_PAGE)
2603 goto retry_find;
2604
2605 /* Things didn't work out. Return zero to tell the mm layer so. */
2606 shrink_readahead_size_eio(file, ra);
Nick Piggind0217ac2007-07-19 01:47:03 -07002607 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002608
2609out_retry:
2610 /*
2611 * We dropped the mmap_sem, we need to return to the fault handler to
2612 * re-find the vma and come back and find our hopefully still populated
2613 * page.
2614 */
2615 if (page)
2616 put_page(page);
2617 if (fpin)
2618 fput(fpin);
2619 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07002620}
2621EXPORT_SYMBOL(filemap_fault);
2622
Jan Kara82b0f8c2016-12-14 15:06:58 -08002623void filemap_map_pages(struct vm_fault *vmf,
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002624 pgoff_t start_pgoff, pgoff_t end_pgoff)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002625{
Jan Kara82b0f8c2016-12-14 15:06:58 -08002626 struct file *file = vmf->vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002627 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002628 pgoff_t last_pgoff = start_pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002629 unsigned long max_idx;
Matthew Wilcox070e8072018-05-17 00:08:30 -04002630 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002631 struct page *head, *page;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002632
2633 rcu_read_lock();
Matthew Wilcox070e8072018-05-17 00:08:30 -04002634 xas_for_each(&xas, page, end_pgoff) {
2635 if (xas_retry(&xas, page))
2636 continue;
2637 if (xa_is_value(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002638 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002639
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002640 head = compound_head(page);
2641
Michal Hockoe0975b22018-12-28 00:38:36 -08002642 /*
2643 * Check for a locked page first, as a speculative
2644 * reference may adversely influence page migration.
2645 */
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002646 if (PageLocked(head))
Michal Hockoe0975b22018-12-28 00:38:36 -08002647 goto next;
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002648 if (!page_cache_get_speculative(head))
Matthew Wilcox070e8072018-05-17 00:08:30 -04002649 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002650
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002651 /* The page was split under us? */
2652 if (compound_head(page) != head)
2653 goto skip;
2654
2655 /* Has the page moved? */
Matthew Wilcox070e8072018-05-17 00:08:30 -04002656 if (unlikely(page != xas_reload(&xas)))
2657 goto skip;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002658
2659 if (!PageUptodate(page) ||
2660 PageReadahead(page) ||
2661 PageHWPoison(page))
2662 goto skip;
2663 if (!trylock_page(page))
2664 goto skip;
2665
2666 if (page->mapping != mapping || !PageUptodate(page))
2667 goto unlock;
2668
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002669 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2670 if (page->index >= max_idx)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002671 goto unlock;
2672
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002673 if (file->f_ra.mmap_miss > 0)
2674 file->f_ra.mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002675
Matthew Wilcox070e8072018-05-17 00:08:30 -04002676 vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002677 if (vmf->pte)
Matthew Wilcox070e8072018-05-17 00:08:30 -04002678 vmf->pte += xas.xa_index - last_pgoff;
2679 last_pgoff = xas.xa_index;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002680 if (alloc_set_pte(vmf, NULL, page))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002681 goto unlock;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002682 unlock_page(page);
2683 goto next;
2684unlock:
2685 unlock_page(page);
2686skip:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002687 put_page(page);
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002688next:
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002689 /* Huge page is mapped? No need to proceed. */
Jan Kara82b0f8c2016-12-14 15:06:58 -08002690 if (pmd_trans_huge(*vmf->pmd))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002691 break;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002692 }
2693 rcu_read_unlock();
2694}
2695EXPORT_SYMBOL(filemap_map_pages);
2696
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002697vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02002698{
2699 struct page *page = vmf->page;
Dave Jiang11bac802017-02-24 14:56:41 -08002700 struct inode *inode = file_inode(vmf->vma->vm_file);
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002701 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02002702
Jan Kara14da9202012-06-12 16:20:37 +02002703 sb_start_pagefault(inode->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08002704 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002705 lock_page(page);
2706 if (page->mapping != inode->i_mapping) {
2707 unlock_page(page);
2708 ret = VM_FAULT_NOPAGE;
2709 goto out;
2710 }
Jan Kara14da9202012-06-12 16:20:37 +02002711 /*
2712 * We mark the page dirty already here so that when freeze is in
2713 * progress, we are guaranteed that writeback during freezing will
2714 * see the dirty page and writeprotect it again.
2715 */
2716 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08002717 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002718out:
Jan Kara14da9202012-06-12 16:20:37 +02002719 sb_end_pagefault(inode->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002720 return ret;
2721}
Jan Kara4fcf1c62012-06-12 16:20:29 +02002722
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04002723const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07002724 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002725 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02002726 .page_mkwrite = filemap_page_mkwrite,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002727};
2728
2729/* This is used for a general mmap of a disk file */
2730
2731int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2732{
2733 struct address_space *mapping = file->f_mapping;
2734
2735 if (!mapping->a_ops->readpage)
2736 return -ENOEXEC;
2737 file_accessed(file);
2738 vma->vm_ops = &generic_file_vm_ops;
2739 return 0;
2740}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002741
2742/*
2743 * This is for filesystems which do not implement ->writepage.
2744 */
2745int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2746{
2747 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2748 return -EINVAL;
2749 return generic_file_mmap(file, vma);
2750}
2751#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07002752vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann453972282018-04-13 15:35:27 -07002753{
Souptick Joarder4b96a372018-10-26 15:04:03 -07002754 return VM_FAULT_SIGBUS;
Arnd Bergmann453972282018-04-13 15:35:27 -07002755}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002756int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2757{
2758 return -ENOSYS;
2759}
2760int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2761{
2762 return -ENOSYS;
2763}
2764#endif /* CONFIG_MMU */
2765
Arnd Bergmann453972282018-04-13 15:35:27 -07002766EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002767EXPORT_SYMBOL(generic_file_mmap);
2768EXPORT_SYMBOL(generic_file_readonly_mmap);
2769
Sasha Levin67f9fd92014-04-03 14:48:18 -07002770static struct page *wait_on_page_read(struct page *page)
2771{
2772 if (!IS_ERR(page)) {
2773 wait_on_page_locked(page);
2774 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002775 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07002776 page = ERR_PTR(-EIO);
2777 }
2778 }
2779 return page;
2780}
2781
Mel Gorman32b63522016-03-15 14:55:36 -07002782static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07002783 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002784 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002785 void *data,
2786 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002787{
Nick Piggineb2be182007-10-16 01:24:57 -07002788 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002789 int err;
2790repeat:
2791 page = find_get_page(mapping, index);
2792 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08002793 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002794 if (!page)
2795 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002796 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002797 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002798 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07002799 if (err == -EEXIST)
2800 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05002801 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002802 return ERR_PTR(err);
2803 }
Mel Gorman32b63522016-03-15 14:55:36 -07002804
2805filler:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002806 err = filler(data, page);
2807 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002808 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002809 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002810 }
Mel Gorman32b63522016-03-15 14:55:36 -07002811
2812 page = wait_on_page_read(page);
2813 if (IS_ERR(page))
2814 return page;
2815 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002816 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002817 if (PageUptodate(page))
2818 goto out;
2819
Mel Gormanebded022016-03-15 14:55:39 -07002820 /*
2821 * Page is not up to date and may be locked due one of the following
2822 * case a: Page is being filled and the page lock is held
2823 * case b: Read/write error clearing the page uptodate status
2824 * case c: Truncation in progress (page locked)
2825 * case d: Reclaim in progress
2826 *
2827 * Case a, the page will be up to date when the page is unlocked.
2828 * There is no need to serialise on the page lock here as the page
2829 * is pinned so the lock gives no additional protection. Even if the
2830 * the page is truncated, the data is still valid if PageUptodate as
2831 * it's a race vs truncate race.
2832 * Case b, the page will not be up to date
2833 * Case c, the page may be truncated but in itself, the data may still
2834 * be valid after IO completes as it's a read vs truncate race. The
2835 * operation must restart if the page is not uptodate on unlock but
2836 * otherwise serialising on page lock to stabilise the mapping gives
2837 * no additional guarantees to the caller as the page lock is
2838 * released before return.
2839 * Case d, similar to truncation. If reclaim holds the page lock, it
2840 * will be a race with remove_mapping that determines if the mapping
2841 * is valid on unlock but otherwise the data is valid and there is
2842 * no need to serialise with page lock.
2843 *
2844 * As the page lock gives no additional guarantee, we optimistically
2845 * wait on the page to be unlocked and check if it's up to date and
2846 * use the page if it is. Otherwise, the page lock is required to
2847 * distinguish between the different cases. The motivation is that we
2848 * avoid spurious serialisations and wakeups when multiple processes
2849 * wait on the same page for IO to complete.
2850 */
2851 wait_on_page_locked(page);
2852 if (PageUptodate(page))
2853 goto out;
2854
2855 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002856 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07002857
2858 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002859 if (!page->mapping) {
2860 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002861 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002862 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002863 }
Mel Gormanebded022016-03-15 14:55:39 -07002864
2865 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002866 if (PageUptodate(page)) {
2867 unlock_page(page);
2868 goto out;
2869 }
Mel Gorman32b63522016-03-15 14:55:36 -07002870 goto filler;
2871
David Howellsc855ff32007-05-09 13:42:20 +01002872out:
Nick Piggin6fe69002007-05-06 14:49:04 -07002873 mark_page_accessed(page);
2874 return page;
2875}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002876
2877/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07002878 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002879 * @mapping: the page's address_space
2880 * @index: the page index
2881 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002882 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002883 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002884 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07002885 * not set, try to fill the page and wait for it to become unlocked.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002886 *
2887 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002888 *
2889 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002890 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07002891struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002892 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002893 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002894 void *data)
2895{
2896 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2897}
Sasha Levin67f9fd92014-04-03 14:48:18 -07002898EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002899
2900/**
2901 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2902 * @mapping: the page's address_space
2903 * @index: the page index
2904 * @gfp: the page allocator flags to use if allocating
2905 *
2906 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002907 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002908 *
2909 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002910 *
2911 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002912 */
2913struct page *read_cache_page_gfp(struct address_space *mapping,
2914 pgoff_t index,
2915 gfp_t gfp)
2916{
2917 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2918
Sasha Levin67f9fd92014-04-03 14:48:18 -07002919 return do_read_cache_page(mapping, index, filler, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002920}
2921EXPORT_SYMBOL(read_cache_page_gfp);
2922
Nick Piggin2f718ff2007-10-16 01:24:59 -07002923/*
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002924 * Don't operate on ranges the page cache doesn't support, and don't exceed the
2925 * LFS limits. If pos is under the limit it becomes a short access. If it
2926 * exceeds the limit we return -EFBIG.
2927 */
2928static int generic_access_check_limits(struct file *file, loff_t pos,
2929 loff_t *count)
2930{
2931 struct inode *inode = file->f_mapping->host;
2932 loff_t max_size = inode->i_sb->s_maxbytes;
2933
2934 if (!(file->f_flags & O_LARGEFILE))
2935 max_size = MAX_NON_LFS;
2936
2937 if (unlikely(pos >= max_size))
2938 return -EFBIG;
2939 *count = min(*count, max_size - pos);
2940 return 0;
2941}
2942
2943static int generic_write_check_limits(struct file *file, loff_t pos,
2944 loff_t *count)
2945{
2946 loff_t limit = rlimit(RLIMIT_FSIZE);
2947
2948 if (limit != RLIM_INFINITY) {
2949 if (pos >= limit) {
2950 send_sig(SIGXFSZ, current, 0);
2951 return -EFBIG;
2952 }
2953 *count = min(*count, limit - pos);
2954 }
2955
2956 return generic_access_check_limits(file, pos, count);
2957}
2958
2959/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002960 * Performs necessary checks before doing a write
2961 *
Randy Dunlap485bb992006-06-23 02:03:49 -07002962 * Can adjust writing position or amount of bytes to write.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002963 * Returns appropriate error code that caller should return or
2964 * zero in case that write should be allowed.
2965 */
Al Viro3309dd02015-04-09 12:55:47 -04002966inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002967{
Al Viro3309dd02015-04-09 12:55:47 -04002968 struct file *file = iocb->ki_filp;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002969 struct inode *inode = file->f_mapping->host;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002970 loff_t count;
2971 int ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002972
Al Viro3309dd02015-04-09 12:55:47 -04002973 if (!iov_iter_count(from))
2974 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002975
Al Viro0fa6b002015-04-04 04:05:48 -04002976 /* FIXME: this is for backwards compatibility with 2.4 */
Al Viro2ba48ce2015-04-09 13:52:01 -04002977 if (iocb->ki_flags & IOCB_APPEND)
Al Viro3309dd02015-04-09 12:55:47 -04002978 iocb->ki_pos = i_size_read(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002979
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002980 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2981 return -EINVAL;
2982
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002983 count = iov_iter_count(from);
2984 ret = generic_write_check_limits(file, iocb->ki_pos, &count);
2985 if (ret)
2986 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002987
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002988 iov_iter_truncate(from, count);
Al Viro3309dd02015-04-09 12:55:47 -04002989 return iov_iter_count(from);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002990}
2991EXPORT_SYMBOL(generic_write_checks);
2992
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11002993/*
2994 * Performs necessary checks before doing a clone.
2995 *
2996 * Can adjust amount of bytes to clone.
2997 * Returns appropriate error code that caller should return or
2998 * zero in case the clone should be allowed.
2999 */
3000int generic_remap_checks(struct file *file_in, loff_t pos_in,
3001 struct file *file_out, loff_t pos_out,
Darrick J. Wong42ec3d42018-10-30 10:41:49 +11003002 loff_t *req_count, unsigned int remap_flags)
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003003{
3004 struct inode *inode_in = file_in->f_mapping->host;
3005 struct inode *inode_out = file_out->f_mapping->host;
3006 uint64_t count = *req_count;
3007 uint64_t bcount;
3008 loff_t size_in, size_out;
3009 loff_t bs = inode_out->i_sb->s_blocksize;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003010 int ret;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003011
3012 /* The start of both ranges must be aligned to an fs block. */
3013 if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_out, bs))
3014 return -EINVAL;
3015
3016 /* Ensure offsets don't wrap. */
3017 if (pos_in + count < pos_in || pos_out + count < pos_out)
3018 return -EINVAL;
3019
3020 size_in = i_size_read(inode_in);
3021 size_out = i_size_read(inode_out);
3022
3023 /* Dedupe requires both ranges to be within EOF. */
Darrick J. Wong3d281932018-10-30 10:41:34 +11003024 if ((remap_flags & REMAP_FILE_DEDUP) &&
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003025 (pos_in >= size_in || pos_in + count > size_in ||
3026 pos_out >= size_out || pos_out + count > size_out))
3027 return -EINVAL;
3028
3029 /* Ensure the infile range is within the infile. */
3030 if (pos_in >= size_in)
3031 return -EINVAL;
3032 count = min(count, size_in - (uint64_t)pos_in);
3033
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003034 ret = generic_access_check_limits(file_in, pos_in, &count);
3035 if (ret)
3036 return ret;
3037
3038 ret = generic_write_check_limits(file_out, pos_out, &count);
3039 if (ret)
3040 return ret;
3041
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003042 /*
3043 * If the user wanted us to link to the infile's EOF, round up to the
3044 * next block boundary for this check.
3045 *
3046 * Otherwise, make sure the count is also block-aligned, having
3047 * already confirmed the starting offsets' block alignment.
3048 */
3049 if (pos_in + count == size_in) {
3050 bcount = ALIGN(size_in, bs) - pos_in;
3051 } else {
3052 if (!IS_ALIGNED(count, bs))
Darrick J. Wongeca36542018-10-30 10:42:10 +11003053 count = ALIGN_DOWN(count, bs);
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003054 bcount = count;
3055 }
3056
3057 /* Don't allow overlapped cloning within the same file. */
3058 if (inode_in == inode_out &&
3059 pos_out + bcount > pos_in &&
3060 pos_out < pos_in + bcount)
3061 return -EINVAL;
3062
Darrick J. Wongeca36542018-10-30 10:42:10 +11003063 /*
3064 * We shortened the request but the caller can't deal with that, so
3065 * bounce the request back to userspace.
3066 */
3067 if (*req_count != count && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003068 return -EINVAL;
3069
Darrick J. Wongeca36542018-10-30 10:42:10 +11003070 *req_count = count;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003071 return 0;
3072}
3073
Nick Pigginafddba42007-10-16 01:25:01 -07003074int pagecache_write_begin(struct file *file, struct address_space *mapping,
3075 loff_t pos, unsigned len, unsigned flags,
3076 struct page **pagep, void **fsdata)
3077{
3078 const struct address_space_operations *aops = mapping->a_ops;
3079
Nick Piggin4e02ed42008-10-29 14:00:55 -07003080 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003081 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003082}
3083EXPORT_SYMBOL(pagecache_write_begin);
3084
3085int pagecache_write_end(struct file *file, struct address_space *mapping,
3086 loff_t pos, unsigned len, unsigned copied,
3087 struct page *page, void *fsdata)
3088{
3089 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003090
Nick Piggin4e02ed42008-10-29 14:00:55 -07003091 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003092}
3093EXPORT_SYMBOL(pagecache_write_end);
3094
Linus Torvalds1da177e2005-04-16 15:20:36 -07003095ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003096generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003097{
3098 struct file *file = iocb->ki_filp;
3099 struct address_space *mapping = file->f_mapping;
3100 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003101 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003102 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003103 size_t write_len;
3104 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003105
Al Viro0c949332014-03-22 06:51:37 -04003106 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003107 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003108
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003109 if (iocb->ki_flags & IOCB_NOWAIT) {
3110 /* If there are pages to writeback, return */
3111 if (filemap_range_has_page(inode->i_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003112 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003113 return -EAGAIN;
3114 } else {
3115 written = filemap_write_and_wait_range(mapping, pos,
3116 pos + write_len - 1);
3117 if (written)
3118 goto out;
3119 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003120
3121 /*
3122 * After a write we want buffered reads to be sure to go to disk to get
3123 * the new data. We invalidate clean cached page from the region we're
3124 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003125 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003126 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003127 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003128 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003129 /*
3130 * If a page can not be invalidated, return 0 to fall back
3131 * to buffered write.
3132 */
3133 if (written) {
3134 if (written == -EBUSY)
3135 return 0;
3136 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003137 }
3138
Al Viro639a93a52017-04-13 14:10:15 -04003139 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003140
3141 /*
3142 * Finally, try again to invalidate clean pages which might have been
3143 * cached by non-direct readahead, or faulted in by get_user_pages()
3144 * if the source of the write was an mmap'ed region of the file
3145 * we're writing. Either one is a pretty crazy thing to do,
3146 * so we don't support it 100%. If this invalidation
3147 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003148 *
3149 * Most of the time we do not need this since dio_complete() will do
3150 * the invalidation for us. However there are some file systems that
3151 * do not end up with dio_complete() being called, so let's not break
3152 * them by removing it completely
Christoph Hellwiga969e902008-07-23 21:27:04 -07003153 */
Lukas Czerner332391a2017-09-21 08:16:29 -06003154 if (mapping->nrpages)
3155 invalidate_inode_pages2_range(mapping,
3156 pos >> PAGE_SHIFT, end);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003157
Linus Torvalds1da177e2005-04-16 15:20:36 -07003158 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003159 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003160 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003161 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3162 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003163 mark_inode_dirty(inode);
3164 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003165 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003166 }
Al Viro639a93a52017-04-13 14:10:15 -04003167 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003168out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003169 return written;
3170}
3171EXPORT_SYMBOL(generic_file_direct_write);
3172
Nick Piggineb2be182007-10-16 01:24:57 -07003173/*
3174 * Find or create a page at the given pagecache position. Return the locked
3175 * page. This function is specifically for buffered writes.
3176 */
Nick Piggin54566b22009-01-04 12:00:53 -08003177struct page *grab_cache_page_write_begin(struct address_space *mapping,
3178 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003179{
Nick Piggineb2be182007-10-16 01:24:57 -07003180 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003181 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003182
Nick Piggin54566b22009-01-04 12:00:53 -08003183 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003184 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003185
Mel Gorman2457aec2014-06-04 16:10:31 -07003186 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003187 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003188 if (page)
3189 wait_for_stable_page(page);
3190
Nick Piggineb2be182007-10-16 01:24:57 -07003191 return page;
3192}
Nick Piggin54566b22009-01-04 12:00:53 -08003193EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003194
Al Viro3b93f912014-02-11 21:34:08 -05003195ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003196 struct iov_iter *i, loff_t pos)
3197{
3198 struct address_space *mapping = file->f_mapping;
3199 const struct address_space_operations *a_ops = mapping->a_ops;
3200 long status = 0;
3201 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003202 unsigned int flags = 0;
3203
Nick Pigginafddba42007-10-16 01:25:01 -07003204 do {
3205 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003206 unsigned long offset; /* Offset into pagecache page */
3207 unsigned long bytes; /* Bytes to write to page */
3208 size_t copied; /* Bytes copied from user */
3209 void *fsdata;
3210
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003211 offset = (pos & (PAGE_SIZE - 1));
3212 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003213 iov_iter_count(i));
3214
3215again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003216 /*
3217 * Bring in the user page that we will copy from _first_.
3218 * Otherwise there's a nasty deadlock on copying from the
3219 * same page as we're writing to, without it being marked
3220 * up-to-date.
3221 *
3222 * Not only is this an optimisation, but it is also required
3223 * to check that the address is actually valid, when atomic
3224 * usercopies are used, below.
3225 */
3226 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3227 status = -EFAULT;
3228 break;
3229 }
3230
Jan Kara296291c2015-10-22 13:32:21 -07003231 if (fatal_signal_pending(current)) {
3232 status = -EINTR;
3233 break;
3234 }
3235
Nick Piggin674b8922007-10-16 01:25:03 -07003236 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003237 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003238 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003239 break;
3240
anfei zhou931e80e2010-02-02 13:44:02 -08003241 if (mapping_writably_mapped(mapping))
3242 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003243
Nick Pigginafddba42007-10-16 01:25:01 -07003244 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
Nick Pigginafddba42007-10-16 01:25:01 -07003245 flush_dcache_page(page);
3246
3247 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3248 page, fsdata);
3249 if (unlikely(status < 0))
3250 break;
3251 copied = status;
3252
3253 cond_resched();
3254
Nick Piggin124d3b72008-02-02 15:01:17 +01003255 iov_iter_advance(i, copied);
Nick Pigginafddba42007-10-16 01:25:01 -07003256 if (unlikely(copied == 0)) {
3257 /*
3258 * If we were unable to copy any data at all, we must
3259 * fall back to a single segment length write.
3260 *
3261 * If we didn't fallback here, we could livelock
3262 * because not all segments in the iov can be copied at
3263 * once without a pagefault.
3264 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003265 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003266 iov_iter_single_seg_count(i));
3267 goto again;
3268 }
Nick Pigginafddba42007-10-16 01:25:01 -07003269 pos += copied;
3270 written += copied;
3271
3272 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003273 } while (iov_iter_count(i));
3274
3275 return written ? written : status;
3276}
Al Viro3b93f912014-02-11 21:34:08 -05003277EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003278
Jan Karae4dd9de2009-08-17 18:10:06 +02003279/**
Al Viro81742022014-04-03 03:17:43 -04003280 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003281 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003282 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003283 *
3284 * This function does all the work needed for actually writing data to a
3285 * file. It does all basic checks, removes SUID from the file, updates
3286 * modification times and calls proper subroutines depending on whether we
3287 * do direct IO or a standard buffered write.
3288 *
3289 * It expects i_mutex to be grabbed unless we work on a block device or similar
3290 * object which does not need locking at all.
3291 *
3292 * This function does *not* take care of syncing data in case of O_SYNC write.
3293 * A caller has to handle it. This is mainly due to the fact that we want to
3294 * avoid syncing under i_mutex.
Mike Rapoporta862f682019-03-05 15:48:42 -08003295 *
3296 * Return:
3297 * * number of bytes written, even for truncated writes
3298 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003299 */
Al Viro81742022014-04-03 03:17:43 -04003300ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003301{
3302 struct file *file = iocb->ki_filp;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003303 struct address_space * mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003304 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003305 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003306 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003307 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003308
Linus Torvalds1da177e2005-04-16 15:20:36 -07003309 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003310 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003311 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003312 if (err)
3313 goto out;
3314
Josef Bacikc3b2da32012-03-26 09:59:21 -04003315 err = file_update_time(file);
3316 if (err)
3317 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003318
Al Viro2ba48ce2015-04-09 13:52:01 -04003319 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003320 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003321
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003322 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003323 /*
3324 * If the write stopped short of completing, fall back to
3325 * buffered writes. Some filesystems do this for writes to
3326 * holes, for example. For DAX files, a buffered write will
3327 * not succeed (even if it did, DAX does not handle dirty
3328 * page-cache pages correctly).
3329 */
Al Viro0b8def92015-04-07 10:22:53 -04003330 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003331 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003332
Al Viro0b8def92015-04-07 10:22:53 -04003333 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003334 /*
Al Viro3b93f912014-02-11 21:34:08 -05003335 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003336 * then we want to return the number of bytes which were
3337 * direct-written, or the error code if that was zero. Note
3338 * that this differs from normal direct-io semantics, which
3339 * will return -EFOO even if some bytes were written.
3340 */
Al Viro60bb4522014-08-08 12:39:16 -04003341 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003342 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003343 goto out;
3344 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003345 /*
3346 * We need to ensure that the page cache pages are written to
3347 * disk and invalidated to preserve the expected O_DIRECT
3348 * semantics.
3349 */
Al Viro3b93f912014-02-11 21:34:08 -05003350 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003351 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003352 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003353 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003354 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003355 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003356 pos >> PAGE_SHIFT,
3357 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003358 } else {
3359 /*
3360 * We don't know how much we wrote, so just return
3361 * the number of bytes which were direct-written
3362 */
3363 }
3364 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003365 written = generic_perform_write(file, from, iocb->ki_pos);
3366 if (likely(written > 0))
3367 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003368 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003369out:
3370 current->backing_dev_info = NULL;
3371 return written ? written : err;
3372}
Al Viro81742022014-04-03 03:17:43 -04003373EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003374
Jan Karae4dd9de2009-08-17 18:10:06 +02003375/**
Al Viro81742022014-04-03 03:17:43 -04003376 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003377 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003378 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003379 *
Al Viro81742022014-04-03 03:17:43 -04003380 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003381 * filesystems. It takes care of syncing the file in case of O_SYNC file
3382 * and acquires i_mutex as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003383 * Return:
3384 * * negative error code if no data has been written at all of
3385 * vfs_fsync_range() failed for a synchronous write
3386 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003387 */
Al Viro81742022014-04-03 03:17:43 -04003388ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003389{
3390 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003391 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003392 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003393
Al Viro59551022016-01-22 15:40:57 -05003394 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003395 ret = generic_write_checks(iocb, from);
3396 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003397 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003398 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003399
Christoph Hellwige2592212016-04-07 08:52:01 -07003400 if (ret > 0)
3401 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003402 return ret;
3403}
Al Viro81742022014-04-03 03:17:43 -04003404EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003405
David Howellscf9a2ae2006-08-29 19:05:54 +01003406/**
3407 * try_to_release_page() - release old fs-specific metadata on a page
3408 *
3409 * @page: the page which the kernel is trying to free
3410 * @gfp_mask: memory allocation flags (and I/O mode)
3411 *
3412 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003413 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003414 *
David Howells266cf652009-04-03 16:42:36 +01003415 * This may also be called if PG_fscache is set on a page, indicating that the
3416 * page is known to the local caching routines.
3417 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003418 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003419 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003420 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003421 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003422 */
3423int try_to_release_page(struct page *page, gfp_t gfp_mask)
3424{
3425 struct address_space * const mapping = page->mapping;
3426
3427 BUG_ON(!PageLocked(page));
3428 if (PageWriteback(page))
3429 return 0;
3430
3431 if (mapping && mapping->a_ops->releasepage)
3432 return mapping->a_ops->releasepage(page, gfp_mask);
3433 return try_to_free_buffers(page);
3434}
3435
3436EXPORT_SYMBOL(try_to_release_page);