blob: d6f7596f148f6f566024a24f5fbc8f0d449e91be [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/**
Ross Zwisleraa0bfcd2019-06-20 17:05:37 -0400553 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
554 * @mapping: 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 given address space in the
559 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
560 * this function does not clear error status of the address space.
561 *
562 * Use this function if callers don't handle errors themselves. Expected
563 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
564 * fsfreeze(8)
565 */
566int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
567 loff_t start_byte, loff_t end_byte)
568{
569 __filemap_fdatawait_range(mapping, start_byte, end_byte);
570 return filemap_check_and_keep_errors(mapping);
571}
572EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
573
574/**
Jeff Laytona823e452017-07-28 07:24:43 -0400575 * file_fdatawait_range - wait for writeback to complete
576 * @file: file pointing to address space structure to wait for
577 * @start_byte: offset in bytes where the range starts
578 * @end_byte: offset in bytes where the range ends (inclusive)
579 *
580 * Walk the list of under-writeback pages of the address space that file
581 * refers to, in the given range and wait for all of them. Check error
582 * status of the address space vs. the file->f_wb_err cursor and return it.
583 *
584 * Since the error status of the file is advanced by this function,
585 * callers are responsible for checking the return value and handling and/or
586 * reporting the error.
Mike Rapoporta862f682019-03-05 15:48:42 -0800587 *
588 * Return: error status of the address space vs. the file->f_wb_err cursor.
Jeff Laytona823e452017-07-28 07:24:43 -0400589 */
590int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
591{
592 struct address_space *mapping = file->f_mapping;
593
594 __filemap_fdatawait_range(mapping, start_byte, end_byte);
595 return file_check_and_advance_wb_err(file);
596}
597EXPORT_SYMBOL(file_fdatawait_range);
598
599/**
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800600 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
601 * @mapping: address space structure to wait for
602 *
603 * Walk the list of under-writeback pages of the given address space
604 * and wait for all of them. Unlike filemap_fdatawait(), this function
605 * does not clear error status of the address space.
606 *
607 * Use this function if callers don't handle errors themselves. Expected
608 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
609 * fsfreeze(8)
Mike Rapoporta862f682019-03-05 15:48:42 -0800610 *
611 * Return: error status of the address space.
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800612 */
Jeff Layton76341ca2017-07-06 07:02:22 -0400613int filemap_fdatawait_keep_errors(struct address_space *mapping)
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800614{
Jeff Laytonffb959b2017-07-31 10:29:38 -0400615 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
Jeff Layton76341ca2017-07-06 07:02:22 -0400616 return filemap_check_and_keep_errors(mapping);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800617}
Jeff Layton76341ca2017-07-06 07:02:22 -0400618EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
Junichi Nomuraaa750fd2015-11-05 18:47:23 -0800619
Jeff Layton9326c9b2017-07-26 10:21:11 -0400620static bool mapping_needs_writeback(struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700621{
Jeff Layton9326c9b2017-07-26 10:21:11 -0400622 return (!dax_mapping(mapping) && mapping->nrpages) ||
623 (dax_mapping(mapping) && mapping->nrexceptional);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700624}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700625
626int filemap_write_and_wait(struct address_space *mapping)
627{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800628 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700629
Jeff Layton9326c9b2017-07-26 10:21:11 -0400630 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800631 err = filemap_fdatawrite(mapping);
632 /*
633 * Even if the above returned error, the pages may be
634 * written partially (e.g. -ENOSPC), so we wait for it.
635 * But the -EIO is special case, it may indicate the worst
636 * thing (e.g. bug) happened, so we avoid waiting for it.
637 */
638 if (err != -EIO) {
639 int err2 = filemap_fdatawait(mapping);
640 if (!err)
641 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400642 } else {
643 /* Clear any previously stored errors */
644 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800645 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700646 } else {
647 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700648 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800649 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700650}
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800651EXPORT_SYMBOL(filemap_write_and_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700652
Randy Dunlap485bb992006-06-23 02:03:49 -0700653/**
654 * filemap_write_and_wait_range - write out & wait on a file range
655 * @mapping: the address_space for the pages
656 * @lstart: offset in bytes where the range starts
657 * @lend: offset in bytes where the range ends (inclusive)
658 *
Andrew Morton469eb4d2006-03-24 03:17:45 -0800659 * Write out and wait upon file offsets lstart->lend, inclusive.
660 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -0300661 * Note that @lend is inclusive (describes the last byte to be written) so
Andrew Morton469eb4d2006-03-24 03:17:45 -0800662 * that this function can be used to write to the very end-of-file (end = -1).
Mike Rapoporta862f682019-03-05 15:48:42 -0800663 *
664 * Return: error status of the address space.
Andrew Morton469eb4d2006-03-24 03:17:45 -0800665 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700666int filemap_write_and_wait_range(struct address_space *mapping,
667 loff_t lstart, loff_t lend)
668{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800669 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700670
Jeff Layton9326c9b2017-07-26 10:21:11 -0400671 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800672 err = __filemap_fdatawrite_range(mapping, lstart, lend,
673 WB_SYNC_ALL);
674 /* See comment of filemap_write_and_wait() */
675 if (err != -EIO) {
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200676 int err2 = filemap_fdatawait_range(mapping,
677 lstart, lend);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800678 if (!err)
679 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400680 } else {
681 /* Clear any previously stored errors */
682 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800683 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700684 } else {
685 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800687 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688}
Chris Masonf6995582009-04-15 13:22:37 -0400689EXPORT_SYMBOL(filemap_write_and_wait_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690
Jeff Layton5660e132017-07-06 07:02:25 -0400691void __filemap_set_wb_err(struct address_space *mapping, int err)
692{
Jeff Layton3acdfd22017-07-24 06:22:15 -0400693 errseq_t eseq = errseq_set(&mapping->wb_err, err);
Jeff Layton5660e132017-07-06 07:02:25 -0400694
695 trace_filemap_set_wb_err(mapping, eseq);
696}
697EXPORT_SYMBOL(__filemap_set_wb_err);
698
699/**
700 * file_check_and_advance_wb_err - report wb error (if any) that was previously
701 * and advance wb_err to current one
702 * @file: struct file on which the error is being reported
703 *
704 * When userland calls fsync (or something like nfsd does the equivalent), we
705 * want to report any writeback errors that occurred since the last fsync (or
706 * since the file was opened if there haven't been any).
707 *
708 * Grab the wb_err from the mapping. If it matches what we have in the file,
709 * then just quickly return 0. The file is all caught up.
710 *
711 * If it doesn't match, then take the mapping value, set the "seen" flag in
712 * it and try to swap it into place. If it works, or another task beat us
713 * to it with the new value, then update the f_wb_err and return the error
714 * portion. The error at this point must be reported via proper channels
715 * (a'la fsync, or NFS COMMIT operation, etc.).
716 *
717 * While we handle mapping->wb_err with atomic operations, the f_wb_err
718 * value is protected by the f_lock since we must ensure that it reflects
719 * the latest value swapped in for this file descriptor.
Mike Rapoporta862f682019-03-05 15:48:42 -0800720 *
721 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400722 */
723int file_check_and_advance_wb_err(struct file *file)
724{
725 int err = 0;
726 errseq_t old = READ_ONCE(file->f_wb_err);
727 struct address_space *mapping = file->f_mapping;
728
729 /* Locklessly handle the common case where nothing has changed */
730 if (errseq_check(&mapping->wb_err, old)) {
731 /* Something changed, must use slow path */
732 spin_lock(&file->f_lock);
733 old = file->f_wb_err;
734 err = errseq_check_and_advance(&mapping->wb_err,
735 &file->f_wb_err);
736 trace_file_check_and_advance_wb_err(file, old);
737 spin_unlock(&file->f_lock);
738 }
Jeff Laytonf4e222c2017-10-03 16:15:25 -0700739
740 /*
741 * We're mostly using this function as a drop in replacement for
742 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
743 * that the legacy code would have had on these flags.
744 */
745 clear_bit(AS_EIO, &mapping->flags);
746 clear_bit(AS_ENOSPC, &mapping->flags);
Jeff Layton5660e132017-07-06 07:02:25 -0400747 return err;
748}
749EXPORT_SYMBOL(file_check_and_advance_wb_err);
750
751/**
752 * file_write_and_wait_range - write out & wait on a file range
753 * @file: file pointing to address_space with pages
754 * @lstart: offset in bytes where the range starts
755 * @lend: offset in bytes where the range ends (inclusive)
756 *
757 * Write out and wait upon file offsets lstart->lend, inclusive.
758 *
759 * Note that @lend is inclusive (describes the last byte to be written) so
760 * that this function can be used to write to the very end-of-file (end = -1).
761 *
762 * After writing out and waiting on the data, we check and advance the
763 * f_wb_err cursor to the latest value, and return any errors detected there.
Mike Rapoporta862f682019-03-05 15:48:42 -0800764 *
765 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400766 */
767int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
768{
769 int err = 0, err2;
770 struct address_space *mapping = file->f_mapping;
771
Jeff Layton9326c9b2017-07-26 10:21:11 -0400772 if (mapping_needs_writeback(mapping)) {
Jeff Layton5660e132017-07-06 07:02:25 -0400773 err = __filemap_fdatawrite_range(mapping, lstart, lend,
774 WB_SYNC_ALL);
775 /* See comment of filemap_write_and_wait() */
776 if (err != -EIO)
777 __filemap_fdatawait_range(mapping, lstart, lend);
778 }
779 err2 = file_check_and_advance_wb_err(file);
780 if (!err)
781 err = err2;
782 return err;
783}
784EXPORT_SYMBOL(file_write_and_wait_range);
785
Randy Dunlap485bb992006-06-23 02:03:49 -0700786/**
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700787 * replace_page_cache_page - replace a pagecache page with a new one
788 * @old: page to be replaced
789 * @new: page to replace with
790 * @gfp_mask: allocation mode
791 *
792 * This function replaces a page in the pagecache with a new one. On
793 * success it acquires the pagecache reference for the new page and
794 * drops it for the old page. Both the old and new pages must be
795 * locked. This function does not add the new page to the LRU, the
796 * caller must do that.
797 *
Matthew Wilcox74d60952017-11-17 10:01:45 -0500798 * The remove + add is atomic. This function cannot fail.
Mike Rapoporta862f682019-03-05 15:48:42 -0800799 *
800 * Return: %0
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700801 */
802int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
803{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500804 struct address_space *mapping = old->mapping;
805 void (*freepage)(struct page *) = mapping->a_ops->freepage;
806 pgoff_t offset = old->index;
807 XA_STATE(xas, &mapping->i_pages, offset);
808 unsigned long flags;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700809
Sasha Levin309381fea2014-01-23 15:52:54 -0800810 VM_BUG_ON_PAGE(!PageLocked(old), old);
811 VM_BUG_ON_PAGE(!PageLocked(new), new);
812 VM_BUG_ON_PAGE(new->mapping, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700813
Matthew Wilcox74d60952017-11-17 10:01:45 -0500814 get_page(new);
815 new->mapping = mapping;
816 new->index = offset;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700817
Matthew Wilcox74d60952017-11-17 10:01:45 -0500818 xas_lock_irqsave(&xas, flags);
819 xas_store(&xas, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700820
Matthew Wilcox74d60952017-11-17 10:01:45 -0500821 old->mapping = NULL;
822 /* hugetlb pages do not participate in page cache accounting. */
823 if (!PageHuge(old))
824 __dec_node_page_state(new, NR_FILE_PAGES);
825 if (!PageHuge(new))
826 __inc_node_page_state(new, NR_FILE_PAGES);
827 if (PageSwapBacked(old))
828 __dec_node_page_state(new, NR_SHMEM);
829 if (PageSwapBacked(new))
830 __inc_node_page_state(new, NR_SHMEM);
831 xas_unlock_irqrestore(&xas, flags);
832 mem_cgroup_migrate(old, new);
833 if (freepage)
834 freepage(old);
835 put_page(old);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700836
Matthew Wilcox74d60952017-11-17 10:01:45 -0500837 return 0;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700838}
839EXPORT_SYMBOL_GPL(replace_page_cache_page);
840
Johannes Weinera5289102014-04-03 14:47:51 -0700841static int __add_to_page_cache_locked(struct page *page,
842 struct address_space *mapping,
843 pgoff_t offset, gfp_t gfp_mask,
844 void **shadowp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700845{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500846 XA_STATE(xas, &mapping->i_pages, offset);
Johannes Weiner00501b52014-08-08 14:19:20 -0700847 int huge = PageHuge(page);
848 struct mem_cgroup *memcg;
Nick Piggine2867812008-07-25 19:45:30 -0700849 int error;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500850 void *old;
Nick Piggine2867812008-07-25 19:45:30 -0700851
Sasha Levin309381fea2014-01-23 15:52:54 -0800852 VM_BUG_ON_PAGE(!PageLocked(page), page);
853 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500854 mapping_set_update(&xas, mapping);
Nick Piggine2867812008-07-25 19:45:30 -0700855
Johannes Weiner00501b52014-08-08 14:19:20 -0700856 if (!huge) {
857 error = mem_cgroup_try_charge(page, current->mm,
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800858 gfp_mask, &memcg, false);
Johannes Weiner00501b52014-08-08 14:19:20 -0700859 if (error)
860 return error;
861 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300863 get_page(page);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700864 page->mapping = mapping;
865 page->index = offset;
866
Matthew Wilcox74d60952017-11-17 10:01:45 -0500867 do {
868 xas_lock_irq(&xas);
869 old = xas_load(&xas);
870 if (old && !xa_is_value(old))
871 xas_set_err(&xas, -EEXIST);
872 xas_store(&xas, page);
873 if (xas_error(&xas))
874 goto unlock;
Michal Hocko4165b9b42015-06-24 16:57:24 -0700875
Matthew Wilcox74d60952017-11-17 10:01:45 -0500876 if (xa_is_value(old)) {
877 mapping->nrexceptional--;
878 if (shadowp)
879 *shadowp = old;
880 }
881 mapping->nrpages++;
882
883 /* hugetlb pages do not participate in page cache accounting */
884 if (!huge)
885 __inc_node_page_state(page, NR_FILE_PAGES);
886unlock:
887 xas_unlock_irq(&xas);
888 } while (xas_nomem(&xas, gfp_mask & GFP_RECLAIM_MASK));
889
890 if (xas_error(&xas))
891 goto error;
892
Johannes Weiner00501b52014-08-08 14:19:20 -0700893 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800894 mem_cgroup_commit_charge(page, memcg, false, false);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700895 trace_mm_filemap_add_to_page_cache(page);
896 return 0;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500897error:
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700898 page->mapping = NULL;
899 /* Leave page->index set: truncation relies upon it */
Johannes Weiner00501b52014-08-08 14:19:20 -0700900 if (!huge)
Kirill A. Shutemovf627c2f2016-01-15 16:52:20 -0800901 mem_cgroup_cancel_charge(page, memcg, false);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300902 put_page(page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500903 return xas_error(&xas);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904}
Josef Bacikcfcbfb12019-05-13 17:21:04 -0700905ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
Johannes Weinera5289102014-04-03 14:47:51 -0700906
907/**
908 * add_to_page_cache_locked - add a locked page to the pagecache
909 * @page: page to add
910 * @mapping: the page's address_space
911 * @offset: page index
912 * @gfp_mask: page allocation mode
913 *
914 * This function is used to add a page to the pagecache. It must be locked.
915 * This function does not add the page to the LRU. The caller must do that.
Mike Rapoporta862f682019-03-05 15:48:42 -0800916 *
917 * Return: %0 on success, negative error code otherwise.
Johannes Weinera5289102014-04-03 14:47:51 -0700918 */
919int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
920 pgoff_t offset, gfp_t gfp_mask)
921{
922 return __add_to_page_cache_locked(page, mapping, offset,
923 gfp_mask, NULL);
924}
Nick Piggine2867812008-07-25 19:45:30 -0700925EXPORT_SYMBOL(add_to_page_cache_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700926
927int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
Al Viro6daa0e22005-10-21 03:18:50 -0400928 pgoff_t offset, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700929{
Johannes Weinera5289102014-04-03 14:47:51 -0700930 void *shadow = NULL;
Rik van Riel4f98a2f2008-10-18 20:26:32 -0700931 int ret;
932
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800933 __SetPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700934 ret = __add_to_page_cache_locked(page, mapping, offset,
935 gfp_mask, &shadow);
936 if (unlikely(ret))
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800937 __ClearPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700938 else {
939 /*
940 * The page might have been evicted from cache only
941 * recently, in which case it should be activated like
942 * any other repeatedly accessed page.
Rik van Rielf0281a02016-05-20 16:56:25 -0700943 * The exception is pages getting rewritten; evicting other
944 * data from the working set, only to cache data that will
945 * get overwritten with something else, is a waste of memory.
Johannes Weinera5289102014-04-03 14:47:51 -0700946 */
Johannes Weiner1899ad12018-10-26 15:06:04 -0700947 WARN_ON_ONCE(PageActive(page));
948 if (!(gfp_mask & __GFP_WRITE) && shadow)
949 workingset_refault(page, shadow);
Johannes Weinera5289102014-04-03 14:47:51 -0700950 lru_cache_add(page);
951 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952 return ret;
953}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +0300954EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955
Paul Jackson44110fe2006-03-24 03:16:04 -0800956#ifdef CONFIG_NUMA
Nick Piggin2ae88142006-10-28 10:38:23 -0700957struct page *__page_cache_alloc(gfp_t gfp)
Paul Jackson44110fe2006-03-24 03:16:04 -0800958{
Miao Xiec0ff7452010-05-24 14:32:08 -0700959 int n;
960 struct page *page;
961
Paul Jackson44110fe2006-03-24 03:16:04 -0800962 if (cpuset_do_page_mem_spread()) {
Mel Gormancc9a6c82012-03-21 16:34:11 -0700963 unsigned int cpuset_mems_cookie;
964 do {
Mel Gormand26914d2014-04-03 14:47:24 -0700965 cpuset_mems_cookie = read_mems_allowed_begin();
Mel Gormancc9a6c82012-03-21 16:34:11 -0700966 n = cpuset_mem_spread_node();
Vlastimil Babka96db8002015-09-08 15:03:50 -0700967 page = __alloc_pages_node(n, gfp, 0);
Mel Gormand26914d2014-04-03 14:47:24 -0700968 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
Mel Gormancc9a6c82012-03-21 16:34:11 -0700969
Miao Xiec0ff7452010-05-24 14:32:08 -0700970 return page;
Paul Jackson44110fe2006-03-24 03:16:04 -0800971 }
Nick Piggin2ae88142006-10-28 10:38:23 -0700972 return alloc_pages(gfp, 0);
Paul Jackson44110fe2006-03-24 03:16:04 -0800973}
Nick Piggin2ae88142006-10-28 10:38:23 -0700974EXPORT_SYMBOL(__page_cache_alloc);
Paul Jackson44110fe2006-03-24 03:16:04 -0800975#endif
976
Linus Torvalds1da177e2005-04-16 15:20:36 -0700977/*
978 * In order to wait for pages to become available there must be
979 * waitqueues associated with pages. By using a hash table of
980 * waitqueues where the bucket discipline is to maintain all
981 * waiters on the same queue and wake all when any of the pages
982 * become available, and for the woken contexts to check to be
983 * sure the appropriate page became available, this saves space
984 * at a cost of "thundering herd" phenomena during rare hash
985 * collisions.
986 */
Nicholas Piggin62906022016-12-25 13:00:30 +1000987#define PAGE_WAIT_TABLE_BITS 8
988#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
989static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
990
991static wait_queue_head_t *page_waitqueue(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700992{
Nicholas Piggin62906022016-12-25 13:00:30 +1000993 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
Linus Torvalds1da177e2005-04-16 15:20:36 -0700994}
Nicholas Piggin62906022016-12-25 13:00:30 +1000995
996void __init pagecache_init(void)
997{
998 int i;
999
1000 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1001 init_waitqueue_head(&page_wait_table[i]);
1002
1003 page_writeback_init();
1004}
1005
Linus Torvalds3510ca22017-08-27 13:55:12 -07001006/* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
Nicholas Piggin62906022016-12-25 13:00:30 +10001007struct wait_page_key {
1008 struct page *page;
1009 int bit_nr;
1010 int page_match;
1011};
1012
1013struct wait_page_queue {
1014 struct page *page;
1015 int bit_nr;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001016 wait_queue_entry_t wait;
Nicholas Piggin62906022016-12-25 13:00:30 +10001017};
1018
Ingo Molnarac6424b2017-06-20 12:06:13 +02001019static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
Nicholas Piggin62906022016-12-25 13:00:30 +10001020{
1021 struct wait_page_key *key = arg;
1022 struct wait_page_queue *wait_page
1023 = container_of(wait, struct wait_page_queue, wait);
1024
1025 if (wait_page->page != key->page)
1026 return 0;
1027 key->page_match = 1;
1028
1029 if (wait_page->bit_nr != key->bit_nr)
1030 return 0;
Linus Torvalds3510ca22017-08-27 13:55:12 -07001031
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001032 /*
1033 * Stop walking if it's locked.
1034 * Is this safe if put_and_wait_on_page_locked() is in use?
1035 * Yes: the waker must hold a reference to this page, and if PG_locked
1036 * has now already been set by another task, that task must also hold
1037 * a reference to the *same usage* of this page; so there is no need
1038 * to walk on to wake even the put_and_wait_on_page_locked() callers.
1039 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001040 if (test_bit(key->bit_nr, &key->page->flags))
Linus Torvalds3510ca22017-08-27 13:55:12 -07001041 return -1;
Nicholas Piggin62906022016-12-25 13:00:30 +10001042
1043 return autoremove_wake_function(wait, mode, sync, key);
1044}
1045
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001046static void wake_up_page_bit(struct page *page, int bit_nr)
Nicholas Piggin62906022016-12-25 13:00:30 +10001047{
1048 wait_queue_head_t *q = page_waitqueue(page);
1049 struct wait_page_key key;
1050 unsigned long flags;
Tim Chen11a19c72017-08-25 09:13:55 -07001051 wait_queue_entry_t bookmark;
Nicholas Piggin62906022016-12-25 13:00:30 +10001052
1053 key.page = page;
1054 key.bit_nr = bit_nr;
1055 key.page_match = 0;
1056
Tim Chen11a19c72017-08-25 09:13:55 -07001057 bookmark.flags = 0;
1058 bookmark.private = NULL;
1059 bookmark.func = NULL;
1060 INIT_LIST_HEAD(&bookmark.entry);
1061
Nicholas Piggin62906022016-12-25 13:00:30 +10001062 spin_lock_irqsave(&q->lock, flags);
Tim Chen11a19c72017-08-25 09:13:55 -07001063 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1064
1065 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1066 /*
1067 * Take a breather from holding the lock,
1068 * allow pages that finish wake up asynchronously
1069 * to acquire the lock and remove themselves
1070 * from wait queue
1071 */
1072 spin_unlock_irqrestore(&q->lock, flags);
1073 cpu_relax();
1074 spin_lock_irqsave(&q->lock, flags);
1075 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1076 }
1077
Nicholas Piggin62906022016-12-25 13:00:30 +10001078 /*
1079 * It is possible for other pages to have collided on the waitqueue
1080 * hash, so in that case check for a page match. That prevents a long-
1081 * term waiter
1082 *
1083 * It is still possible to miss a case here, when we woke page waiters
1084 * and removed them from the waitqueue, but there are still other
1085 * page waiters.
1086 */
1087 if (!waitqueue_active(q) || !key.page_match) {
1088 ClearPageWaiters(page);
1089 /*
1090 * It's possible to miss clearing Waiters here, when we woke
1091 * our page waiters, but the hashed waitqueue has waiters for
1092 * other pages on it.
1093 *
1094 * That's okay, it's a rare case. The next waker will clear it.
1095 */
1096 }
1097 spin_unlock_irqrestore(&q->lock, flags);
1098}
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001099
1100static void wake_up_page(struct page *page, int bit)
1101{
1102 if (!PageWaiters(page))
1103 return;
1104 wake_up_page_bit(page, bit);
1105}
Nicholas Piggin62906022016-12-25 13:00:30 +10001106
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001107/*
1108 * A choice of three behaviors for wait_on_page_bit_common():
1109 */
1110enum behavior {
1111 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1112 * __lock_page() waiting on then setting PG_locked.
1113 */
1114 SHARED, /* Hold ref to page and check the bit when woken, like
1115 * wait_on_page_writeback() waiting on PG_writeback.
1116 */
1117 DROP, /* Drop ref to page before wait, no check when woken,
1118 * like put_and_wait_on_page_locked() on PG_locked.
1119 */
1120};
1121
Nicholas Piggin62906022016-12-25 13:00:30 +10001122static inline int wait_on_page_bit_common(wait_queue_head_t *q,
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001123 struct page *page, int bit_nr, int state, enum behavior behavior)
Nicholas Piggin62906022016-12-25 13:00:30 +10001124{
1125 struct wait_page_queue wait_page;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001126 wait_queue_entry_t *wait = &wait_page.wait;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001127 bool bit_is_set;
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001128 bool thrashing = false;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001129 bool delayacct = false;
Johannes Weinereb414682018-10-26 15:06:27 -07001130 unsigned long pflags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001131 int ret = 0;
1132
Johannes Weinereb414682018-10-26 15:06:27 -07001133 if (bit_nr == PG_locked &&
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001134 !PageUptodate(page) && PageWorkingset(page)) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001135 if (!PageSwapBacked(page)) {
Johannes Weinereb414682018-10-26 15:06:27 -07001136 delayacct_thrashing_start();
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001137 delayacct = true;
1138 }
Johannes Weinereb414682018-10-26 15:06:27 -07001139 psi_memstall_enter(&pflags);
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001140 thrashing = true;
1141 }
1142
Nicholas Piggin62906022016-12-25 13:00:30 +10001143 init_wait(wait);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001144 wait->flags = behavior == EXCLUSIVE ? WQ_FLAG_EXCLUSIVE : 0;
Nicholas Piggin62906022016-12-25 13:00:30 +10001145 wait->func = wake_page_function;
1146 wait_page.page = page;
1147 wait_page.bit_nr = bit_nr;
1148
1149 for (;;) {
1150 spin_lock_irq(&q->lock);
1151
Ingo Molnar2055da92017-06-20 12:06:46 +02001152 if (likely(list_empty(&wait->entry))) {
Linus Torvalds3510ca22017-08-27 13:55:12 -07001153 __add_wait_queue_entry_tail(q, wait);
Nicholas Piggin62906022016-12-25 13:00:30 +10001154 SetPageWaiters(page);
1155 }
1156
1157 set_current_state(state);
1158
1159 spin_unlock_irq(&q->lock);
1160
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001161 bit_is_set = test_bit(bit_nr, &page->flags);
1162 if (behavior == DROP)
1163 put_page(page);
Nicholas Piggin62906022016-12-25 13:00:30 +10001164
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001165 if (likely(bit_is_set))
1166 io_schedule();
1167
1168 if (behavior == EXCLUSIVE) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001169 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1170 break;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001171 } else if (behavior == SHARED) {
Nicholas Piggin62906022016-12-25 13:00:30 +10001172 if (!test_bit(bit_nr, &page->flags))
1173 break;
1174 }
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001175
Davidlohr Buesofa45f112019-01-03 15:28:55 -08001176 if (signal_pending_state(state, current)) {
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001177 ret = -EINTR;
1178 break;
1179 }
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001180
1181 if (behavior == DROP) {
1182 /*
1183 * We can no longer safely access page->flags:
1184 * even if CONFIG_MEMORY_HOTREMOVE is not enabled,
1185 * there is a risk of waiting forever on a page reused
1186 * for something that keeps it locked indefinitely.
1187 * But best check for -EINTR above before breaking.
1188 */
1189 break;
1190 }
Nicholas Piggin62906022016-12-25 13:00:30 +10001191 }
1192
1193 finish_wait(q, wait);
1194
Johannes Weinereb414682018-10-26 15:06:27 -07001195 if (thrashing) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001196 if (delayacct)
Johannes Weinereb414682018-10-26 15:06:27 -07001197 delayacct_thrashing_end();
1198 psi_memstall_leave(&pflags);
1199 }
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001200
Nicholas Piggin62906022016-12-25 13:00:30 +10001201 /*
1202 * A signal could leave PageWaiters set. Clearing it here if
1203 * !waitqueue_active would be possible (by open-coding finish_wait),
1204 * but still fail to catch it in the case of wait hash collision. We
1205 * already can fail to clear wait hash collision cases, so don't
1206 * bother with signals either.
1207 */
1208
1209 return ret;
1210}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001211
Harvey Harrison920c7a52008-02-04 22:29:26 -08001212void wait_on_page_bit(struct page *page, int bit_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001213{
Nicholas Piggin62906022016-12-25 13:00:30 +10001214 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001215 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001216}
1217EXPORT_SYMBOL(wait_on_page_bit);
1218
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001219int wait_on_page_bit_killable(struct page *page, int bit_nr)
1220{
Nicholas Piggin62906022016-12-25 13:00:30 +10001221 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001222 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001223}
David Howells4343d002017-11-02 15:27:52 +00001224EXPORT_SYMBOL(wait_on_page_bit_killable);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001225
Linus Torvalds1da177e2005-04-16 15:20:36 -07001226/**
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001227 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1228 * @page: The page to wait for.
1229 *
1230 * The caller should hold a reference on @page. They expect the page to
1231 * become unlocked relatively soon, but do not wish to hold up migration
1232 * (for example) by holding the reference while waiting for the page to
1233 * come unlocked. After this function returns, the caller should not
1234 * dereference @page.
1235 */
1236void put_and_wait_on_page_locked(struct page *page)
1237{
1238 wait_queue_head_t *q;
1239
1240 page = compound_head(page);
1241 q = page_waitqueue(page);
1242 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, DROP);
1243}
1244
1245/**
David Howells385e1ca5f2009-04-03 16:42:39 +01001246 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
Randy Dunlap697f6192009-04-13 14:39:54 -07001247 * @page: Page defining the wait queue of interest
1248 * @waiter: Waiter to add to the queue
David Howells385e1ca5f2009-04-03 16:42:39 +01001249 *
1250 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1251 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001252void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
David Howells385e1ca5f2009-04-03 16:42:39 +01001253{
1254 wait_queue_head_t *q = page_waitqueue(page);
1255 unsigned long flags;
1256
1257 spin_lock_irqsave(&q->lock, flags);
Linus Torvalds9c3a8152017-08-28 16:45:40 -07001258 __add_wait_queue_entry_tail(q, waiter);
Nicholas Piggin62906022016-12-25 13:00:30 +10001259 SetPageWaiters(page);
David Howells385e1ca5f2009-04-03 16:42:39 +01001260 spin_unlock_irqrestore(&q->lock, flags);
1261}
1262EXPORT_SYMBOL_GPL(add_page_wait_queue);
1263
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001264#ifndef clear_bit_unlock_is_negative_byte
1265
1266/*
1267 * PG_waiters is the high bit in the same byte as PG_lock.
1268 *
1269 * On x86 (and on many other architectures), we can clear PG_lock and
1270 * test the sign bit at the same time. But if the architecture does
1271 * not support that special operation, we just do this all by hand
1272 * instead.
1273 *
1274 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1275 * being cleared, but a memory barrier should be unneccssary since it is
1276 * in the same byte as PG_locked.
1277 */
1278static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1279{
1280 clear_bit_unlock(nr, mem);
1281 /* smp_mb__after_atomic(); */
Olof Johansson98473f92016-12-29 14:16:07 -08001282 return test_bit(PG_waiters, mem);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001283}
1284
1285#endif
1286
David Howells385e1ca5f2009-04-03 16:42:39 +01001287/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001288 * unlock_page - unlock a locked page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001289 * @page: the page
1290 *
1291 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1292 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
Masanari Iidada3dae52014-09-09 01:27:23 +09001293 * mechanism between PageLocked pages and PageWriteback pages is shared.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001294 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1295 *
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001296 * Note that this depends on PG_waiters being the sign bit in the byte
1297 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1298 * clear the PG_locked bit and test PG_waiters at the same time fairly
1299 * portably (architectures that do LL/SC can test any bit, while x86 can
1300 * test the sign bit).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001301 */
Harvey Harrison920c7a52008-02-04 22:29:26 -08001302void unlock_page(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001303{
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001304 BUILD_BUG_ON(PG_waiters != 7);
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -08001305 page = compound_head(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001306 VM_BUG_ON_PAGE(!PageLocked(page), page);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001307 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1308 wake_up_page_bit(page, PG_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001309}
1310EXPORT_SYMBOL(unlock_page);
1311
Randy Dunlap485bb992006-06-23 02:03:49 -07001312/**
1313 * end_page_writeback - end writeback against a page
1314 * @page: the page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001315 */
1316void end_page_writeback(struct page *page)
1317{
Mel Gorman888cf2d2014-06-04 16:10:34 -07001318 /*
1319 * TestClearPageReclaim could be used here but it is an atomic
1320 * operation and overkill in this particular case. Failing to
1321 * shuffle a page marked for immediate reclaim is too mild to
1322 * justify taking an atomic operation penalty at the end of
1323 * ever page writeback.
1324 */
1325 if (PageReclaim(page)) {
1326 ClearPageReclaim(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001327 rotate_reclaimable_page(page);
Mel Gorman888cf2d2014-06-04 16:10:34 -07001328 }
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001329
1330 if (!test_clear_page_writeback(page))
1331 BUG();
1332
Peter Zijlstra4e857c52014-03-17 18:06:10 +01001333 smp_mb__after_atomic();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001334 wake_up_page(page, PG_writeback);
1335}
1336EXPORT_SYMBOL(end_page_writeback);
1337
Matthew Wilcox57d99842014-06-04 16:07:45 -07001338/*
1339 * After completing I/O on a page, call this routine to update the page
1340 * flags appropriately
1341 */
Jens Axboec11f0c02016-08-05 08:11:04 -06001342void page_endio(struct page *page, bool is_write, int err)
Matthew Wilcox57d99842014-06-04 16:07:45 -07001343{
Jens Axboec11f0c02016-08-05 08:11:04 -06001344 if (!is_write) {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001345 if (!err) {
1346 SetPageUptodate(page);
1347 } else {
1348 ClearPageUptodate(page);
1349 SetPageError(page);
1350 }
1351 unlock_page(page);
Mike Christieabf54542016-08-04 14:23:34 -06001352 } else {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001353 if (err) {
Minchan Kimdd8416c2017-02-24 14:59:59 -08001354 struct address_space *mapping;
1355
Matthew Wilcox57d99842014-06-04 16:07:45 -07001356 SetPageError(page);
Minchan Kimdd8416c2017-02-24 14:59:59 -08001357 mapping = page_mapping(page);
1358 if (mapping)
1359 mapping_set_error(mapping, err);
Matthew Wilcox57d99842014-06-04 16:07:45 -07001360 }
1361 end_page_writeback(page);
1362 }
1363}
1364EXPORT_SYMBOL_GPL(page_endio);
1365
Randy Dunlap485bb992006-06-23 02:03:49 -07001366/**
1367 * __lock_page - get a lock on the page, assuming we need to sleep to get it
Randy Dunlap87066752017-02-22 15:44:44 -08001368 * @__page: the page to lock
Linus Torvalds1da177e2005-04-16 15:20:36 -07001369 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001370void __lock_page(struct page *__page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001371{
Nicholas Piggin62906022016-12-25 13:00:30 +10001372 struct page *page = compound_head(__page);
1373 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001374 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1375 EXCLUSIVE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001376}
1377EXPORT_SYMBOL(__lock_page);
1378
Nicholas Piggin62906022016-12-25 13:00:30 +10001379int __lock_page_killable(struct page *__page)
Matthew Wilcox2687a352007-12-06 11:18:49 -05001380{
Nicholas Piggin62906022016-12-25 13:00:30 +10001381 struct page *page = compound_head(__page);
1382 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001383 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1384 EXCLUSIVE);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001385}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +03001386EXPORT_SYMBOL_GPL(__lock_page_killable);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001387
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001388/*
1389 * Return values:
1390 * 1 - page is locked; mmap_sem is still held.
1391 * 0 - page is not locked.
1392 * mmap_sem has been released (up_read()), unless flags had both
1393 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1394 * which case mmap_sem is still held.
1395 *
1396 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1397 * with the page locked and the mmap_sem unperturbed.
1398 */
Michel Lespinassed065bd82010-10-26 14:21:57 -07001399int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1400 unsigned int flags)
1401{
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001402 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1403 /*
1404 * CAUTION! In this case, mmap_sem is not released
1405 * even though return 0.
1406 */
1407 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1408 return 0;
1409
1410 up_read(&mm->mmap_sem);
1411 if (flags & FAULT_FLAG_KILLABLE)
1412 wait_on_page_locked_killable(page);
1413 else
Gleb Natapov318b2752011-03-22 16:30:51 -07001414 wait_on_page_locked(page);
Michel Lespinassed065bd82010-10-26 14:21:57 -07001415 return 0;
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001416 } else {
1417 if (flags & FAULT_FLAG_KILLABLE) {
1418 int ret;
1419
1420 ret = __lock_page_killable(page);
1421 if (ret) {
1422 up_read(&mm->mmap_sem);
1423 return 0;
1424 }
1425 } else
1426 __lock_page(page);
1427 return 1;
Michel Lespinassed065bd82010-10-26 14:21:57 -07001428 }
1429}
1430
Randy Dunlap485bb992006-06-23 02:03:49 -07001431/**
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001432 * page_cache_next_miss() - Find the next gap in the page cache.
1433 * @mapping: Mapping.
1434 * @index: Index.
1435 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001436 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001437 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1438 * gap with the lowest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001439 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001440 * This function may be called under the rcu_read_lock. However, this will
1441 * not atomically search a snapshot of the cache at a single point in time.
1442 * For example, if a gap is created at index 5, then subsequently a gap is
1443 * created at index 10, page_cache_next_miss covering both indices may
1444 * return 10 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001445 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001446 * Return: The index of the gap if found, otherwise an index outside the
1447 * range specified (in which case 'return - index >= max_scan' will be true).
1448 * In the rare case of index wrap-around, 0 will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001449 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001450pgoff_t page_cache_next_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001451 pgoff_t index, unsigned long max_scan)
1452{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001453 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001454
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001455 while (max_scan--) {
1456 void *entry = xas_next(&xas);
1457 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001458 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001459 if (xas.xa_index == 0)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001460 break;
1461 }
1462
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001463 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001464}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001465EXPORT_SYMBOL(page_cache_next_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001466
1467/**
Laurent Dufour2346a562019-05-13 17:21:29 -07001468 * page_cache_prev_miss() - Find the previous gap in the page cache.
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001469 * @mapping: Mapping.
1470 * @index: Index.
1471 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001472 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001473 * Search the range [max(index - max_scan + 1, 0), index] for the
1474 * gap with the highest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001475 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001476 * This function may be called under the rcu_read_lock. However, this will
1477 * not atomically search a snapshot of the cache at a single point in time.
1478 * For example, if a gap is created at index 10, then subsequently a gap is
1479 * created at index 5, page_cache_prev_miss() covering both indices may
1480 * return 5 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001481 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001482 * Return: The index of the gap if found, otherwise an index outside the
1483 * range specified (in which case 'index - return >= max_scan' will be true).
1484 * In the rare case of wrap-around, ULONG_MAX will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001485 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001486pgoff_t page_cache_prev_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001487 pgoff_t index, unsigned long max_scan)
1488{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001489 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001490
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001491 while (max_scan--) {
1492 void *entry = xas_prev(&xas);
1493 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001494 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001495 if (xas.xa_index == ULONG_MAX)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001496 break;
1497 }
1498
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001499 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001500}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001501EXPORT_SYMBOL(page_cache_prev_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001502
1503/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001504 * find_get_entry - find and get a page cache entry
Randy Dunlap485bb992006-06-23 02:03:49 -07001505 * @mapping: the address_space to search
Johannes Weiner0cd61442014-04-03 14:47:46 -07001506 * @offset: the page cache index
Randy Dunlap485bb992006-06-23 02:03:49 -07001507 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001508 * Looks up the page cache slot at @mapping & @offset. If there is a
1509 * page cache page, it is returned with an increased refcount.
1510 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001511 * If the slot holds a shadow entry of a previously evicted page, or a
1512 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001513 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001514 * Return: the found page or shadow entry, %NULL if nothing is found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001515 */
Johannes Weiner0cd61442014-04-03 14:47:46 -07001516struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001517{
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001518 XA_STATE(xas, &mapping->i_pages, offset);
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001519 struct page *head, *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001520
Nick Piggina60637c2008-07-25 19:45:31 -07001521 rcu_read_lock();
1522repeat:
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001523 xas_reset(&xas);
1524 page = xas_load(&xas);
1525 if (xas_retry(&xas, page))
1526 goto repeat;
1527 /*
1528 * A shadow entry of a recently evicted page, or a swap entry from
1529 * shmem/tmpfs. Return it without attempting to raise page count.
1530 */
1531 if (!page || xa_is_value(page))
1532 goto out;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001533
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001534 head = compound_head(page);
1535 if (!page_cache_get_speculative(head))
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001536 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001537
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001538 /* The page was split under us? */
1539 if (compound_head(page) != head) {
1540 put_page(head);
1541 goto repeat;
1542 }
1543
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001544 /*
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001545 * Has the page moved?
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001546 * This is part of the lockless pagecache protocol. See
1547 * include/linux/pagemap.h for details.
1548 */
1549 if (unlikely(page != xas_reload(&xas))) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001550 put_page(head);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001551 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001552 }
Nick Piggin27d20fd2010-11-11 14:05:19 -08001553out:
Nick Piggina60637c2008-07-25 19:45:31 -07001554 rcu_read_unlock();
1555
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556 return page;
1557}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001558EXPORT_SYMBOL(find_get_entry);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001559
Randy Dunlap485bb992006-06-23 02:03:49 -07001560/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001561 * find_lock_entry - locate, pin and lock a page cache entry
1562 * @mapping: the address_space to search
1563 * @offset: the page cache index
1564 *
1565 * Looks up the page cache slot at @mapping & @offset. If there is a
1566 * page cache page, it is returned locked and with an increased
1567 * refcount.
1568 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001569 * If the slot holds a shadow entry of a previously evicted page, or a
1570 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001571 *
Johannes Weiner0cd61442014-04-03 14:47:46 -07001572 * find_lock_entry() may sleep.
Mike Rapoporta862f682019-03-05 15:48:42 -08001573 *
1574 * Return: the found page or shadow entry, %NULL if nothing is found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001575 */
1576struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577{
1578 struct page *page;
1579
Linus Torvalds1da177e2005-04-16 15:20:36 -07001580repeat:
Johannes Weiner0cd61442014-04-03 14:47:46 -07001581 page = find_get_entry(mapping, offset);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001582 if (page && !xa_is_value(page)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001583 lock_page(page);
1584 /* Has the page been truncated? */
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001585 if (unlikely(page_mapping(page) != mapping)) {
Nick Piggina60637c2008-07-25 19:45:31 -07001586 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001587 put_page(page);
Nick Piggina60637c2008-07-25 19:45:31 -07001588 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001589 }
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001590 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001591 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001592 return page;
1593}
Johannes Weiner0cd61442014-04-03 14:47:46 -07001594EXPORT_SYMBOL(find_lock_entry);
1595
1596/**
Mel Gorman2457aec2014-06-04 16:10:31 -07001597 * pagecache_get_page - find and get a page reference
Johannes Weiner0cd61442014-04-03 14:47:46 -07001598 * @mapping: the address_space to search
1599 * @offset: the page index
Mel Gorman2457aec2014-06-04 16:10:31 -07001600 * @fgp_flags: PCG flags
Michal Hocko45f87de2014-12-29 20:30:35 +01001601 * @gfp_mask: gfp mask to use for the page cache data page allocation
Johannes Weiner0cd61442014-04-03 14:47:46 -07001602 *
Mel Gorman2457aec2014-06-04 16:10:31 -07001603 * Looks up the page cache slot at @mapping & @offset.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001604 *
Randy Dunlap75325182014-07-30 16:08:37 -07001605 * PCG flags modify how the page is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001606 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -03001607 * @fgp_flags can be:
1608 *
1609 * - FGP_ACCESSED: the page will be marked accessed
1610 * - FGP_LOCK: Page is return locked
1611 * - FGP_CREAT: If page is not present then a new page is allocated using
1612 * @gfp_mask and added to the page cache and the VM's LRU
1613 * list. The page is returned locked and with an increased
Mike Rapoporta862f682019-03-05 15:48:42 -08001614 * refcount.
Josef Bacika75d4c32019-03-13 11:44:14 -07001615 * - FGP_FOR_MMAP: Similar to FGP_CREAT, only we want to allow the caller to do
1616 * its own locking dance if the page is already in cache, or unlock the page
1617 * before returning if we had to add the page to pagecache.
Mel Gorman2457aec2014-06-04 16:10:31 -07001618 *
1619 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1620 * if the GFP flags specified for FGP_CREAT are atomic.
1621 *
1622 * If there is a page cache page, it is returned with an increased refcount.
Mike Rapoporta862f682019-03-05 15:48:42 -08001623 *
1624 * Return: the found page or %NULL otherwise.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001625 */
Mel Gorman2457aec2014-06-04 16:10:31 -07001626struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
Michal Hocko45f87de2014-12-29 20:30:35 +01001627 int fgp_flags, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001628{
Nick Piggineb2be182007-10-16 01:24:57 -07001629 struct page *page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001630
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631repeat:
Mel Gorman2457aec2014-06-04 16:10:31 -07001632 page = find_get_entry(mapping, offset);
Matthew Wilcox3159f942017-11-03 13:30:42 -04001633 if (xa_is_value(page))
Mel Gorman2457aec2014-06-04 16:10:31 -07001634 page = NULL;
1635 if (!page)
1636 goto no_page;
1637
1638 if (fgp_flags & FGP_LOCK) {
1639 if (fgp_flags & FGP_NOWAIT) {
1640 if (!trylock_page(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001641 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001642 return NULL;
1643 }
1644 } else {
1645 lock_page(page);
1646 }
1647
1648 /* Has the page been truncated? */
1649 if (unlikely(page->mapping != mapping)) {
1650 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001651 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001652 goto repeat;
1653 }
1654 VM_BUG_ON_PAGE(page->index != offset, page);
1655 }
1656
Kirill Tkhaic16eb002018-12-28 00:37:35 -08001657 if (fgp_flags & FGP_ACCESSED)
Mel Gorman2457aec2014-06-04 16:10:31 -07001658 mark_page_accessed(page);
1659
1660no_page:
1661 if (!page && (fgp_flags & FGP_CREAT)) {
1662 int err;
1663 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
Michal Hocko45f87de2014-12-29 20:30:35 +01001664 gfp_mask |= __GFP_WRITE;
1665 if (fgp_flags & FGP_NOFS)
1666 gfp_mask &= ~__GFP_FS;
Mel Gorman2457aec2014-06-04 16:10:31 -07001667
Michal Hocko45f87de2014-12-29 20:30:35 +01001668 page = __page_cache_alloc(gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001669 if (!page)
1670 return NULL;
Mel Gorman2457aec2014-06-04 16:10:31 -07001671
Josef Bacika75d4c32019-03-13 11:44:14 -07001672 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
Mel Gorman2457aec2014-06-04 16:10:31 -07001673 fgp_flags |= FGP_LOCK;
1674
Hugh Dickinseb39d612014-08-06 16:06:43 -07001675 /* Init accessed so avoid atomic mark_page_accessed later */
Mel Gorman2457aec2014-06-04 16:10:31 -07001676 if (fgp_flags & FGP_ACCESSED)
Hugh Dickinseb39d612014-08-06 16:06:43 -07001677 __SetPageReferenced(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001678
Matthew Wilcoxabc1be12018-04-20 14:56:20 -07001679 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001680 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001681 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07001682 page = NULL;
1683 if (err == -EEXIST)
1684 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 }
Josef Bacika75d4c32019-03-13 11:44:14 -07001686
1687 /*
1688 * add_to_page_cache_lru locks the page, and for mmap we expect
1689 * an unlocked page.
1690 */
1691 if (page && (fgp_flags & FGP_FOR_MMAP))
1692 unlock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001693 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001694
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 return page;
1696}
Mel Gorman2457aec2014-06-04 16:10:31 -07001697EXPORT_SYMBOL(pagecache_get_page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001698
1699/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001700 * find_get_entries - gang pagecache lookup
1701 * @mapping: The address_space to search
1702 * @start: The starting page cache index
1703 * @nr_entries: The maximum number of entries
1704 * @entries: Where the resulting entries are placed
1705 * @indices: The cache indices corresponding to the entries in @entries
1706 *
1707 * find_get_entries() will search for and return a group of up to
1708 * @nr_entries entries in the mapping. The entries are placed at
1709 * @entries. find_get_entries() takes a reference against any actual
1710 * pages it returns.
1711 *
1712 * The search returns a group of mapping-contiguous page cache entries
1713 * with ascending indexes. There may be holes in the indices due to
1714 * not-present pages.
1715 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001716 * Any shadow entries of evicted pages, or swap entries from
1717 * shmem/tmpfs, are included in the returned array.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001718 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001719 * Return: the number of pages and shadow entries which were found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001720 */
1721unsigned find_get_entries(struct address_space *mapping,
1722 pgoff_t start, unsigned int nr_entries,
1723 struct page **entries, pgoff_t *indices)
1724{
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001725 XA_STATE(xas, &mapping->i_pages, start);
1726 struct page *page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001727 unsigned int ret = 0;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001728
1729 if (!nr_entries)
1730 return 0;
1731
1732 rcu_read_lock();
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001733 xas_for_each(&xas, page, ULONG_MAX) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001734 struct page *head;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001735 if (xas_retry(&xas, page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001736 continue;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001737 /*
1738 * A shadow entry of a recently evicted page, a swap
1739 * entry from shmem/tmpfs or a DAX entry. Return it
1740 * without attempting to raise page count.
1741 */
1742 if (xa_is_value(page))
Johannes Weiner0cd61442014-04-03 14:47:46 -07001743 goto export;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001744
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001745 head = compound_head(page);
1746 if (!page_cache_get_speculative(head))
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001747 goto retry;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001748
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001749 /* The page was split under us? */
1750 if (compound_head(page) != head)
1751 goto put_page;
1752
1753 /* Has the page moved? */
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001754 if (unlikely(page != xas_reload(&xas)))
1755 goto put_page;
1756
Johannes Weiner0cd61442014-04-03 14:47:46 -07001757export:
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001758 indices[ret] = xas.xa_index;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001759 entries[ret] = page;
1760 if (++ret == nr_entries)
1761 break;
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001762 continue;
1763put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001764 put_page(head);
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001765retry:
1766 xas_reset(&xas);
Johannes Weiner0cd61442014-04-03 14:47:46 -07001767 }
1768 rcu_read_unlock();
1769 return ret;
1770}
1771
1772/**
Jan Karab947cee2017-09-06 16:21:21 -07001773 * find_get_pages_range - gang pagecache lookup
Linus Torvalds1da177e2005-04-16 15:20:36 -07001774 * @mapping: The address_space to search
1775 * @start: The starting page index
Jan Karab947cee2017-09-06 16:21:21 -07001776 * @end: The final page index (inclusive)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001777 * @nr_pages: The maximum number of pages
1778 * @pages: Where the resulting pages are placed
1779 *
Jan Karab947cee2017-09-06 16:21:21 -07001780 * find_get_pages_range() will search for and return a group of up to @nr_pages
1781 * pages in the mapping starting at index @start and up to index @end
1782 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1783 * a reference against the returned pages.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001784 *
1785 * The search returns a group of mapping-contiguous pages with ascending
1786 * indexes. There may be holes in the indices due to not-present pages.
Jan Karad72dc8a2017-09-06 16:21:18 -07001787 * We also update @start to index the next page for the traversal.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001788 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001789 * Return: the number of pages which were found. If this number is
1790 * smaller than @nr_pages, the end of specified range has been
Jan Karab947cee2017-09-06 16:21:21 -07001791 * reached.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001792 */
Jan Karab947cee2017-09-06 16:21:21 -07001793unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1794 pgoff_t end, unsigned int nr_pages,
1795 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001796{
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001797 XA_STATE(xas, &mapping->i_pages, *start);
1798 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001799 unsigned ret = 0;
1800
1801 if (unlikely(!nr_pages))
1802 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001803
Nick Piggina60637c2008-07-25 19:45:31 -07001804 rcu_read_lock();
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001805 xas_for_each(&xas, page, end) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001806 struct page *head;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001807 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001808 continue;
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001809 /* Skip over shadow, swap and DAX entries */
1810 if (xa_is_value(page))
Hugh Dickins8079b1c2011-08-03 16:21:28 -07001811 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001812
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001813 head = compound_head(page);
1814 if (!page_cache_get_speculative(head))
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001815 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001816
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001817 /* The page was split under us? */
1818 if (compound_head(page) != head)
1819 goto put_page;
1820
1821 /* Has the page moved? */
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001822 if (unlikely(page != xas_reload(&xas)))
1823 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001824
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001825 pages[ret] = page;
Jan Karab947cee2017-09-06 16:21:21 -07001826 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001827 *start = xas.xa_index + 1;
Jan Karab947cee2017-09-06 16:21:21 -07001828 goto out;
1829 }
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001830 continue;
1831put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001832 put_page(head);
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001833retry:
1834 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001835 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001836
Jan Karab947cee2017-09-06 16:21:21 -07001837 /*
1838 * We come here when there is no page beyond @end. We take care to not
1839 * overflow the index @start as it confuses some of the callers. This
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04001840 * breaks the iteration when there is a page at index -1 but that is
Jan Karab947cee2017-09-06 16:21:21 -07001841 * already broken anyway.
1842 */
1843 if (end == (pgoff_t)-1)
1844 *start = (pgoff_t)-1;
1845 else
1846 *start = end + 1;
1847out:
Nick Piggina60637c2008-07-25 19:45:31 -07001848 rcu_read_unlock();
Jan Karad72dc8a2017-09-06 16:21:18 -07001849
Linus Torvalds1da177e2005-04-16 15:20:36 -07001850 return ret;
1851}
1852
Jens Axboeebf43502006-04-27 08:46:01 +02001853/**
1854 * find_get_pages_contig - gang contiguous pagecache lookup
1855 * @mapping: The address_space to search
1856 * @index: The starting page index
1857 * @nr_pages: The maximum number of pages
1858 * @pages: Where the resulting pages are placed
1859 *
1860 * find_get_pages_contig() works exactly like find_get_pages(), except
1861 * that the returned number of pages are guaranteed to be contiguous.
1862 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001863 * Return: the number of pages which were found.
Jens Axboeebf43502006-04-27 08:46:01 +02001864 */
1865unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1866 unsigned int nr_pages, struct page **pages)
1867{
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001868 XA_STATE(xas, &mapping->i_pages, index);
1869 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001870 unsigned int ret = 0;
1871
1872 if (unlikely(!nr_pages))
1873 return 0;
Jens Axboeebf43502006-04-27 08:46:01 +02001874
Nick Piggina60637c2008-07-25 19:45:31 -07001875 rcu_read_lock();
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001876 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001877 struct page *head;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001878 if (xas_retry(&xas, page))
1879 continue;
1880 /*
1881 * If the entry has been swapped out, we can stop looking.
1882 * No current caller is looking for DAX entries.
1883 */
1884 if (xa_is_value(page))
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001885 break;
Hugh Dickins9d8aa4e2011-03-22 16:33:06 -07001886
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001887 head = compound_head(page);
1888 if (!page_cache_get_speculative(head))
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001889 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001890
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001891 /* The page was split under us? */
1892 if (compound_head(page) != head)
1893 goto put_page;
1894
1895 /* Has the page moved? */
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001896 if (unlikely(page != xas_reload(&xas)))
1897 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001898
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001899 pages[ret] = page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001900 if (++ret == nr_pages)
1901 break;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001902 continue;
1903put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001904 put_page(head);
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04001905retry:
1906 xas_reset(&xas);
Jens Axboeebf43502006-04-27 08:46:01 +02001907 }
Nick Piggina60637c2008-07-25 19:45:31 -07001908 rcu_read_unlock();
1909 return ret;
Jens Axboeebf43502006-04-27 08:46:01 +02001910}
David Howellsef71c152007-05-09 02:33:44 -07001911EXPORT_SYMBOL(find_get_pages_contig);
Jens Axboeebf43502006-04-27 08:46:01 +02001912
Randy Dunlap485bb992006-06-23 02:03:49 -07001913/**
Jan Kara72b045a2017-11-15 17:34:33 -08001914 * find_get_pages_range_tag - find and return pages in given range matching @tag
Randy Dunlap485bb992006-06-23 02:03:49 -07001915 * @mapping: the address_space to search
1916 * @index: the starting page index
Jan Kara72b045a2017-11-15 17:34:33 -08001917 * @end: The final page index (inclusive)
Randy Dunlap485bb992006-06-23 02:03:49 -07001918 * @tag: the tag index
1919 * @nr_pages: the maximum number of pages
1920 * @pages: where the resulting pages are placed
1921 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001922 * Like find_get_pages, except we only return pages which are tagged with
Randy Dunlap485bb992006-06-23 02:03:49 -07001923 * @tag. We update @index to index the next page for the traversal.
Mike Rapoporta862f682019-03-05 15:48:42 -08001924 *
1925 * Return: the number of pages which were found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001926 */
Jan Kara72b045a2017-11-15 17:34:33 -08001927unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001928 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
Jan Kara72b045a2017-11-15 17:34:33 -08001929 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001930{
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001931 XA_STATE(xas, &mapping->i_pages, *index);
1932 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07001933 unsigned ret = 0;
1934
1935 if (unlikely(!nr_pages))
1936 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001937
Nick Piggina60637c2008-07-25 19:45:31 -07001938 rcu_read_lock();
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001939 xas_for_each_marked(&xas, page, end, tag) {
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001940 struct page *head;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001941 if (xas_retry(&xas, page))
Nick Piggina60637c2008-07-25 19:45:31 -07001942 continue;
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001943 /*
1944 * Shadow entries should never be tagged, but this iteration
1945 * is lockless so there is a window for page reclaim to evict
1946 * a page we saw tagged. Skip over it.
1947 */
1948 if (xa_is_value(page))
Johannes Weiner139b6a62014-05-06 12:50:05 -07001949 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07001950
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001951 head = compound_head(page);
1952 if (!page_cache_get_speculative(head))
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001953 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07001954
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001955 /* The page was split under us? */
1956 if (compound_head(page) != head)
1957 goto put_page;
1958
1959 /* Has the page moved? */
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001960 if (unlikely(page != xas_reload(&xas)))
1961 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07001962
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001963 pages[ret] = page;
Jan Kara72b045a2017-11-15 17:34:33 -08001964 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08001965 *index = xas.xa_index + 1;
Jan Kara72b045a2017-11-15 17:34:33 -08001966 goto out;
1967 }
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001968 continue;
1969put_page:
Linus Torvalds69bf4b62019-07-05 19:55:18 -07001970 put_page(head);
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001971retry:
1972 xas_reset(&xas);
Nick Piggina60637c2008-07-25 19:45:31 -07001973 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07001974
Jan Kara72b045a2017-11-15 17:34:33 -08001975 /*
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001976 * We come here when we got to @end. We take care to not overflow the
Jan Kara72b045a2017-11-15 17:34:33 -08001977 * index @index as it confuses some of the callers. This breaks the
Matthew Wilcoxa6906972018-05-16 18:12:54 -04001978 * iteration when there is a page at index -1 but that is already
1979 * broken anyway.
Jan Kara72b045a2017-11-15 17:34:33 -08001980 */
1981 if (end == (pgoff_t)-1)
1982 *index = (pgoff_t)-1;
1983 else
1984 *index = end + 1;
1985out:
Nick Piggina60637c2008-07-25 19:45:31 -07001986 rcu_read_unlock();
1987
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988 return ret;
1989}
Jan Kara72b045a2017-11-15 17:34:33 -08001990EXPORT_SYMBOL(find_get_pages_range_tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001991
Wu Fengguang76d42bd2006-06-25 05:48:43 -07001992/*
1993 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1994 * a _large_ part of the i/o request. Imagine the worst scenario:
1995 *
1996 * ---R__________________________________________B__________
1997 * ^ reading here ^ bad block(assume 4k)
1998 *
1999 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2000 * => failing the whole request => read(R) => read(R+1) =>
2001 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2002 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2003 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2004 *
2005 * It is going insane. Fix it by quickly scaling down the readahead size.
2006 */
2007static void shrink_readahead_size_eio(struct file *filp,
2008 struct file_ra_state *ra)
2009{
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002010 ra->ra_pages /= 4;
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002011}
2012
Randy Dunlap485bb992006-06-23 02:03:49 -07002013/**
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002014 * generic_file_buffered_read - generic file read routine
2015 * @iocb: the iocb to read
Al Viro6e58e792014-02-03 17:07:03 -05002016 * @iter: data destination
2017 * @written: already copied
Randy Dunlap485bb992006-06-23 02:03:49 -07002018 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07002019 * This is a generic file read routine, and uses the
Randy Dunlap485bb992006-06-23 02:03:49 -07002020 * mapping->a_ops->readpage() function for the actual low-level stuff.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002021 *
2022 * This is really ugly. But the goto's actually try to clarify some
2023 * of the logic when it comes to error handling etc.
Mike Rapoporta862f682019-03-05 15:48:42 -08002024 *
2025 * Return:
2026 * * total number of bytes copied, including those the were already @written
2027 * * negative error code if nothing was copied
Linus Torvalds1da177e2005-04-16 15:20:36 -07002028 */
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002029static ssize_t generic_file_buffered_read(struct kiocb *iocb,
Al Viro6e58e792014-02-03 17:07:03 -05002030 struct iov_iter *iter, ssize_t written)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002031{
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002032 struct file *filp = iocb->ki_filp;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002033 struct address_space *mapping = filp->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002034 struct inode *inode = mapping->host;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002035 struct file_ra_state *ra = &filp->f_ra;
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002036 loff_t *ppos = &iocb->ki_pos;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002037 pgoff_t index;
2038 pgoff_t last_index;
2039 pgoff_t prev_index;
2040 unsigned long offset; /* offset into pagecache page */
Jan Karaec0f1632007-05-06 14:49:25 -07002041 unsigned int prev_offset;
Al Viro6e58e792014-02-03 17:07:03 -05002042 int error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002043
Wei Fangc2a97372016-10-07 17:01:52 -07002044 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
Linus Torvaldsd05c5f72016-12-14 12:45:25 -08002045 return 0;
Wei Fangc2a97372016-10-07 17:01:52 -07002046 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2047
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002048 index = *ppos >> PAGE_SHIFT;
2049 prev_index = ra->prev_pos >> PAGE_SHIFT;
2050 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2051 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2052 offset = *ppos & ~PAGE_MASK;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002053
Linus Torvalds1da177e2005-04-16 15:20:36 -07002054 for (;;) {
2055 struct page *page;
Fengguang Wu57f6b962007-10-16 01:24:37 -07002056 pgoff_t end_index;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002057 loff_t isize;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002058 unsigned long nr, ret;
2059
Linus Torvalds1da177e2005-04-16 15:20:36 -07002060 cond_resched();
Linus Torvalds1da177e2005-04-16 15:20:36 -07002061find_page:
Michal Hocko5abf1862017-02-03 13:13:29 -08002062 if (fatal_signal_pending(current)) {
2063 error = -EINTR;
2064 goto out;
2065 }
2066
Linus Torvalds1da177e2005-04-16 15:20:36 -07002067 page = find_get_page(mapping, index);
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002068 if (!page) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002069 if (iocb->ki_flags & IOCB_NOWAIT)
2070 goto would_block;
Rusty Russellcf914a72007-07-19 01:48:08 -07002071 page_cache_sync_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002072 ra, filp,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002073 index, last_index - index);
2074 page = find_get_page(mapping, index);
2075 if (unlikely(page == NULL))
2076 goto no_cached_page;
2077 }
2078 if (PageReadahead(page)) {
Rusty Russellcf914a72007-07-19 01:48:08 -07002079 page_cache_async_readahead(mapping,
Fengguang Wu7ff81072007-10-16 01:24:35 -07002080 ra, filp, page,
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002081 index, last_index - index);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002082 }
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002083 if (!PageUptodate(page)) {
Milosz Tanski3239d832017-08-29 16:13:19 +02002084 if (iocb->ki_flags & IOCB_NOWAIT) {
2085 put_page(page);
2086 goto would_block;
2087 }
2088
Mel Gormanebded022016-03-15 14:55:39 -07002089 /*
2090 * See comment in do_read_cache_page on why
2091 * wait_on_page_locked is used to avoid unnecessarily
2092 * serialisations and why it's safe.
2093 */
Bart Van Asschec4b209a2016-10-07 16:58:33 -07002094 error = wait_on_page_locked_killable(page);
2095 if (unlikely(error))
2096 goto readpage_error;
Mel Gormanebded022016-03-15 14:55:39 -07002097 if (PageUptodate(page))
2098 goto page_ok;
2099
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002100 if (inode->i_blkbits == PAGE_SHIFT ||
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002101 !mapping->a_ops->is_partially_uptodate)
2102 goto page_not_up_to_date;
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002103 /* pipes can't handle partially uptodate pages */
David Howells00e23702018-10-22 13:07:28 +01002104 if (unlikely(iov_iter_is_pipe(iter)))
Eryu Guan6d6d36b2016-11-01 15:43:07 +08002105 goto page_not_up_to_date;
Nick Piggin529ae9a2008-08-02 12:01:03 +02002106 if (!trylock_page(page))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002107 goto page_not_up_to_date;
Dave Hansen8d056cb2010-11-11 14:05:15 -08002108 /* Did it get truncated before we got the lock? */
2109 if (!page->mapping)
2110 goto page_not_up_to_date_locked;
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002111 if (!mapping->a_ops->is_partially_uptodate(page,
Al Viro6e58e792014-02-03 17:07:03 -05002112 offset, iter->count))
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002113 goto page_not_up_to_date_locked;
2114 unlock_page(page);
2115 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002116page_ok:
NeilBrowna32ea1e2007-07-17 04:03:04 -07002117 /*
2118 * i_size must be checked after we know the page is Uptodate.
2119 *
2120 * Checking i_size after the check allows us to calculate
2121 * the correct value for "nr", which means the zero-filled
2122 * part of the page is not copied back to userspace (unless
2123 * another truncate extends the file - this is desired though).
2124 */
2125
2126 isize = i_size_read(inode);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002127 end_index = (isize - 1) >> PAGE_SHIFT;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002128 if (unlikely(!isize || index > end_index)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002129 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002130 goto out;
2131 }
2132
2133 /* nr is the maximum number of bytes to copy from this page */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002134 nr = PAGE_SIZE;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002135 if (index == end_index) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002136 nr = ((isize - 1) & ~PAGE_MASK) + 1;
NeilBrowna32ea1e2007-07-17 04:03:04 -07002137 if (nr <= offset) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002138 put_page(page);
NeilBrowna32ea1e2007-07-17 04:03:04 -07002139 goto out;
2140 }
2141 }
2142 nr = nr - offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002143
2144 /* If users can be writing to this page using arbitrary
2145 * virtual addresses, take care about potential aliasing
2146 * before reading the page on the kernel side.
2147 */
2148 if (mapping_writably_mapped(mapping))
2149 flush_dcache_page(page);
2150
2151 /*
Jan Karaec0f1632007-05-06 14:49:25 -07002152 * When a sequential read accesses a page several times,
2153 * only mark it as accessed the first time.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002154 */
Jan Karaec0f1632007-05-06 14:49:25 -07002155 if (prev_index != index || offset != prev_offset)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002156 mark_page_accessed(page);
2157 prev_index = index;
2158
2159 /*
2160 * Ok, we have the page, and it's up-to-date, so
2161 * now we can copy it to user space...
Linus Torvalds1da177e2005-04-16 15:20:36 -07002162 */
Al Viro6e58e792014-02-03 17:07:03 -05002163
2164 ret = copy_page_to_iter(page, offset, nr, iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002165 offset += ret;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002166 index += offset >> PAGE_SHIFT;
2167 offset &= ~PAGE_MASK;
Jan Kara6ce745e2007-05-06 14:49:26 -07002168 prev_offset = offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002169
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002170 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002171 written += ret;
2172 if (!iov_iter_count(iter))
2173 goto out;
2174 if (ret < nr) {
2175 error = -EFAULT;
2176 goto out;
2177 }
2178 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002179
2180page_not_up_to_date:
2181 /* Get exclusive access to the page ... */
Oleg Nesterov85462322008-06-08 21:20:43 +04002182 error = lock_page_killable(page);
2183 if (unlikely(error))
2184 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002185
Hisashi Hifumi8ab22b92008-07-28 15:46:36 -07002186page_not_up_to_date_locked:
Nick Pigginda6052f2006-09-25 23:31:35 -07002187 /* Did it get truncated before we got the lock? */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002188 if (!page->mapping) {
2189 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002190 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002191 continue;
2192 }
2193
2194 /* Did somebody else fill it already? */
2195 if (PageUptodate(page)) {
2196 unlock_page(page);
2197 goto page_ok;
2198 }
2199
2200readpage:
Jeff Moyer91803b42010-05-26 11:49:40 -04002201 /*
2202 * A previous I/O error may have been due to temporary
2203 * failures, eg. multipath errors.
2204 * PG_error will be set again if readpage fails.
2205 */
2206 ClearPageError(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002207 /* Start the actual read. The read will unlock the page. */
2208 error = mapping->a_ops->readpage(filp, page);
2209
Zach Brown994fc28c2005-12-15 14:28:17 -08002210 if (unlikely(error)) {
2211 if (error == AOP_TRUNCATED_PAGE) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002212 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002213 error = 0;
Zach Brown994fc28c2005-12-15 14:28:17 -08002214 goto find_page;
2215 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002216 goto readpage_error;
Zach Brown994fc28c2005-12-15 14:28:17 -08002217 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002218
2219 if (!PageUptodate(page)) {
Oleg Nesterov85462322008-06-08 21:20:43 +04002220 error = lock_page_killable(page);
2221 if (unlikely(error))
2222 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002223 if (!PageUptodate(page)) {
2224 if (page->mapping == NULL) {
2225 /*
Christoph Hellwig2ecdc822010-01-26 17:27:20 +01002226 * invalidate_mapping_pages got it
Linus Torvalds1da177e2005-04-16 15:20:36 -07002227 */
2228 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002229 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002230 goto find_page;
2231 }
2232 unlock_page(page);
Fengguang Wu7ff81072007-10-16 01:24:35 -07002233 shrink_readahead_size_eio(filp, ra);
Oleg Nesterov85462322008-06-08 21:20:43 +04002234 error = -EIO;
2235 goto readpage_error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002236 }
2237 unlock_page(page);
2238 }
2239
Linus Torvalds1da177e2005-04-16 15:20:36 -07002240 goto page_ok;
2241
2242readpage_error:
2243 /* UHHUH! A synchronous read error occurred. Report it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002244 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002245 goto out;
2246
2247no_cached_page:
2248 /*
2249 * Ok, it wasn't cached, so we need to create a new
2250 * page..
2251 */
Mel Gorman453f85d2017-11-15 17:38:03 -08002252 page = page_cache_alloc(mapping);
Nick Piggineb2be182007-10-16 01:24:57 -07002253 if (!page) {
Al Viro6e58e792014-02-03 17:07:03 -05002254 error = -ENOMEM;
Nick Piggineb2be182007-10-16 01:24:57 -07002255 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002256 }
Michal Hocko6afdb852015-06-24 16:58:06 -07002257 error = add_to_page_cache_lru(page, mapping, index,
Michal Hockoc62d2552015-11-06 16:28:49 -08002258 mapping_gfp_constraint(mapping, GFP_KERNEL));
Linus Torvalds1da177e2005-04-16 15:20:36 -07002259 if (error) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002260 put_page(page);
Al Viro6e58e792014-02-03 17:07:03 -05002261 if (error == -EEXIST) {
2262 error = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002263 goto find_page;
Al Viro6e58e792014-02-03 17:07:03 -05002264 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002265 goto out;
2266 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002267 goto readpage;
2268 }
2269
Milosz Tanski3239d832017-08-29 16:13:19 +02002270would_block:
2271 error = -EAGAIN;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002272out:
Fengguang Wu7ff81072007-10-16 01:24:35 -07002273 ra->prev_pos = prev_index;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002274 ra->prev_pos <<= PAGE_SHIFT;
Fengguang Wu7ff81072007-10-16 01:24:35 -07002275 ra->prev_pos |= prev_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002276
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002277 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002278 file_accessed(filp);
Al Viro6e58e792014-02-03 17:07:03 -05002279 return written ? written : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002280}
2281
Randy Dunlap485bb992006-06-23 02:03:49 -07002282/**
Al Viro6abd2322014-04-04 14:20:57 -04002283 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002284 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002285 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002286 *
Al Viro6abd2322014-04-04 14:20:57 -04002287 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002288 * that can use the page cache directly.
Mike Rapoporta862f682019-03-05 15:48:42 -08002289 * Return:
2290 * * number of bytes copied, even for partial reads
2291 * * negative error code if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002292 */
2293ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002294generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002295{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002296 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002297 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002298
2299 if (!count)
2300 goto out; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002301
Al Viro2ba48ce2015-04-09 13:52:01 -04002302 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002303 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002304 struct address_space *mapping = file->f_mapping;
2305 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002306 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002307
Linus Torvalds1da177e2005-04-16 15:20:36 -07002308 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002309 if (iocb->ki_flags & IOCB_NOWAIT) {
2310 if (filemap_range_has_page(mapping, iocb->ki_pos,
2311 iocb->ki_pos + count - 1))
2312 return -EAGAIN;
2313 } else {
2314 retval = filemap_write_and_wait_range(mapping,
2315 iocb->ki_pos,
2316 iocb->ki_pos + count - 1);
2317 if (retval < 0)
2318 goto out;
2319 }
Al Viroed978a82014-03-05 22:53:04 -05002320
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002321 file_accessed(file);
2322
Al Viro5ecda132017-04-13 14:13:36 -04002323 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002324 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002325 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002326 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002327 }
Al Viro5b47d592017-05-08 13:54:47 -04002328 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002329
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002330 /*
2331 * Btrfs can have a short DIO read if we encounter
2332 * compressed extents, so if there was an error, or if
2333 * we've already read everything we wanted to, or if
2334 * there was a short read because we hit EOF, go ahead
2335 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002336 * the rest of the read. Buffered reads will not work for
2337 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002338 */
Al Viro5ecda132017-04-13 14:13:36 -04002339 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002340 IS_DAX(inode))
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002341 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002342 }
2343
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002344 retval = generic_file_buffered_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002345out:
2346 return retval;
2347}
Al Viroed978a82014-03-05 22:53:04 -05002348EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002349
Linus Torvalds1da177e2005-04-16 15:20:36 -07002350#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002351#define MMAP_LOTSAMISS (100)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002352static struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
2353 struct file *fpin)
2354{
2355 int flags = vmf->flags;
2356
2357 if (fpin)
2358 return fpin;
2359
2360 /*
2361 * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
2362 * anything, so we only pin the file and drop the mmap_sem if only
2363 * FAULT_FLAG_ALLOW_RETRY is set.
2364 */
2365 if ((flags & (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT)) ==
2366 FAULT_FLAG_ALLOW_RETRY) {
2367 fpin = get_file(vmf->vma->vm_file);
2368 up_read(&vmf->vma->vm_mm->mmap_sem);
2369 }
2370 return fpin;
2371}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002372
Linus Torvaldsef00e082009-06-16 15:31:25 -07002373/*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002374 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_sem
2375 * @vmf - the vm_fault for this fault.
2376 * @page - the page to lock.
2377 * @fpin - the pointer to the file we may pin (or is already pinned).
2378 *
2379 * This works similar to lock_page_or_retry in that it can drop the mmap_sem.
2380 * It differs in that it actually returns the page locked if it returns 1 and 0
2381 * if it couldn't lock the page. If we did have to drop the mmap_sem then fpin
2382 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002383 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002384static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2385 struct file **fpin)
2386{
2387 if (trylock_page(page))
2388 return 1;
2389
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002390 /*
2391 * NOTE! This will make us return with VM_FAULT_RETRY, but with
2392 * the mmap_sem still held. That's how FAULT_FLAG_RETRY_NOWAIT
2393 * is supposed to work. We have way too many special cases..
2394 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002395 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2396 return 0;
2397
2398 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2399 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2400 if (__lock_page_killable(page)) {
2401 /*
2402 * We didn't have the right flags to drop the mmap_sem,
2403 * but all fault_handlers only check for fatal signals
2404 * if we return VM_FAULT_RETRY, so we need to drop the
2405 * mmap_sem here and return 0 if we don't have a fpin.
2406 */
2407 if (*fpin == NULL)
2408 up_read(&vmf->vma->vm_mm->mmap_sem);
2409 return 0;
2410 }
2411 } else
2412 __lock_page(page);
2413 return 1;
2414}
2415
2416
2417/*
2418 * Synchronous readahead happens when we don't even find a page in the page
2419 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2420 * to drop the mmap sem we return the file that was pinned in order for us to do
2421 * that. If we didn't pin a file then we return NULL. The file that is
2422 * returned needs to be fput()'ed when we're done with it.
2423 */
2424static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002425{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002426 struct file *file = vmf->vma->vm_file;
2427 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002428 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002429 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002430 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002431
2432 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002433 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002434 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002435 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002436 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002437
Josef Bacik2a1180f2019-03-13 11:44:18 -07002438 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002439 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang7ffc59b2009-06-16 15:31:38 -07002440 page_cache_sync_readahead(mapping, ra, file, offset,
2441 ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002442 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002443 }
2444
Andi Kleen207d04b2011-05-24 17:12:29 -07002445 /* Avoid banging the cache line if not needed */
2446 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002447 ra->mmap_miss++;
2448
2449 /*
2450 * Do we miss much more than hit in this file? If so,
2451 * stop bothering with read-ahead. It will only hurt.
2452 */
2453 if (ra->mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002454 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002455
Wu Fengguangd30a1102009-06-16 15:31:30 -07002456 /*
2457 * mmap read-around
2458 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002459 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002460 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2461 ra->size = ra->ra_pages;
2462 ra->async_size = ra->ra_pages / 4;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002463 ra_submit(ra, mapping, file);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002464 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002465}
2466
2467/*
2468 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002469 * so we want to possibly extend the readahead further. We return the file that
2470 * was pinned if we have to drop the mmap_sem in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002471 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002472static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2473 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002474{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002475 struct file *file = vmf->vma->vm_file;
2476 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002477 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002478 struct file *fpin = NULL;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002479 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002480
2481 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002482 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002483 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002484 if (ra->mmap_miss > 0)
2485 ra->mmap_miss--;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002486 if (PageReadahead(page)) {
2487 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002488 page_cache_async_readahead(mapping, ra, file,
2489 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002490 }
2491 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002492}
2493
Randy Dunlap485bb992006-06-23 02:03:49 -07002494/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002495 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002496 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002497 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002498 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002499 * mapped memory region to read in file data during a page fault.
2500 *
2501 * The goto's are kind of ugly, but this streamlines the normal case of having
2502 * it in the page cache, and handles the special cases reasonably without
2503 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002504 *
2505 * vma->vm_mm->mmap_sem must be held on entry.
2506 *
2507 * If our return value has VM_FAULT_RETRY set, it's because
2508 * lock_page_or_retry() returned 0.
2509 * The mmap_sem has usually been released in this case.
2510 * See __lock_page_or_retry() for the exception.
2511 *
2512 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2513 * has not been released.
2514 *
2515 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002516 *
2517 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002518 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002519vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002520{
2521 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002522 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002523 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002524 struct address_space *mapping = file->f_mapping;
2525 struct file_ra_state *ra = &file->f_ra;
2526 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002527 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002528 pgoff_t max_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002529 struct page *page;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002530 vm_fault_t ret = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002531
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002532 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2533 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002534 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002535
Linus Torvalds1da177e2005-04-16 15:20:36 -07002536 /*
Johannes Weiner49426422013-10-16 13:46:59 -07002537 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07002538 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002539 page = find_get_page(mapping, offset);
Shaohua Li45cac652012-10-08 16:32:19 -07002540 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002541 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002542 * We found the page, so try async readahead before
2543 * waiting for the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002544 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002545 fpin = do_async_mmap_readahead(vmf, page);
Shaohua Li45cac652012-10-08 16:32:19 -07002546 } else if (!page) {
Linus Torvaldsef00e082009-06-16 15:31:25 -07002547 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07002548 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07002549 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002550 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002551 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002552retry_find:
Josef Bacika75d4c32019-03-13 11:44:14 -07002553 page = pagecache_get_page(mapping, offset,
2554 FGP_CREAT|FGP_FOR_MMAP,
2555 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002556 if (!page) {
2557 if (fpin)
2558 goto out_retry;
Josef Bacika75d4c32019-03-13 11:44:14 -07002559 return vmf_error(-ENOMEM);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002560 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002561 }
2562
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002563 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
2564 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07002565
2566 /* Did it get truncated? */
2567 if (unlikely(page->mapping != mapping)) {
2568 unlock_page(page);
2569 put_page(page);
2570 goto retry_find;
2571 }
Sasha Levin309381fea2014-01-23 15:52:54 -08002572 VM_BUG_ON_PAGE(page->index != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07002573
Linus Torvalds1da177e2005-04-16 15:20:36 -07002574 /*
Nick Piggind00806b2007-07-19 01:46:57 -07002575 * We have a locked page in the page cache, now we need to check
2576 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002577 */
Nick Piggind00806b2007-07-19 01:46:57 -07002578 if (unlikely(!PageUptodate(page)))
Linus Torvalds1da177e2005-04-16 15:20:36 -07002579 goto page_not_uptodate;
2580
Linus Torvaldsef00e082009-06-16 15:31:25 -07002581 /*
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002582 * We've made it this far and we had to drop our mmap_sem, now is the
2583 * time to return to the upper layer and have it re-find the vma and
2584 * redo the fault.
2585 */
2586 if (fpin) {
2587 unlock_page(page);
2588 goto out_retry;
2589 }
2590
2591 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07002592 * Found the page and have a reference on it.
2593 * We must recheck i_size under page lock.
2594 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002595 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2596 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07002597 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002598 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07002599 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07002600 }
2601
Nick Piggind0217ac2007-07-19 01:47:03 -07002602 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07002603 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002604
Linus Torvalds1da177e2005-04-16 15:20:36 -07002605page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002606 /*
2607 * Umm, take care of errors if the page isn't up-to-date.
2608 * Try to re-read it _once_. We do this synchronously,
2609 * because there really aren't any performance issues here
2610 * and we need to check for errors.
2611 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002612 ClearPageError(page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002613 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Zach Brown994fc28c2005-12-15 14:28:17 -08002614 error = mapping->a_ops->readpage(file, page);
Miklos Szeredi3ef0f722008-05-14 16:05:37 -07002615 if (!error) {
2616 wait_on_page_locked(page);
2617 if (!PageUptodate(page))
2618 error = -EIO;
2619 }
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002620 if (fpin)
2621 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002622 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07002623
2624 if (!error || error == AOP_TRUNCATED_PAGE)
2625 goto retry_find;
2626
2627 /* Things didn't work out. Return zero to tell the mm layer so. */
2628 shrink_readahead_size_eio(file, ra);
Nick Piggind0217ac2007-07-19 01:47:03 -07002629 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002630
2631out_retry:
2632 /*
2633 * We dropped the mmap_sem, we need to return to the fault handler to
2634 * re-find the vma and come back and find our hopefully still populated
2635 * page.
2636 */
2637 if (page)
2638 put_page(page);
2639 if (fpin)
2640 fput(fpin);
2641 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07002642}
2643EXPORT_SYMBOL(filemap_fault);
2644
Jan Kara82b0f8c2016-12-14 15:06:58 -08002645void filemap_map_pages(struct vm_fault *vmf,
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002646 pgoff_t start_pgoff, pgoff_t end_pgoff)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002647{
Jan Kara82b0f8c2016-12-14 15:06:58 -08002648 struct file *file = vmf->vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002649 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07002650 pgoff_t last_pgoff = start_pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002651 unsigned long max_idx;
Matthew Wilcox070e8072018-05-17 00:08:30 -04002652 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002653 struct page *head, *page;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002654
2655 rcu_read_lock();
Matthew Wilcox070e8072018-05-17 00:08:30 -04002656 xas_for_each(&xas, page, end_pgoff) {
2657 if (xas_retry(&xas, page))
2658 continue;
2659 if (xa_is_value(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002660 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002661
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002662 head = compound_head(page);
2663
Michal Hockoe0975b22018-12-28 00:38:36 -08002664 /*
2665 * Check for a locked page first, as a speculative
2666 * reference may adversely influence page migration.
2667 */
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002668 if (PageLocked(head))
Michal Hockoe0975b22018-12-28 00:38:36 -08002669 goto next;
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002670 if (!page_cache_get_speculative(head))
Matthew Wilcox070e8072018-05-17 00:08:30 -04002671 goto next;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002672
Linus Torvalds69bf4b62019-07-05 19:55:18 -07002673 /* The page was split under us? */
2674 if (compound_head(page) != head)
2675 goto skip;
2676
2677 /* Has the page moved? */
Matthew Wilcox070e8072018-05-17 00:08:30 -04002678 if (unlikely(page != xas_reload(&xas)))
2679 goto skip;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002680
2681 if (!PageUptodate(page) ||
2682 PageReadahead(page) ||
2683 PageHWPoison(page))
2684 goto skip;
2685 if (!trylock_page(page))
2686 goto skip;
2687
2688 if (page->mapping != mapping || !PageUptodate(page))
2689 goto unlock;
2690
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002691 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2692 if (page->index >= max_idx)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002693 goto unlock;
2694
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002695 if (file->f_ra.mmap_miss > 0)
2696 file->f_ra.mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002697
Matthew Wilcox070e8072018-05-17 00:08:30 -04002698 vmf->address += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002699 if (vmf->pte)
Matthew Wilcox070e8072018-05-17 00:08:30 -04002700 vmf->pte += xas.xa_index - last_pgoff;
2701 last_pgoff = xas.xa_index;
Jan Kara82b0f8c2016-12-14 15:06:58 -08002702 if (alloc_set_pte(vmf, NULL, page))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002703 goto unlock;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002704 unlock_page(page);
2705 goto next;
2706unlock:
2707 unlock_page(page);
2708skip:
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002709 put_page(page);
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002710next:
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002711 /* Huge page is mapped? No need to proceed. */
Jan Kara82b0f8c2016-12-14 15:06:58 -08002712 if (pmd_trans_huge(*vmf->pmd))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07002713 break;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002714 }
2715 rcu_read_unlock();
2716}
2717EXPORT_SYMBOL(filemap_map_pages);
2718
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002719vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02002720{
2721 struct page *page = vmf->page;
Dave Jiang11bac802017-02-24 14:56:41 -08002722 struct inode *inode = file_inode(vmf->vma->vm_file);
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002723 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02002724
Jan Kara14da9202012-06-12 16:20:37 +02002725 sb_start_pagefault(inode->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08002726 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002727 lock_page(page);
2728 if (page->mapping != inode->i_mapping) {
2729 unlock_page(page);
2730 ret = VM_FAULT_NOPAGE;
2731 goto out;
2732 }
Jan Kara14da9202012-06-12 16:20:37 +02002733 /*
2734 * We mark the page dirty already here so that when freeze is in
2735 * progress, we are guaranteed that writeback during freezing will
2736 * see the dirty page and writeprotect it again.
2737 */
2738 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08002739 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002740out:
Jan Kara14da9202012-06-12 16:20:37 +02002741 sb_end_pagefault(inode->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02002742 return ret;
2743}
Jan Kara4fcf1c62012-06-12 16:20:29 +02002744
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04002745const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07002746 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07002747 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02002748 .page_mkwrite = filemap_page_mkwrite,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002749};
2750
2751/* This is used for a general mmap of a disk file */
2752
2753int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2754{
2755 struct address_space *mapping = file->f_mapping;
2756
2757 if (!mapping->a_ops->readpage)
2758 return -ENOEXEC;
2759 file_accessed(file);
2760 vma->vm_ops = &generic_file_vm_ops;
2761 return 0;
2762}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002763
2764/*
2765 * This is for filesystems which do not implement ->writepage.
2766 */
2767int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2768{
2769 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2770 return -EINVAL;
2771 return generic_file_mmap(file, vma);
2772}
2773#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07002774vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann453972282018-04-13 15:35:27 -07002775{
Souptick Joarder4b96a372018-10-26 15:04:03 -07002776 return VM_FAULT_SIGBUS;
Arnd Bergmann453972282018-04-13 15:35:27 -07002777}
Linus Torvalds1da177e2005-04-16 15:20:36 -07002778int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2779{
2780 return -ENOSYS;
2781}
2782int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2783{
2784 return -ENOSYS;
2785}
2786#endif /* CONFIG_MMU */
2787
Arnd Bergmann453972282018-04-13 15:35:27 -07002788EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002789EXPORT_SYMBOL(generic_file_mmap);
2790EXPORT_SYMBOL(generic_file_readonly_mmap);
2791
Sasha Levin67f9fd92014-04-03 14:48:18 -07002792static struct page *wait_on_page_read(struct page *page)
2793{
2794 if (!IS_ERR(page)) {
2795 wait_on_page_locked(page);
2796 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002797 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07002798 page = ERR_PTR(-EIO);
2799 }
2800 }
2801 return page;
2802}
2803
Mel Gorman32b63522016-03-15 14:55:36 -07002804static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07002805 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002806 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002807 void *data,
2808 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002809{
Nick Piggineb2be182007-10-16 01:24:57 -07002810 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002811 int err;
2812repeat:
2813 page = find_get_page(mapping, index);
2814 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08002815 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002816 if (!page)
2817 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002818 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07002819 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002820 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07002821 if (err == -EEXIST)
2822 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05002823 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002824 return ERR_PTR(err);
2825 }
Mel Gorman32b63522016-03-15 14:55:36 -07002826
2827filler:
Linus Torvalds1da177e2005-04-16 15:20:36 -07002828 err = filler(data, page);
2829 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002830 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002831 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002832 }
Mel Gorman32b63522016-03-15 14:55:36 -07002833
2834 page = wait_on_page_read(page);
2835 if (IS_ERR(page))
2836 return page;
2837 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002838 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07002839 if (PageUptodate(page))
2840 goto out;
2841
Mel Gormanebded022016-03-15 14:55:39 -07002842 /*
2843 * Page is not up to date and may be locked due one of the following
2844 * case a: Page is being filled and the page lock is held
2845 * case b: Read/write error clearing the page uptodate status
2846 * case c: Truncation in progress (page locked)
2847 * case d: Reclaim in progress
2848 *
2849 * Case a, the page will be up to date when the page is unlocked.
2850 * There is no need to serialise on the page lock here as the page
2851 * is pinned so the lock gives no additional protection. Even if the
2852 * the page is truncated, the data is still valid if PageUptodate as
2853 * it's a race vs truncate race.
2854 * Case b, the page will not be up to date
2855 * Case c, the page may be truncated but in itself, the data may still
2856 * be valid after IO completes as it's a read vs truncate race. The
2857 * operation must restart if the page is not uptodate on unlock but
2858 * otherwise serialising on page lock to stabilise the mapping gives
2859 * no additional guarantees to the caller as the page lock is
2860 * released before return.
2861 * Case d, similar to truncation. If reclaim holds the page lock, it
2862 * will be a race with remove_mapping that determines if the mapping
2863 * is valid on unlock but otherwise the data is valid and there is
2864 * no need to serialise with page lock.
2865 *
2866 * As the page lock gives no additional guarantee, we optimistically
2867 * wait on the page to be unlocked and check if it's up to date and
2868 * use the page if it is. Otherwise, the page lock is required to
2869 * distinguish between the different cases. The motivation is that we
2870 * avoid spurious serialisations and wakeups when multiple processes
2871 * wait on the same page for IO to complete.
2872 */
2873 wait_on_page_locked(page);
2874 if (PageUptodate(page))
2875 goto out;
2876
2877 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002878 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07002879
2880 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002881 if (!page->mapping) {
2882 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03002883 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07002884 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002885 }
Mel Gormanebded022016-03-15 14:55:39 -07002886
2887 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002888 if (PageUptodate(page)) {
2889 unlock_page(page);
2890 goto out;
2891 }
Mel Gorman32b63522016-03-15 14:55:36 -07002892 goto filler;
2893
David Howellsc855ff32007-05-09 13:42:20 +01002894out:
Nick Piggin6fe69002007-05-06 14:49:04 -07002895 mark_page_accessed(page);
2896 return page;
2897}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002898
2899/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07002900 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002901 * @mapping: the page's address_space
2902 * @index: the page index
2903 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002904 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002905 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002906 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07002907 * not set, try to fill the page and wait for it to become unlocked.
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 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07002913struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002914 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07002915 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002916 void *data)
2917{
Christoph Hellwigd322a8e2019-07-11 20:55:17 -07002918 return do_read_cache_page(mapping, index, filler, data,
2919 mapping_gfp_mask(mapping));
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002920}
Sasha Levin67f9fd92014-04-03 14:48:18 -07002921EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002922
2923/**
2924 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2925 * @mapping: the page's address_space
2926 * @index: the page index
2927 * @gfp: the page allocator flags to use if allocating
2928 *
2929 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06002930 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002931 *
2932 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08002933 *
2934 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002935 */
2936struct page *read_cache_page_gfp(struct address_space *mapping,
2937 pgoff_t index,
2938 gfp_t gfp)
2939{
2940 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2941
Sasha Levin67f9fd92014-04-03 14:48:18 -07002942 return do_read_cache_page(mapping, index, filler, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08002943}
2944EXPORT_SYMBOL(read_cache_page_gfp);
2945
Nick Piggin2f718ff2007-10-16 01:24:59 -07002946/*
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002947 * Don't operate on ranges the page cache doesn't support, and don't exceed the
2948 * LFS limits. If pos is under the limit it becomes a short access. If it
2949 * exceeds the limit we return -EFBIG.
2950 */
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002951static int generic_write_check_limits(struct file *file, loff_t pos,
2952 loff_t *count)
2953{
Amir Goldstein646955c2019-06-05 08:04:48 -07002954 struct inode *inode = file->f_mapping->host;
2955 loff_t max_size = inode->i_sb->s_maxbytes;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002956 loff_t limit = rlimit(RLIMIT_FSIZE);
2957
2958 if (limit != RLIM_INFINITY) {
2959 if (pos >= limit) {
2960 send_sig(SIGXFSZ, current, 0);
2961 return -EFBIG;
2962 }
2963 *count = min(*count, limit - pos);
2964 }
2965
Amir Goldstein646955c2019-06-05 08:04:48 -07002966 if (!(file->f_flags & O_LARGEFILE))
2967 max_size = MAX_NON_LFS;
2968
2969 if (unlikely(pos >= max_size))
2970 return -EFBIG;
2971
2972 *count = min(*count, max_size - pos);
2973
2974 return 0;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002975}
2976
2977/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07002978 * Performs necessary checks before doing a write
2979 *
Randy Dunlap485bb992006-06-23 02:03:49 -07002980 * Can adjust writing position or amount of bytes to write.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002981 * Returns appropriate error code that caller should return or
2982 * zero in case that write should be allowed.
2983 */
Al Viro3309dd02015-04-09 12:55:47 -04002984inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002985{
Al Viro3309dd02015-04-09 12:55:47 -04002986 struct file *file = iocb->ki_filp;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002987 struct inode *inode = file->f_mapping->host;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11002988 loff_t count;
2989 int ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002990
Al Viro3309dd02015-04-09 12:55:47 -04002991 if (!iov_iter_count(from))
2992 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002993
Al Viro0fa6b002015-04-04 04:05:48 -04002994 /* FIXME: this is for backwards compatibility with 2.4 */
Al Viro2ba48ce2015-04-09 13:52:01 -04002995 if (iocb->ki_flags & IOCB_APPEND)
Al Viro3309dd02015-04-09 12:55:47 -04002996 iocb->ki_pos = i_size_read(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002997
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002998 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2999 return -EINVAL;
3000
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003001 count = iov_iter_count(from);
3002 ret = generic_write_check_limits(file, iocb->ki_pos, &count);
3003 if (ret)
3004 return ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003005
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003006 iov_iter_truncate(from, count);
Al Viro3309dd02015-04-09 12:55:47 -04003007 return iov_iter_count(from);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003008}
3009EXPORT_SYMBOL(generic_write_checks);
3010
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003011/*
3012 * Performs necessary checks before doing a clone.
3013 *
Amir Goldstein646955c2019-06-05 08:04:48 -07003014 * Can adjust amount of bytes to clone via @req_count argument.
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003015 * Returns appropriate error code that caller should return or
3016 * zero in case the clone should be allowed.
3017 */
3018int generic_remap_checks(struct file *file_in, loff_t pos_in,
3019 struct file *file_out, loff_t pos_out,
Darrick J. Wong42ec3d42018-10-30 10:41:49 +11003020 loff_t *req_count, unsigned int remap_flags)
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003021{
3022 struct inode *inode_in = file_in->f_mapping->host;
3023 struct inode *inode_out = file_out->f_mapping->host;
3024 uint64_t count = *req_count;
3025 uint64_t bcount;
3026 loff_t size_in, size_out;
3027 loff_t bs = inode_out->i_sb->s_blocksize;
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003028 int ret;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003029
3030 /* The start of both ranges must be aligned to an fs block. */
3031 if (!IS_ALIGNED(pos_in, bs) || !IS_ALIGNED(pos_out, bs))
3032 return -EINVAL;
3033
3034 /* Ensure offsets don't wrap. */
3035 if (pos_in + count < pos_in || pos_out + count < pos_out)
3036 return -EINVAL;
3037
3038 size_in = i_size_read(inode_in);
3039 size_out = i_size_read(inode_out);
3040
3041 /* Dedupe requires both ranges to be within EOF. */
Darrick J. Wong3d281932018-10-30 10:41:34 +11003042 if ((remap_flags & REMAP_FILE_DEDUP) &&
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003043 (pos_in >= size_in || pos_in + count > size_in ||
3044 pos_out >= size_out || pos_out + count > size_out))
3045 return -EINVAL;
3046
3047 /* Ensure the infile range is within the infile. */
3048 if (pos_in >= size_in)
3049 return -EINVAL;
3050 count = min(count, size_in - (uint64_t)pos_in);
3051
Darrick J. Wong9fd91a90cb2018-10-30 10:40:46 +11003052 ret = generic_write_check_limits(file_out, pos_out, &count);
3053 if (ret)
3054 return ret;
3055
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003056 /*
3057 * If the user wanted us to link to the infile's EOF, round up to the
3058 * next block boundary for this check.
3059 *
3060 * Otherwise, make sure the count is also block-aligned, having
3061 * already confirmed the starting offsets' block alignment.
3062 */
3063 if (pos_in + count == size_in) {
3064 bcount = ALIGN(size_in, bs) - pos_in;
3065 } else {
3066 if (!IS_ALIGNED(count, bs))
Darrick J. Wongeca36542018-10-30 10:42:10 +11003067 count = ALIGN_DOWN(count, bs);
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003068 bcount = count;
3069 }
3070
3071 /* Don't allow overlapped cloning within the same file. */
3072 if (inode_in == inode_out &&
3073 pos_out + bcount > pos_in &&
3074 pos_out < pos_in + bcount)
3075 return -EINVAL;
3076
Darrick J. Wongeca36542018-10-30 10:42:10 +11003077 /*
3078 * We shortened the request but the caller can't deal with that, so
3079 * bounce the request back to userspace.
3080 */
3081 if (*req_count != count && !(remap_flags & REMAP_FILE_CAN_SHORTEN))
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003082 return -EINVAL;
3083
Darrick J. Wongeca36542018-10-30 10:42:10 +11003084 *req_count = count;
Darrick J. Wong1383a7e2018-10-30 10:40:31 +11003085 return 0;
3086}
3087
Amir Goldsteina3171352019-06-05 08:04:48 -07003088
3089/*
3090 * Performs common checks before doing a file copy/clone
3091 * from @file_in to @file_out.
3092 */
3093int generic_file_rw_checks(struct file *file_in, struct file *file_out)
3094{
3095 struct inode *inode_in = file_inode(file_in);
3096 struct inode *inode_out = file_inode(file_out);
3097
3098 /* Don't copy dirs, pipes, sockets... */
3099 if (S_ISDIR(inode_in->i_mode) || S_ISDIR(inode_out->i_mode))
3100 return -EISDIR;
3101 if (!S_ISREG(inode_in->i_mode) || !S_ISREG(inode_out->i_mode))
3102 return -EINVAL;
3103
3104 if (!(file_in->f_mode & FMODE_READ) ||
3105 !(file_out->f_mode & FMODE_WRITE) ||
3106 (file_out->f_flags & O_APPEND))
3107 return -EBADF;
3108
3109 return 0;
3110}
3111
Amir Goldstein96e6e8f2019-06-05 08:04:49 -07003112/*
3113 * Performs necessary checks before doing a file copy
3114 *
3115 * Can adjust amount of bytes to copy via @req_count argument.
3116 * Returns appropriate error code that caller should return or
3117 * zero in case the copy should be allowed.
3118 */
3119int generic_copy_file_checks(struct file *file_in, loff_t pos_in,
3120 struct file *file_out, loff_t pos_out,
3121 size_t *req_count, unsigned int flags)
3122{
3123 struct inode *inode_in = file_inode(file_in);
3124 struct inode *inode_out = file_inode(file_out);
3125 uint64_t count = *req_count;
3126 loff_t size_in;
3127 int ret;
3128
3129 ret = generic_file_rw_checks(file_in, file_out);
3130 if (ret)
3131 return ret;
3132
3133 /* Don't touch certain kinds of inodes */
3134 if (IS_IMMUTABLE(inode_out))
3135 return -EPERM;
3136
3137 if (IS_SWAPFILE(inode_in) || IS_SWAPFILE(inode_out))
3138 return -ETXTBSY;
3139
3140 /* Ensure offsets don't wrap. */
3141 if (pos_in + count < pos_in || pos_out + count < pos_out)
3142 return -EOVERFLOW;
3143
3144 /* Shorten the copy to EOF */
3145 size_in = i_size_read(inode_in);
3146 if (pos_in >= size_in)
3147 count = 0;
3148 else
3149 count = min(count, size_in - (uint64_t)pos_in);
3150
3151 ret = generic_write_check_limits(file_out, pos_out, &count);
3152 if (ret)
3153 return ret;
3154
3155 /* Don't allow overlapped copying within the same file. */
3156 if (inode_in == inode_out &&
3157 pos_out + count > pos_in &&
3158 pos_out < pos_in + count)
3159 return -EINVAL;
3160
3161 *req_count = count;
3162 return 0;
3163}
3164
Nick Pigginafddba42007-10-16 01:25:01 -07003165int pagecache_write_begin(struct file *file, struct address_space *mapping,
3166 loff_t pos, unsigned len, unsigned flags,
3167 struct page **pagep, void **fsdata)
3168{
3169 const struct address_space_operations *aops = mapping->a_ops;
3170
Nick Piggin4e02ed42008-10-29 14:00:55 -07003171 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003172 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003173}
3174EXPORT_SYMBOL(pagecache_write_begin);
3175
3176int pagecache_write_end(struct file *file, struct address_space *mapping,
3177 loff_t pos, unsigned len, unsigned copied,
3178 struct page *page, void *fsdata)
3179{
3180 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003181
Nick Piggin4e02ed42008-10-29 14:00:55 -07003182 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003183}
3184EXPORT_SYMBOL(pagecache_write_end);
3185
Linus Torvalds1da177e2005-04-16 15:20:36 -07003186ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003187generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003188{
3189 struct file *file = iocb->ki_filp;
3190 struct address_space *mapping = file->f_mapping;
3191 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003192 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003193 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003194 size_t write_len;
3195 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003196
Al Viro0c949332014-03-22 06:51:37 -04003197 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003198 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003199
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003200 if (iocb->ki_flags & IOCB_NOWAIT) {
3201 /* If there are pages to writeback, return */
3202 if (filemap_range_has_page(inode->i_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003203 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003204 return -EAGAIN;
3205 } else {
3206 written = filemap_write_and_wait_range(mapping, pos,
3207 pos + write_len - 1);
3208 if (written)
3209 goto out;
3210 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003211
3212 /*
3213 * After a write we want buffered reads to be sure to go to disk to get
3214 * the new data. We invalidate clean cached page from the region we're
3215 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003216 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003217 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003218 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003219 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003220 /*
3221 * If a page can not be invalidated, return 0 to fall back
3222 * to buffered write.
3223 */
3224 if (written) {
3225 if (written == -EBUSY)
3226 return 0;
3227 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003228 }
3229
Al Viro639a93a52017-04-13 14:10:15 -04003230 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003231
3232 /*
3233 * Finally, try again to invalidate clean pages which might have been
3234 * cached by non-direct readahead, or faulted in by get_user_pages()
3235 * if the source of the write was an mmap'ed region of the file
3236 * we're writing. Either one is a pretty crazy thing to do,
3237 * so we don't support it 100%. If this invalidation
3238 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003239 *
3240 * Most of the time we do not need this since dio_complete() will do
3241 * the invalidation for us. However there are some file systems that
3242 * do not end up with dio_complete() being called, so let's not break
3243 * them by removing it completely
Christoph Hellwiga969e902008-07-23 21:27:04 -07003244 */
Lukas Czerner332391a2017-09-21 08:16:29 -06003245 if (mapping->nrpages)
3246 invalidate_inode_pages2_range(mapping,
3247 pos >> PAGE_SHIFT, end);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003248
Linus Torvalds1da177e2005-04-16 15:20:36 -07003249 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003250 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003251 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003252 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3253 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003254 mark_inode_dirty(inode);
3255 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003256 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003257 }
Al Viro639a93a52017-04-13 14:10:15 -04003258 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003259out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003260 return written;
3261}
3262EXPORT_SYMBOL(generic_file_direct_write);
3263
Nick Piggineb2be182007-10-16 01:24:57 -07003264/*
3265 * Find or create a page at the given pagecache position. Return the locked
3266 * page. This function is specifically for buffered writes.
3267 */
Nick Piggin54566b22009-01-04 12:00:53 -08003268struct page *grab_cache_page_write_begin(struct address_space *mapping,
3269 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003270{
Nick Piggineb2be182007-10-16 01:24:57 -07003271 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003272 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003273
Nick Piggin54566b22009-01-04 12:00:53 -08003274 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003275 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003276
Mel Gorman2457aec2014-06-04 16:10:31 -07003277 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003278 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003279 if (page)
3280 wait_for_stable_page(page);
3281
Nick Piggineb2be182007-10-16 01:24:57 -07003282 return page;
3283}
Nick Piggin54566b22009-01-04 12:00:53 -08003284EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003285
Al Viro3b93f912014-02-11 21:34:08 -05003286ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003287 struct iov_iter *i, loff_t pos)
3288{
3289 struct address_space *mapping = file->f_mapping;
3290 const struct address_space_operations *a_ops = mapping->a_ops;
3291 long status = 0;
3292 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003293 unsigned int flags = 0;
3294
Nick Pigginafddba42007-10-16 01:25:01 -07003295 do {
3296 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003297 unsigned long offset; /* Offset into pagecache page */
3298 unsigned long bytes; /* Bytes to write to page */
3299 size_t copied; /* Bytes copied from user */
3300 void *fsdata;
3301
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003302 offset = (pos & (PAGE_SIZE - 1));
3303 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003304 iov_iter_count(i));
3305
3306again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003307 /*
3308 * Bring in the user page that we will copy from _first_.
3309 * Otherwise there's a nasty deadlock on copying from the
3310 * same page as we're writing to, without it being marked
3311 * up-to-date.
3312 *
3313 * Not only is this an optimisation, but it is also required
3314 * to check that the address is actually valid, when atomic
3315 * usercopies are used, below.
3316 */
3317 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3318 status = -EFAULT;
3319 break;
3320 }
3321
Jan Kara296291c2015-10-22 13:32:21 -07003322 if (fatal_signal_pending(current)) {
3323 status = -EINTR;
3324 break;
3325 }
3326
Nick Piggin674b8922007-10-16 01:25:03 -07003327 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003328 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003329 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003330 break;
3331
anfei zhou931e80e2010-02-02 13:44:02 -08003332 if (mapping_writably_mapped(mapping))
3333 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003334
Nick Pigginafddba42007-10-16 01:25:01 -07003335 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
Nick Pigginafddba42007-10-16 01:25:01 -07003336 flush_dcache_page(page);
3337
3338 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3339 page, fsdata);
3340 if (unlikely(status < 0))
3341 break;
3342 copied = status;
3343
3344 cond_resched();
3345
Nick Piggin124d3b72008-02-02 15:01:17 +01003346 iov_iter_advance(i, copied);
Nick Pigginafddba42007-10-16 01:25:01 -07003347 if (unlikely(copied == 0)) {
3348 /*
3349 * If we were unable to copy any data at all, we must
3350 * fall back to a single segment length write.
3351 *
3352 * If we didn't fallback here, we could livelock
3353 * because not all segments in the iov can be copied at
3354 * once without a pagefault.
3355 */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003356 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003357 iov_iter_single_seg_count(i));
3358 goto again;
3359 }
Nick Pigginafddba42007-10-16 01:25:01 -07003360 pos += copied;
3361 written += copied;
3362
3363 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003364 } while (iov_iter_count(i));
3365
3366 return written ? written : status;
3367}
Al Viro3b93f912014-02-11 21:34:08 -05003368EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003369
Jan Karae4dd9de2009-08-17 18:10:06 +02003370/**
Al Viro81742022014-04-03 03:17:43 -04003371 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003372 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003373 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003374 *
3375 * This function does all the work needed for actually writing data to a
3376 * file. It does all basic checks, removes SUID from the file, updates
3377 * modification times and calls proper subroutines depending on whether we
3378 * do direct IO or a standard buffered write.
3379 *
3380 * It expects i_mutex to be grabbed unless we work on a block device or similar
3381 * object which does not need locking at all.
3382 *
3383 * This function does *not* take care of syncing data in case of O_SYNC write.
3384 * A caller has to handle it. This is mainly due to the fact that we want to
3385 * avoid syncing under i_mutex.
Mike Rapoporta862f682019-03-05 15:48:42 -08003386 *
3387 * Return:
3388 * * number of bytes written, even for truncated writes
3389 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003390 */
Al Viro81742022014-04-03 03:17:43 -04003391ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003392{
3393 struct file *file = iocb->ki_filp;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003394 struct address_space * mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003395 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003396 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003397 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003398 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003399
Linus Torvalds1da177e2005-04-16 15:20:36 -07003400 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003401 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003402 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003403 if (err)
3404 goto out;
3405
Josef Bacikc3b2da32012-03-26 09:59:21 -04003406 err = file_update_time(file);
3407 if (err)
3408 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003409
Al Viro2ba48ce2015-04-09 13:52:01 -04003410 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003411 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003412
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003413 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003414 /*
3415 * If the write stopped short of completing, fall back to
3416 * buffered writes. Some filesystems do this for writes to
3417 * holes, for example. For DAX files, a buffered write will
3418 * not succeed (even if it did, DAX does not handle dirty
3419 * page-cache pages correctly).
3420 */
Al Viro0b8def92015-04-07 10:22:53 -04003421 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003422 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003423
Al Viro0b8def92015-04-07 10:22:53 -04003424 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003425 /*
Al Viro3b93f912014-02-11 21:34:08 -05003426 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003427 * then we want to return the number of bytes which were
3428 * direct-written, or the error code if that was zero. Note
3429 * that this differs from normal direct-io semantics, which
3430 * will return -EFOO even if some bytes were written.
3431 */
Al Viro60bb4522014-08-08 12:39:16 -04003432 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003433 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003434 goto out;
3435 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003436 /*
3437 * We need to ensure that the page cache pages are written to
3438 * disk and invalidated to preserve the expected O_DIRECT
3439 * semantics.
3440 */
Al Viro3b93f912014-02-11 21:34:08 -05003441 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003442 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003443 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003444 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003445 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003446 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003447 pos >> PAGE_SHIFT,
3448 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003449 } else {
3450 /*
3451 * We don't know how much we wrote, so just return
3452 * the number of bytes which were direct-written
3453 */
3454 }
3455 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003456 written = generic_perform_write(file, from, iocb->ki_pos);
3457 if (likely(written > 0))
3458 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003459 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003460out:
3461 current->backing_dev_info = NULL;
3462 return written ? written : err;
3463}
Al Viro81742022014-04-03 03:17:43 -04003464EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003465
Jan Karae4dd9de2009-08-17 18:10:06 +02003466/**
Al Viro81742022014-04-03 03:17:43 -04003467 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003468 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003469 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003470 *
Al Viro81742022014-04-03 03:17:43 -04003471 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003472 * filesystems. It takes care of syncing the file in case of O_SYNC file
3473 * and acquires i_mutex as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003474 * Return:
3475 * * negative error code if no data has been written at all of
3476 * vfs_fsync_range() failed for a synchronous write
3477 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003478 */
Al Viro81742022014-04-03 03:17:43 -04003479ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003480{
3481 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003482 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003483 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003484
Al Viro59551022016-01-22 15:40:57 -05003485 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003486 ret = generic_write_checks(iocb, from);
3487 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003488 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003489 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003490
Christoph Hellwige2592212016-04-07 08:52:01 -07003491 if (ret > 0)
3492 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003493 return ret;
3494}
Al Viro81742022014-04-03 03:17:43 -04003495EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003496
David Howellscf9a2ae2006-08-29 19:05:54 +01003497/**
3498 * try_to_release_page() - release old fs-specific metadata on a page
3499 *
3500 * @page: the page which the kernel is trying to free
3501 * @gfp_mask: memory allocation flags (and I/O mode)
3502 *
3503 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003504 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003505 *
David Howells266cf652009-04-03 16:42:36 +01003506 * This may also be called if PG_fscache is set on a page, indicating that the
3507 * page is known to the local caching routines.
3508 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003509 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003510 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003511 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003512 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003513 */
3514int try_to_release_page(struct page *page, gfp_t gfp_mask)
3515{
3516 struct address_space * const mapping = page->mapping;
3517
3518 BUG_ON(!PageLocked(page));
3519 if (PageWriteback(page))
3520 return 0;
3521
3522 if (mapping && mapping->a_ops->releasepage)
3523 return mapping->a_ops->releasepage(page, gfp_mask);
3524 return try_to_free_buffers(page);
3525}
3526
3527EXPORT_SYMBOL(try_to_release_page);