blob: f7f9b87d2cd000e043c85e36c9dbfcfa9fdd3a1d [file] [log] [blame]
Thomas Gleixner457c8992019-05-19 13:08:55 +01001// SPDX-License-Identifier: GPL-2.0-only
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
3 * linux/mm/filemap.c
4 *
5 * Copyright (C) 1994-1999 Linus Torvalds
6 */
7
8/*
9 * This file handles the generic file mmap semantics used by
10 * most "normal" filesystems (but you don't /have/ to use this:
11 * the NFS filesystem used to do this differently, for example)
12 */
Paul Gortmakerb95f1b312011-10-16 02:01:52 -040013#include <linux/export.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070014#include <linux/compiler.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080015#include <linux/dax.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070016#include <linux/fs.h>
Ingo Molnar3f07c012017-02-08 18:51:30 +010017#include <linux/sched/signal.h>
Hiro Yoshiokac22ce142006-06-23 02:04:16 -070018#include <linux/uaccess.h>
Randy.Dunlapc59ede72006-01-11 12:17:46 -080019#include <linux/capability.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070020#include <linux/kernel_stat.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090021#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070022#include <linux/mm.h>
23#include <linux/swap.h>
24#include <linux/mman.h>
25#include <linux/pagemap.h>
26#include <linux/file.h>
27#include <linux/uio.h>
Josef Bacikcfcbfb12019-05-13 17:21:04 -070028#include <linux/error-injection.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070029#include <linux/hash.h>
30#include <linux/writeback.h>
Linus Torvalds53253382007-10-18 14:47:32 -070031#include <linux/backing-dev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/pagevec.h>
33#include <linux/blkdev.h>
34#include <linux/security.h>
Paul Jackson44110fe2006-03-24 03:16:04 -080035#include <linux/cpuset.h>
Johannes Weiner00501b52014-08-08 14:19:20 -070036#include <linux/hugetlb.h>
Balbir Singh8a9f3cc2008-02-07 00:13:53 -080037#include <linux/memcontrol.h>
Dan Magenheimerc515e1f2011-05-26 10:01:43 -060038#include <linux/cleancache.h>
Mel Gormanc7df8ad2017-11-15 17:37:41 -080039#include <linux/shmem_fs.h>
Kirill A. Shutemovf1820362014-04-07 15:37:19 -070040#include <linux/rmap.h>
Johannes Weinerb1d29ba2018-10-26 15:06:08 -070041#include <linux/delayacct.h>
Johannes Weinereb414682018-10-26 15:06:27 -070042#include <linux/psi.h>
Ben Dooksd0e6a582019-10-18 20:20:20 -070043#include <linux/ramfs.h>
Yang Shib9306a72020-08-06 23:19:55 -070044#include <linux/page_idle.h>
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +030045#include <asm/pgalloc.h>
Will Deaconde591a82021-02-10 11:15:11 +000046#include <asm/tlbflush.h>
Nick Piggin0f8053a2006-03-22 00:08:33 -080047#include "internal.h"
48
Robert Jarzmikfe0bfaa2013-04-29 15:06:10 -070049#define CREATE_TRACE_POINTS
50#include <trace/events/filemap.h>
51
Linus Torvalds1da177e2005-04-16 15:20:36 -070052/*
Linus Torvalds1da177e2005-04-16 15:20:36 -070053 * FIXME: remove all knowledge of the buffer layer from the core VM
54 */
Jan Kara148f9482009-08-17 19:52:36 +020055#include <linux/buffer_head.h> /* for try_to_free_buffers */
Linus Torvalds1da177e2005-04-16 15:20:36 -070056
Linus Torvalds1da177e2005-04-16 15:20:36 -070057#include <asm/mman.h>
58
59/*
60 * Shared mappings implemented 30.11.1994. It's not fully working yet,
61 * though.
62 *
63 * Shared mappings now work. 15.8.1995 Bruno.
64 *
65 * finished 'unifying' the page and buffer cache and SMP-threaded the
66 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
67 *
68 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
69 */
70
71/*
72 * Lock ordering:
73 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080074 * ->i_mmap_rwsem (truncate_pagecache)
Linus Torvalds1da177e2005-04-16 15:20:36 -070075 * ->private_lock (__free_pte->__set_page_dirty_buffers)
Hugh Dickins5d337b92005-09-03 15:54:41 -070076 * ->swap_lock (exclusive_swap_page, others)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070077 * ->i_pages lock
Linus Torvalds1da177e2005-04-16 15:20:36 -070078 *
Jan Kara96087032021-04-12 15:50:21 +020079 * ->i_rwsem
Jan Kara730633f2021-01-28 19:19:45 +010080 * ->invalidate_lock (acquired by fs in truncate path)
81 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
Linus Torvalds1da177e2005-04-16 15:20:36 -070082 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -070083 * ->mmap_lock
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080084 * ->i_mmap_rwsem
Hugh Dickinsb8072f02005-10-29 18:16:41 -070085 * ->page_table_lock or pte_lock (various, mainly in memory.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070086 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
Linus Torvalds1da177e2005-04-16 15:20:36 -070087 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -070088 * ->mmap_lock
Jan Kara730633f2021-01-28 19:19:45 +010089 * ->invalidate_lock (filemap_fault)
90 * ->lock_page (filemap_fault, access_process_vm)
Linus Torvalds1da177e2005-04-16 15:20:36 -070091 *
Jan Kara96087032021-04-12 15:50:21 +020092 * ->i_rwsem (generic_perform_write)
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -070093 * ->mmap_lock (fault_in_pages_readable->do_page_fault)
Linus Torvalds1da177e2005-04-16 15:20:36 -070094 *
Christoph Hellwigf758eea2011-04-21 18:19:44 -060095 * bdi->wb.list_lock
Dave Chinnera66979a2011-03-22 22:23:41 +110096 * sb_lock (fs/fs-writeback.c)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -070097 * ->i_pages lock (__sync_single_inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -070098 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -080099 * ->i_mmap_rwsem
Linus Torvalds1da177e2005-04-16 15:20:36 -0700100 * ->anon_vma.lock (vma_adjust)
101 *
102 * ->anon_vma.lock
Hugh Dickinsb8072f02005-10-29 18:16:41 -0700103 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700104 *
Hugh Dickinsb8072f02005-10-29 18:16:41 -0700105 * ->page_table_lock or pte_lock
Hugh Dickins5d337b92005-09-03 15:54:41 -0700106 * ->swap_lock (try_to_unmap_one)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700107 * ->private_lock (try_to_unmap_one)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700108 * ->i_pages lock (try_to_unmap_one)
Hugh Dickins15b44732020-12-15 14:21:31 -0800109 * ->lruvec->lru_lock (follow_page->mark_page_accessed)
110 * ->lruvec->lru_lock (check_pte_range->isolate_lru_page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700111 * ->private_lock (page_remove_rmap->set_page_dirty)
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700112 * ->i_pages lock (page_remove_rmap->set_page_dirty)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600113 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100114 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
Johannes Weiner81f8c3a2016-03-15 14:57:04 -0700115 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
Christoph Hellwigf758eea2011-04-21 18:19:44 -0600116 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
Dave Chinner250df6e2011-03-22 22:23:36 +1100117 * ->inode->i_lock (zap_pte_range->set_page_dirty)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700118 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
119 *
Davidlohr Buesoc8c06ef2014-12-12 16:54:24 -0800120 * ->i_mmap_rwsem
Andi Kleen9a3c5312012-03-21 16:34:09 -0700121 * ->tasklist_lock (memory_failure, collect_procs_ao)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700122 */
123
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500124static void page_cache_delete(struct address_space *mapping,
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700125 struct page *page, void *shadow)
126{
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500127 XA_STATE(xas, &mapping->i_pages, page->index);
128 unsigned int nr = 1;
Kirill A. Shutemovc70b6472016-12-12 16:43:17 -0800129
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500130 mapping_set_update(&xas, mapping);
131
132 /* hugetlb pages are represented by a single entry in the xarray */
133 if (!PageHuge(page)) {
134 xas_set_order(&xas, page->index, compound_order(page));
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -0700135 nr = compound_nr(page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500136 }
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700137
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700138 VM_BUG_ON_PAGE(!PageLocked(page), page);
139 VM_BUG_ON_PAGE(PageTail(page), page);
140 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
Johannes Weiner449dd692014-04-03 14:47:56 -0700141
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500142 xas_store(&xas, shadow);
143 xas_init_marks(&xas);
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200144
Jan Kara23006382017-11-15 17:37:26 -0800145 page->mapping = NULL;
146 /* Leave page->index set: truncation lookup relies upon it */
Johannes Weinerd3798ae2016-10-04 22:02:08 +0200147 mapping->nrpages -= nr;
Johannes Weiner91b0abe2014-04-03 14:47:49 -0700148}
149
Jan Kara5ecc4d82017-11-15 17:37:29 -0800150static void unaccount_page_cache_page(struct address_space *mapping,
151 struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700152{
Jan Kara5ecc4d82017-11-15 17:37:29 -0800153 int nr;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700154
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600155 /*
156 * if we're uptodate, flush out into the cleancache, otherwise
157 * invalidate any existing cleancache entries. We can't leave
158 * stale data around in the cleancache once our page is gone
159 */
160 if (PageUptodate(page) && PageMappedToDisk(page))
161 cleancache_put_page(page);
162 else
Dan Magenheimer31677602011-09-21 11:56:28 -0400163 cleancache_invalidate_page(mapping, page);
Dan Magenheimerc515e1f2011-05-26 10:01:43 -0600164
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700165 VM_BUG_ON_PAGE(PageTail(page), page);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800166 VM_BUG_ON_PAGE(page_mapped(page), page);
167 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
168 int mapcount;
169
170 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
171 current->comm, page_to_pfn(page));
172 dump_page(page, "still mapped when deleted");
173 dump_stack();
174 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
175
176 mapcount = page_mapcount(page);
177 if (mapping_exiting(mapping) &&
178 page_count(page) >= mapcount + 2) {
179 /*
180 * All vmas have already been torn down, so it's
181 * a good bet that actually the page is unmapped,
182 * and we'd prefer not to leak it: if we're wrong,
183 * some other bad page check should catch it later.
184 */
185 page_mapcount_reset(page);
Joonsoo Kim6d061f92016-05-19 17:10:46 -0700186 page_ref_sub(page, mapcount);
Hugh Dickins06b241f2016-03-09 14:08:07 -0800187 }
188 }
189
Jan Kara76253fb2017-11-15 17:37:22 -0800190 /* hugetlb pages do not participate in page cache accounting. */
Jan Kara5ecc4d82017-11-15 17:37:29 -0800191 if (PageHuge(page))
192 return;
Jan Kara76253fb2017-11-15 17:37:22 -0800193
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -0700194 nr = thp_nr_pages(page);
Jan Kara5ecc4d82017-11-15 17:37:29 -0800195
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700196 __mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);
Jan Kara5ecc4d82017-11-15 17:37:29 -0800197 if (PageSwapBacked(page)) {
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700198 __mod_lruvec_page_state(page, NR_SHMEM, -nr);
Jan Kara5ecc4d82017-11-15 17:37:29 -0800199 if (PageTransHuge(page))
Muchun Song57b28472021-02-24 12:03:31 -0800200 __mod_lruvec_page_state(page, NR_SHMEM_THPS, -nr);
Song Liu99cb0db2019-09-23 15:38:00 -0700201 } else if (PageTransHuge(page)) {
Muchun Songbf9ecea2021-02-24 12:03:27 -0800202 __mod_lruvec_page_state(page, NR_FILE_THPS, -nr);
Song Liu09d91cd2019-09-23 15:38:03 -0700203 filemap_nr_thps_dec(mapping);
Jan Kara76253fb2017-11-15 17:37:22 -0800204 }
Jan Kara5ecc4d82017-11-15 17:37:29 -0800205
206 /*
207 * At this point page must be either written or cleaned by
208 * truncate. Dirty page here signals a bug and loss of
209 * unwritten data.
210 *
211 * This fixes dirty accounting after removing the page entirely
212 * but leaves PageDirty set: it has no effect for truncated
213 * page and anyway will be cleared before returning page into
214 * buddy allocator.
215 */
216 if (WARN_ON_ONCE(PageDirty(page)))
217 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
218}
219
220/*
221 * Delete a page from the page cache and free it. Caller has to make
222 * sure the page is locked and that nobody else uses it - or that usage
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700223 * is safe. The caller must hold the i_pages lock.
Jan Kara5ecc4d82017-11-15 17:37:29 -0800224 */
225void __delete_from_page_cache(struct page *page, void *shadow)
226{
227 struct address_space *mapping = page->mapping;
228
229 trace_mm_filemap_delete_from_page_cache(page);
230
231 unaccount_page_cache_page(mapping, page);
Matthew Wilcox5c024e6a2017-11-21 09:17:59 -0500232 page_cache_delete(mapping, page, shadow);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700233}
234
Jan Kara59c66c52017-11-15 17:37:18 -0800235static void page_cache_free_page(struct address_space *mapping,
236 struct page *page)
237{
238 void (*freepage)(struct page *);
239
240 freepage = mapping->a_ops->freepage;
241 if (freepage)
242 freepage(page);
243
244 if (PageTransHuge(page) && !PageHuge(page)) {
Matthew Wilcox (Oracle)887b22c2020-10-15 20:05:23 -0700245 page_ref_sub(page, thp_nr_pages(page));
Jan Kara59c66c52017-11-15 17:37:18 -0800246 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
247 } else {
248 put_page(page);
249 }
250}
251
Minchan Kim702cfbf2011-03-22 16:32:43 -0700252/**
253 * delete_from_page_cache - delete page from page cache
254 * @page: the page which the kernel is trying to remove from page cache
255 *
256 * This must be called only on pages that have been verified to be in the page
257 * cache and locked. It will never put the page into the free list, the caller
258 * has a reference on the page.
259 */
260void delete_from_page_cache(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700261{
Kirill A. Shutemov83929372016-07-26 15:26:04 -0700262 struct address_space *mapping = page_mapping(page);
Greg Thelenc4843a72015-05-22 17:13:16 -0400263 unsigned long flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700264
Matt Mackallcd7619d2005-05-01 08:59:01 -0700265 BUG_ON(!PageLocked(page));
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700266 xa_lock_irqsave(&mapping->i_pages, flags);
Johannes Weiner62cccb82016-03-15 14:57:22 -0700267 __delete_from_page_cache(page, NULL);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700268 xa_unlock_irqrestore(&mapping->i_pages, flags);
Linus Torvalds6072d132010-12-01 13:35:19 -0500269
Jan Kara59c66c52017-11-15 17:37:18 -0800270 page_cache_free_page(mapping, page);
Minchan Kim97cecb52011-03-22 16:30:53 -0700271}
272EXPORT_SYMBOL(delete_from_page_cache);
273
Jan Karaaa65c292017-11-15 17:37:33 -0800274/*
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500275 * page_cache_delete_batch - delete several pages from page cache
Jan Karaaa65c292017-11-15 17:37:33 -0800276 * @mapping: the mapping to which pages belong
277 * @pvec: pagevec with pages to delete
278 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700279 * The function walks over mapping->i_pages and removes pages passed in @pvec
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700280 * from the mapping. The function expects @pvec to be sorted by page index
281 * and is optimised for it to be dense.
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700282 * It tolerates holes in @pvec (mapping entries at those indices are not
Jan Karaaa65c292017-11-15 17:37:33 -0800283 * modified). The function expects only THP head pages to be present in the
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700284 * @pvec.
Jan Karaaa65c292017-11-15 17:37:33 -0800285 *
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700286 * The function expects the i_pages lock to be held.
Jan Karaaa65c292017-11-15 17:37:33 -0800287 */
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500288static void page_cache_delete_batch(struct address_space *mapping,
Jan Karaaa65c292017-11-15 17:37:33 -0800289 struct pagevec *pvec)
290{
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500291 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
Jan Karaaa65c292017-11-15 17:37:33 -0800292 int total_pages = 0;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700293 int i = 0;
Jan Karaaa65c292017-11-15 17:37:33 -0800294 struct page *page;
Jan Karaaa65c292017-11-15 17:37:33 -0800295
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500296 mapping_set_update(&xas, mapping);
297 xas_for_each(&xas, page, ULONG_MAX) {
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700298 if (i >= pagevec_count(pvec))
Jan Karaaa65c292017-11-15 17:37:33 -0800299 break;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700300
301 /* A swap/dax/shadow entry got inserted? Skip it. */
Matthew Wilcox3159f942017-11-03 13:30:42 -0400302 if (xa_is_value(page))
Jan Karaaa65c292017-11-15 17:37:33 -0800303 continue;
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700304 /*
305 * A page got inserted in our range? Skip it. We have our
306 * pages locked so they are protected from being removed.
307 * If we see a page whose index is higher than ours, it
308 * means our page has been removed, which shouldn't be
309 * possible because we're holding the PageLock.
310 */
311 if (page != pvec->pages[i]) {
312 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
313 page);
314 continue;
Linus Torvalds69bf4b62019-07-05 19:55:18 -0700315 }
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -0700316
317 WARN_ON_ONCE(!PageLocked(page));
318
319 if (page->index == xas.xa_index)
320 page->mapping = NULL;
321 /* Leave page->index set: truncation lookup relies on it */
322
323 /*
324 * Move to the next page in the vector if this is a regular
325 * page or the index is of the last sub-page of this compound
326 * page.
327 */
328 if (page->index + compound_nr(page) - 1 == xas.xa_index)
329 i++;
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500330 xas_store(&xas, NULL);
Jan Karaaa65c292017-11-15 17:37:33 -0800331 total_pages++;
332 }
333 mapping->nrpages -= total_pages;
334}
335
336void delete_from_page_cache_batch(struct address_space *mapping,
337 struct pagevec *pvec)
338{
339 int i;
340 unsigned long flags;
341
342 if (!pagevec_count(pvec))
343 return;
344
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700345 xa_lock_irqsave(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800346 for (i = 0; i < pagevec_count(pvec); i++) {
347 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
348
349 unaccount_page_cache_page(mapping, pvec->pages[i]);
350 }
Matthew Wilcoxef8e5712017-12-04 03:59:45 -0500351 page_cache_delete_batch(mapping, pvec);
Matthew Wilcoxb93b0162018-04-10 16:36:56 -0700352 xa_unlock_irqrestore(&mapping->i_pages, flags);
Jan Karaaa65c292017-11-15 17:37:33 -0800353
354 for (i = 0; i < pagevec_count(pvec); i++)
355 page_cache_free_page(mapping, pvec->pages[i]);
356}
357
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200358int filemap_check_errors(struct address_space *mapping)
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700359{
360 int ret = 0;
361 /* Check for outstanding write errors */
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700362 if (test_bit(AS_ENOSPC, &mapping->flags) &&
363 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700364 ret = -ENOSPC;
Jens Axboe7fcbbaf2014-05-22 11:54:16 -0700365 if (test_bit(AS_EIO, &mapping->flags) &&
366 test_and_clear_bit(AS_EIO, &mapping->flags))
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700367 ret = -EIO;
368 return ret;
369}
Miklos Szeredid72d9e22016-07-29 14:10:57 +0200370EXPORT_SYMBOL(filemap_check_errors);
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700371
Jeff Layton76341ca2017-07-06 07:02:22 -0400372static int filemap_check_and_keep_errors(struct address_space *mapping)
373{
374 /* Check for outstanding write errors */
375 if (test_bit(AS_EIO, &mapping->flags))
376 return -EIO;
377 if (test_bit(AS_ENOSPC, &mapping->flags))
378 return -ENOSPC;
379 return 0;
380}
381
Linus Torvalds1da177e2005-04-16 15:20:36 -0700382/**
Randy Dunlap485bb992006-06-23 02:03:49 -0700383 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
Martin Waitz67be2dd2005-05-01 08:59:26 -0700384 * @mapping: address space structure to write
385 * @start: offset in bytes where the range starts
Andrew Morton469eb4d2006-03-24 03:17:45 -0800386 * @end: offset in bytes where the range ends (inclusive)
Martin Waitz67be2dd2005-05-01 08:59:26 -0700387 * @sync_mode: enable synchronous operation
Linus Torvalds1da177e2005-04-16 15:20:36 -0700388 *
Randy Dunlap485bb992006-06-23 02:03:49 -0700389 * Start writeback against all of a mapping's dirty pages that lie
390 * within the byte offsets <start, end> inclusive.
391 *
Linus Torvalds1da177e2005-04-16 15:20:36 -0700392 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
Randy Dunlap485bb992006-06-23 02:03:49 -0700393 * opposed to a regular memory cleansing writeback. The difference between
Linus Torvalds1da177e2005-04-16 15:20:36 -0700394 * these two operations is that if a dirty page/buffer is encountered, it must
395 * be waited upon, and not just skipped over.
Mike Rapoporta862f682019-03-05 15:48:42 -0800396 *
397 * Return: %0 on success, negative error code otherwise.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700398 */
Andrew Mortonebcf28e2006-03-24 03:18:04 -0800399int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
400 loff_t end, int sync_mode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700401{
402 int ret;
403 struct writeback_control wbc = {
404 .sync_mode = sync_mode,
Nick Piggin05fe4782009-01-06 14:39:08 -0800405 .nr_to_write = LONG_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -0700406 .range_start = start,
407 .range_end = end,
Linus Torvalds1da177e2005-04-16 15:20:36 -0700408 };
409
Christoph Hellwigf56753a2020-09-24 08:51:40 +0200410 if (!mapping_can_writeback(mapping) ||
Konstantin Khlebnikovc3aab9a02019-09-23 15:34:45 -0700411 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700412 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
Konstantin Khlebnikov875d91b2019-09-23 15:34:48 -0700620/* Returns true if writeback might be needed or already in progress. */
Jeff Layton9326c9b2017-07-26 10:21:11 -0400621static bool mapping_needs_writeback(struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700622{
Konstantin Khlebnikov875d91b2019-09-23 15:34:48 -0700623 return mapping->nrpages;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700624}
Linus Torvalds1da177e2005-04-16 15:20:36 -0700625
Randy Dunlap485bb992006-06-23 02:03:49 -0700626/**
Jens Axboe63135aa2021-04-29 22:55:18 -0700627 * filemap_range_needs_writeback - check if range potentially needs writeback
628 * @mapping: address space within which to check
629 * @start_byte: offset in bytes where the range starts
630 * @end_byte: offset in bytes where the range ends (inclusive)
631 *
632 * Find at least one page in the range supplied, usually used to check if
633 * direct writing in this range will trigger a writeback. Used by O_DIRECT
634 * read/write with IOCB_NOWAIT, to see if the caller needs to do
635 * filemap_write_and_wait_range() before proceeding.
636 *
637 * Return: %true if the caller should do filemap_write_and_wait_range() before
638 * doing O_DIRECT to a page in this range, %false otherwise.
639 */
640bool filemap_range_needs_writeback(struct address_space *mapping,
641 loff_t start_byte, loff_t end_byte)
642{
643 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
644 pgoff_t max = end_byte >> PAGE_SHIFT;
645 struct page *page;
646
647 if (!mapping_needs_writeback(mapping))
648 return false;
649 if (!mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
650 !mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK))
651 return false;
652 if (end_byte < start_byte)
653 return false;
654
655 rcu_read_lock();
656 xas_for_each(&xas, page, max) {
657 if (xas_retry(&xas, page))
658 continue;
659 if (xa_is_value(page))
660 continue;
661 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
662 break;
663 }
664 rcu_read_unlock();
665 return page != NULL;
666}
667EXPORT_SYMBOL_GPL(filemap_range_needs_writeback);
668
669/**
Randy Dunlap485bb992006-06-23 02:03:49 -0700670 * filemap_write_and_wait_range - write out & wait on a file range
671 * @mapping: the address_space for the pages
672 * @lstart: offset in bytes where the range starts
673 * @lend: offset in bytes where the range ends (inclusive)
674 *
Andrew Morton469eb4d2006-03-24 03:17:45 -0800675 * Write out and wait upon file offsets lstart->lend, inclusive.
676 *
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -0300677 * Note that @lend is inclusive (describes the last byte to be written) so
Andrew Morton469eb4d2006-03-24 03:17:45 -0800678 * that this function can be used to write to the very end-of-file (end = -1).
Mike Rapoporta862f682019-03-05 15:48:42 -0800679 *
680 * Return: error status of the address space.
Andrew Morton469eb4d2006-03-24 03:17:45 -0800681 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700682int filemap_write_and_wait_range(struct address_space *mapping,
683 loff_t lstart, loff_t lend)
684{
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800685 int err = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686
Jeff Layton9326c9b2017-07-26 10:21:11 -0400687 if (mapping_needs_writeback(mapping)) {
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800688 err = __filemap_fdatawrite_range(mapping, lstart, lend,
689 WB_SYNC_ALL);
Ira Weinyddf8f372020-01-30 22:12:07 -0800690 /*
691 * Even if the above returned error, the pages may be
692 * written partially (e.g. -ENOSPC), so we wait for it.
693 * But the -EIO is special case, it may indicate the worst
694 * thing (e.g. bug) happened, so we avoid waiting for it.
695 */
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800696 if (err != -EIO) {
Christoph Hellwig94004ed2009-09-30 22:16:33 +0200697 int err2 = filemap_fdatawait_range(mapping,
698 lstart, lend);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800699 if (!err)
700 err = err2;
Jeff Laytoncbeaf952017-07-06 07:02:23 -0400701 } else {
702 /* Clear any previously stored errors */
703 filemap_check_errors(mapping);
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800704 }
Dmitry Monakhov865ffef32013-04-29 15:08:42 -0700705 } else {
706 err = filemap_check_errors(mapping);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700707 }
OGAWA Hirofumi28fd1292006-01-08 01:02:14 -0800708 return err;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700709}
Chris Masonf6995582009-04-15 13:22:37 -0400710EXPORT_SYMBOL(filemap_write_and_wait_range);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700711
Jeff Layton5660e132017-07-06 07:02:25 -0400712void __filemap_set_wb_err(struct address_space *mapping, int err)
713{
Jeff Layton3acdfd22017-07-24 06:22:15 -0400714 errseq_t eseq = errseq_set(&mapping->wb_err, err);
Jeff Layton5660e132017-07-06 07:02:25 -0400715
716 trace_filemap_set_wb_err(mapping, eseq);
717}
718EXPORT_SYMBOL(__filemap_set_wb_err);
719
720/**
721 * file_check_and_advance_wb_err - report wb error (if any) that was previously
722 * and advance wb_err to current one
723 * @file: struct file on which the error is being reported
724 *
725 * When userland calls fsync (or something like nfsd does the equivalent), we
726 * want to report any writeback errors that occurred since the last fsync (or
727 * since the file was opened if there haven't been any).
728 *
729 * Grab the wb_err from the mapping. If it matches what we have in the file,
730 * then just quickly return 0. The file is all caught up.
731 *
732 * If it doesn't match, then take the mapping value, set the "seen" flag in
733 * it and try to swap it into place. If it works, or another task beat us
734 * to it with the new value, then update the f_wb_err and return the error
735 * portion. The error at this point must be reported via proper channels
736 * (a'la fsync, or NFS COMMIT operation, etc.).
737 *
738 * While we handle mapping->wb_err with atomic operations, the f_wb_err
739 * value is protected by the f_lock since we must ensure that it reflects
740 * the latest value swapped in for this file descriptor.
Mike Rapoporta862f682019-03-05 15:48:42 -0800741 *
742 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400743 */
744int file_check_and_advance_wb_err(struct file *file)
745{
746 int err = 0;
747 errseq_t old = READ_ONCE(file->f_wb_err);
748 struct address_space *mapping = file->f_mapping;
749
750 /* Locklessly handle the common case where nothing has changed */
751 if (errseq_check(&mapping->wb_err, old)) {
752 /* Something changed, must use slow path */
753 spin_lock(&file->f_lock);
754 old = file->f_wb_err;
755 err = errseq_check_and_advance(&mapping->wb_err,
756 &file->f_wb_err);
757 trace_file_check_and_advance_wb_err(file, old);
758 spin_unlock(&file->f_lock);
759 }
Jeff Laytonf4e222c2017-10-03 16:15:25 -0700760
761 /*
762 * We're mostly using this function as a drop in replacement for
763 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
764 * that the legacy code would have had on these flags.
765 */
766 clear_bit(AS_EIO, &mapping->flags);
767 clear_bit(AS_ENOSPC, &mapping->flags);
Jeff Layton5660e132017-07-06 07:02:25 -0400768 return err;
769}
770EXPORT_SYMBOL(file_check_and_advance_wb_err);
771
772/**
773 * file_write_and_wait_range - write out & wait on a file range
774 * @file: file pointing to address_space with pages
775 * @lstart: offset in bytes where the range starts
776 * @lend: offset in bytes where the range ends (inclusive)
777 *
778 * Write out and wait upon file offsets lstart->lend, inclusive.
779 *
780 * Note that @lend is inclusive (describes the last byte to be written) so
781 * that this function can be used to write to the very end-of-file (end = -1).
782 *
783 * After writing out and waiting on the data, we check and advance the
784 * f_wb_err cursor to the latest value, and return any errors detected there.
Mike Rapoporta862f682019-03-05 15:48:42 -0800785 *
786 * Return: %0 on success, negative error code otherwise.
Jeff Layton5660e132017-07-06 07:02:25 -0400787 */
788int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
789{
790 int err = 0, err2;
791 struct address_space *mapping = file->f_mapping;
792
Jeff Layton9326c9b2017-07-26 10:21:11 -0400793 if (mapping_needs_writeback(mapping)) {
Jeff Layton5660e132017-07-06 07:02:25 -0400794 err = __filemap_fdatawrite_range(mapping, lstart, lend,
795 WB_SYNC_ALL);
796 /* See comment of filemap_write_and_wait() */
797 if (err != -EIO)
798 __filemap_fdatawait_range(mapping, lstart, lend);
799 }
800 err2 = file_check_and_advance_wb_err(file);
801 if (!err)
802 err = err2;
803 return err;
804}
805EXPORT_SYMBOL(file_write_and_wait_range);
806
Randy Dunlap485bb992006-06-23 02:03:49 -0700807/**
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700808 * replace_page_cache_page - replace a pagecache page with a new one
809 * @old: page to be replaced
810 * @new: page to replace with
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700811 *
812 * This function replaces a page in the pagecache with a new one. On
813 * success it acquires the pagecache reference for the new page and
814 * drops it for the old page. Both the old and new pages must be
815 * locked. This function does not add the new page to the LRU, the
816 * caller must do that.
817 *
Matthew Wilcox74d60952017-11-17 10:01:45 -0500818 * The remove + add is atomic. This function cannot fail.
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700819 */
Baolin Wang1f7ef652021-02-24 12:01:42 -0800820void replace_page_cache_page(struct page *old, struct page *new)
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700821{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500822 struct address_space *mapping = old->mapping;
823 void (*freepage)(struct page *) = mapping->a_ops->freepage;
824 pgoff_t offset = old->index;
825 XA_STATE(xas, &mapping->i_pages, offset);
826 unsigned long flags;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700827
Sasha Levin309381fea2014-01-23 15:52:54 -0800828 VM_BUG_ON_PAGE(!PageLocked(old), old);
829 VM_BUG_ON_PAGE(!PageLocked(new), new);
830 VM_BUG_ON_PAGE(new->mapping, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700831
Matthew Wilcox74d60952017-11-17 10:01:45 -0500832 get_page(new);
833 new->mapping = mapping;
834 new->index = offset;
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700835
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700836 mem_cgroup_migrate(old, new);
837
Matthew Wilcox74d60952017-11-17 10:01:45 -0500838 xas_lock_irqsave(&xas, flags);
839 xas_store(&xas, new);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700840
Matthew Wilcox74d60952017-11-17 10:01:45 -0500841 old->mapping = NULL;
842 /* hugetlb pages do not participate in page cache accounting. */
843 if (!PageHuge(old))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700844 __dec_lruvec_page_state(old, NR_FILE_PAGES);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500845 if (!PageHuge(new))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700846 __inc_lruvec_page_state(new, NR_FILE_PAGES);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500847 if (PageSwapBacked(old))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700848 __dec_lruvec_page_state(old, NR_SHMEM);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500849 if (PageSwapBacked(new))
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700850 __inc_lruvec_page_state(new, NR_SHMEM);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500851 xas_unlock_irqrestore(&xas, flags);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500852 if (freepage)
853 freepage(old);
854 put_page(old);
Miklos Szeredief6a3c62011-03-22 16:30:52 -0700855}
856EXPORT_SYMBOL_GPL(replace_page_cache_page);
857
Andrew Morton16c0cc02020-12-11 13:36:27 -0800858noinline int __add_to_page_cache_locked(struct page *page,
Alexei Starovoitov76cd6172020-08-27 15:01:10 -0700859 struct address_space *mapping,
Linus Torvaldsc4cf4982020-10-16 11:31:55 -0700860 pgoff_t offset, gfp_t gfp,
Alexei Starovoitov76cd6172020-08-27 15:01:10 -0700861 void **shadowp)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700862{
Matthew Wilcox74d60952017-11-17 10:01:45 -0500863 XA_STATE(xas, &mapping->i_pages, offset);
Johannes Weiner00501b52014-08-08 14:19:20 -0700864 int huge = PageHuge(page);
Nick Piggine2867812008-07-25 19:45:30 -0700865 int error;
Waiman Longda742402021-02-04 18:32:45 -0800866 bool charged = false;
Nick Piggine2867812008-07-25 19:45:30 -0700867
Sasha Levin309381fea2014-01-23 15:52:54 -0800868 VM_BUG_ON_PAGE(!PageLocked(page), page);
869 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500870 mapping_set_update(&xas, mapping);
Nick Piggine2867812008-07-25 19:45:30 -0700871
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300872 get_page(page);
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700873 page->mapping = mapping;
874 page->index = offset;
875
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700876 if (!huge) {
Dan Schatzberg04f94e32021-06-28 19:38:18 -0700877 error = mem_cgroup_charge(page, NULL, gfp);
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700878 if (error)
879 goto error;
Waiman Longda742402021-02-04 18:32:45 -0800880 charged = true;
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700881 }
882
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700883 gfp &= GFP_RECLAIM_MASK;
884
Matthew Wilcox74d60952017-11-17 10:01:45 -0500885 do {
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700886 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
887 void *entry, *old = NULL;
888
889 if (order > thp_order(page))
890 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
891 order, gfp);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500892 xas_lock_irq(&xas);
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700893 xas_for_each_conflict(&xas, entry) {
894 old = entry;
895 if (!xa_is_value(entry)) {
896 xas_set_err(&xas, -EEXIST);
897 goto unlock;
898 }
899 }
900
901 if (old) {
902 if (shadowp)
903 *shadowp = old;
904 /* entry may have been split before we acquired lock */
905 order = xa_get_order(xas.xa, xas.xa_index);
906 if (order > thp_order(page)) {
907 xas_split(&xas, old, order);
908 xas_reset(&xas);
909 }
910 }
911
Matthew Wilcox74d60952017-11-17 10:01:45 -0500912 xas_store(&xas, page);
913 if (xas_error(&xas))
914 goto unlock;
Michal Hocko4165b9b2015-06-24 16:57:24 -0700915
Matthew Wilcox74d60952017-11-17 10:01:45 -0500916 mapping->nrpages++;
917
918 /* hugetlb pages do not participate in page cache accounting */
919 if (!huge)
Johannes Weiner0d1c2072020-06-03 16:01:54 -0700920 __inc_lruvec_page_state(page, NR_FILE_PAGES);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500921unlock:
922 xas_unlock_irq(&xas);
Matthew Wilcox (Oracle)198b62f2020-10-15 20:05:20 -0700923 } while (xas_nomem(&xas, gfp));
Matthew Wilcox74d60952017-11-17 10:01:45 -0500924
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700925 if (xas_error(&xas)) {
926 error = xas_error(&xas);
Waiman Longda742402021-02-04 18:32:45 -0800927 if (charged)
928 mem_cgroup_uncharge(page);
Matthew Wilcox74d60952017-11-17 10:01:45 -0500929 goto error;
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700930 }
Matthew Wilcox74d60952017-11-17 10:01:45 -0500931
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700932 trace_mm_filemap_add_to_page_cache(page);
933 return 0;
Matthew Wilcox74d60952017-11-17 10:01:45 -0500934error:
Kirill A. Shutemov66a0c8e2013-09-12 15:13:59 -0700935 page->mapping = NULL;
936 /* Leave page->index set: truncation relies upon it */
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +0300937 put_page(page);
Johannes Weiner3fea5a42020-06-03 16:01:41 -0700938 return error;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700939}
Josef Bacikcfcbfb12019-05-13 17:21:04 -0700940ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
Johannes Weinera5289102014-04-03 14:47:51 -0700941
942/**
943 * add_to_page_cache_locked - add a locked page to the pagecache
944 * @page: page to add
945 * @mapping: the page's address_space
946 * @offset: page index
947 * @gfp_mask: page allocation mode
948 *
949 * This function is used to add a page to the pagecache. It must be locked.
950 * This function does not add the page to the LRU. The caller must do that.
Mike Rapoporta862f682019-03-05 15:48:42 -0800951 *
952 * Return: %0 on success, negative error code otherwise.
Johannes Weinera5289102014-04-03 14:47:51 -0700953 */
954int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
955 pgoff_t offset, gfp_t gfp_mask)
956{
957 return __add_to_page_cache_locked(page, mapping, offset,
958 gfp_mask, NULL);
959}
Nick Piggine2867812008-07-25 19:45:30 -0700960EXPORT_SYMBOL(add_to_page_cache_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700961
962int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
Al Viro6daa0e22005-10-21 03:18:50 -0400963 pgoff_t offset, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700964{
Johannes Weinera5289102014-04-03 14:47:51 -0700965 void *shadow = NULL;
Rik van Riel4f98a2f2008-10-18 20:26:32 -0700966 int ret;
967
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800968 __SetPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700969 ret = __add_to_page_cache_locked(page, mapping, offset,
970 gfp_mask, &shadow);
971 if (unlikely(ret))
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -0800972 __ClearPageLocked(page);
Johannes Weinera5289102014-04-03 14:47:51 -0700973 else {
974 /*
975 * The page might have been evicted from cache only
976 * recently, in which case it should be activated like
977 * any other repeatedly accessed page.
Rik van Rielf0281a02016-05-20 16:56:25 -0700978 * The exception is pages getting rewritten; evicting other
979 * data from the working set, only to cache data that will
980 * get overwritten with something else, is a waste of memory.
Johannes Weinera5289102014-04-03 14:47:51 -0700981 */
Johannes Weiner1899ad12018-10-26 15:06:04 -0700982 WARN_ON_ONCE(PageActive(page));
983 if (!(gfp_mask & __GFP_WRITE) && shadow)
984 workingset_refault(page, shadow);
Johannes Weinera5289102014-04-03 14:47:51 -0700985 lru_cache_add(page);
986 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987 return ret;
988}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +0300989EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700990
Paul Jackson44110fe2006-03-24 03:16:04 -0800991#ifdef CONFIG_NUMA
Nick Piggin2ae88142006-10-28 10:38:23 -0700992struct page *__page_cache_alloc(gfp_t gfp)
Paul Jackson44110fe2006-03-24 03:16:04 -0800993{
Miao Xiec0ff7452010-05-24 14:32:08 -0700994 int n;
995 struct page *page;
996
Paul Jackson44110fe2006-03-24 03:16:04 -0800997 if (cpuset_do_page_mem_spread()) {
Mel Gormancc9a6c82012-03-21 16:34:11 -0700998 unsigned int cpuset_mems_cookie;
999 do {
Mel Gormand26914d2014-04-03 14:47:24 -07001000 cpuset_mems_cookie = read_mems_allowed_begin();
Mel Gormancc9a6c82012-03-21 16:34:11 -07001001 n = cpuset_mem_spread_node();
Vlastimil Babka96db8002015-09-08 15:03:50 -07001002 page = __alloc_pages_node(n, gfp, 0);
Mel Gormand26914d2014-04-03 14:47:24 -07001003 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
Mel Gormancc9a6c82012-03-21 16:34:11 -07001004
Miao Xiec0ff7452010-05-24 14:32:08 -07001005 return page;
Paul Jackson44110fe2006-03-24 03:16:04 -08001006 }
Nick Piggin2ae88142006-10-28 10:38:23 -07001007 return alloc_pages(gfp, 0);
Paul Jackson44110fe2006-03-24 03:16:04 -08001008}
Nick Piggin2ae88142006-10-28 10:38:23 -07001009EXPORT_SYMBOL(__page_cache_alloc);
Paul Jackson44110fe2006-03-24 03:16:04 -08001010#endif
1011
Linus Torvalds1da177e2005-04-16 15:20:36 -07001012/*
1013 * In order to wait for pages to become available there must be
1014 * waitqueues associated with pages. By using a hash table of
1015 * waitqueues where the bucket discipline is to maintain all
1016 * waiters on the same queue and wake all when any of the pages
1017 * become available, and for the woken contexts to check to be
1018 * sure the appropriate page became available, this saves space
1019 * at a cost of "thundering herd" phenomena during rare hash
1020 * collisions.
1021 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001022#define PAGE_WAIT_TABLE_BITS 8
1023#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1024static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1025
1026static wait_queue_head_t *page_waitqueue(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027{
Nicholas Piggin62906022016-12-25 13:00:30 +10001028 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
Linus Torvalds1da177e2005-04-16 15:20:36 -07001029}
Nicholas Piggin62906022016-12-25 13:00:30 +10001030
1031void __init pagecache_init(void)
1032{
1033 int i;
1034
1035 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1036 init_waitqueue_head(&page_wait_table[i]);
1037
1038 page_writeback_init();
1039}
1040
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001041/*
1042 * The page wait code treats the "wait->flags" somewhat unusually, because
Linus Torvalds5868ec22020-09-20 10:38:47 -07001043 * we have multiple different kinds of waits, not just the usual "exclusive"
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001044 * one.
1045 *
1046 * We have:
1047 *
1048 * (a) no special bits set:
1049 *
1050 * We're just waiting for the bit to be released, and when a waker
1051 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1052 * and remove it from the wait queue.
1053 *
1054 * Simple and straightforward.
1055 *
1056 * (b) WQ_FLAG_EXCLUSIVE:
1057 *
1058 * The waiter is waiting to get the lock, and only one waiter should
1059 * be woken up to avoid any thundering herd behavior. We'll set the
1060 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1061 *
1062 * This is the traditional exclusive wait.
1063 *
Linus Torvalds5868ec22020-09-20 10:38:47 -07001064 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001065 *
1066 * The waiter is waiting to get the bit, and additionally wants the
1067 * lock to be transferred to it for fair lock behavior. If the lock
1068 * cannot be taken, we stop walking the wait queue without waking
1069 * the waiter.
1070 *
1071 * This is the "fair lock handoff" case, and in addition to setting
1072 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1073 * that it now has the lock.
1074 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001075static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
Nicholas Piggin62906022016-12-25 13:00:30 +10001076{
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001077 unsigned int flags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001078 struct wait_page_key *key = arg;
1079 struct wait_page_queue *wait_page
1080 = container_of(wait, struct wait_page_queue, wait);
1081
Linus Torvaldscdc8fcb2020-08-03 13:01:22 -07001082 if (!wake_page_match(wait_page, key))
Nicholas Piggin62906022016-12-25 13:00:30 +10001083 return 0;
Linus Torvalds3510ca22017-08-27 13:55:12 -07001084
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001085 /*
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001086 * If it's a lock handoff wait, we get the bit for it, and
1087 * stop walking (and do not wake it up) if we can't.
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001088 */
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001089 flags = wait->flags;
1090 if (flags & WQ_FLAG_EXCLUSIVE) {
1091 if (test_bit(key->bit_nr, &key->page->flags))
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001092 return -1;
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001093 if (flags & WQ_FLAG_CUSTOM) {
1094 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1095 return -1;
1096 flags |= WQ_FLAG_DONE;
1097 }
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001098 }
Nicholas Piggin62906022016-12-25 13:00:30 +10001099
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001100 /*
1101 * We are holding the wait-queue lock, but the waiter that
1102 * is waiting for this will be checking the flags without
1103 * any locking.
1104 *
1105 * So update the flags atomically, and wake up the waiter
1106 * afterwards to avoid any races. This store-release pairs
1107 * with the load-acquire in wait_on_page_bit_common().
1108 */
1109 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001110 wake_up_state(wait->private, mode);
1111
1112 /*
1113 * Ok, we have successfully done what we're waiting for,
1114 * and we can unconditionally remove the wait entry.
1115 *
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001116 * Note that this pairs with the "finish_wait()" in the
1117 * waiter, and has to be the absolute last thing we do.
1118 * After this list_del_init(&wait->entry) the wait entry
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001119 * might be de-allocated and the process might even have
1120 * exited.
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001121 */
Linus Torvaldsc6fe44d2020-07-23 12:33:41 -07001122 list_del_init_careful(&wait->entry);
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001123 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
Nicholas Piggin62906022016-12-25 13:00:30 +10001124}
1125
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001126static void wake_up_page_bit(struct page *page, int bit_nr)
Nicholas Piggin62906022016-12-25 13:00:30 +10001127{
1128 wait_queue_head_t *q = page_waitqueue(page);
1129 struct wait_page_key key;
1130 unsigned long flags;
Tim Chen11a19c72017-08-25 09:13:55 -07001131 wait_queue_entry_t bookmark;
Nicholas Piggin62906022016-12-25 13:00:30 +10001132
1133 key.page = page;
1134 key.bit_nr = bit_nr;
1135 key.page_match = 0;
1136
Tim Chen11a19c72017-08-25 09:13:55 -07001137 bookmark.flags = 0;
1138 bookmark.private = NULL;
1139 bookmark.func = NULL;
1140 INIT_LIST_HEAD(&bookmark.entry);
1141
Nicholas Piggin62906022016-12-25 13:00:30 +10001142 spin_lock_irqsave(&q->lock, flags);
Tim Chen11a19c72017-08-25 09:13:55 -07001143 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1144
1145 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1146 /*
1147 * Take a breather from holding the lock,
1148 * allow pages that finish wake up asynchronously
1149 * to acquire the lock and remove themselves
1150 * from wait queue
1151 */
1152 spin_unlock_irqrestore(&q->lock, flags);
1153 cpu_relax();
1154 spin_lock_irqsave(&q->lock, flags);
1155 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1156 }
1157
Nicholas Piggin62906022016-12-25 13:00:30 +10001158 /*
1159 * It is possible for other pages to have collided on the waitqueue
1160 * hash, so in that case check for a page match. That prevents a long-
1161 * term waiter
1162 *
1163 * It is still possible to miss a case here, when we woke page waiters
1164 * and removed them from the waitqueue, but there are still other
1165 * page waiters.
1166 */
1167 if (!waitqueue_active(q) || !key.page_match) {
1168 ClearPageWaiters(page);
1169 /*
1170 * It's possible to miss clearing Waiters here, when we woke
1171 * our page waiters, but the hashed waitqueue has waiters for
1172 * other pages on it.
1173 *
1174 * That's okay, it's a rare case. The next waker will clear it.
1175 */
1176 }
1177 spin_unlock_irqrestore(&q->lock, flags);
1178}
Nicholas Piggin74d81bf2017-02-22 15:44:41 -08001179
1180static void wake_up_page(struct page *page, int bit)
1181{
1182 if (!PageWaiters(page))
1183 return;
1184 wake_up_page_bit(page, bit);
1185}
Nicholas Piggin62906022016-12-25 13:00:30 +10001186
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001187/*
1188 * A choice of three behaviors for wait_on_page_bit_common():
1189 */
1190enum behavior {
1191 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1192 * __lock_page() waiting on then setting PG_locked.
1193 */
1194 SHARED, /* Hold ref to page and check the bit when woken, like
1195 * wait_on_page_writeback() waiting on PG_writeback.
1196 */
1197 DROP, /* Drop ref to page before wait, no check when woken,
1198 * like put_and_wait_on_page_locked() on PG_locked.
1199 */
1200};
1201
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001202/*
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001203 * Attempt to check (or get) the page bit, and mark us done
1204 * if successful.
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001205 */
1206static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1207 struct wait_queue_entry *wait)
1208{
1209 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1210 if (test_and_set_bit(bit_nr, &page->flags))
1211 return false;
1212 } else if (test_bit(bit_nr, &page->flags))
1213 return false;
1214
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001215 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001216 return true;
1217}
1218
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001219/* How many times do we accept lock stealing from under a waiter? */
1220int sysctl_page_lock_unfairness = 5;
1221
Nicholas Piggin62906022016-12-25 13:00:30 +10001222static inline int wait_on_page_bit_common(wait_queue_head_t *q,
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001223 struct page *page, int bit_nr, int state, enum behavior behavior)
Nicholas Piggin62906022016-12-25 13:00:30 +10001224{
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001225 int unfairness = sysctl_page_lock_unfairness;
Nicholas Piggin62906022016-12-25 13:00:30 +10001226 struct wait_page_queue wait_page;
Ingo Molnarac6424b2017-06-20 12:06:13 +02001227 wait_queue_entry_t *wait = &wait_page.wait;
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001228 bool thrashing = false;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001229 bool delayacct = false;
Johannes Weinereb414682018-10-26 15:06:27 -07001230 unsigned long pflags;
Nicholas Piggin62906022016-12-25 13:00:30 +10001231
Johannes Weinereb414682018-10-26 15:06:27 -07001232 if (bit_nr == PG_locked &&
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001233 !PageUptodate(page) && PageWorkingset(page)) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001234 if (!PageSwapBacked(page)) {
Johannes Weinereb414682018-10-26 15:06:27 -07001235 delayacct_thrashing_start();
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001236 delayacct = true;
1237 }
Johannes Weinereb414682018-10-26 15:06:27 -07001238 psi_memstall_enter(&pflags);
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001239 thrashing = true;
1240 }
1241
Nicholas Piggin62906022016-12-25 13:00:30 +10001242 init_wait(wait);
1243 wait->func = wake_page_function;
1244 wait_page.page = page;
1245 wait_page.bit_nr = bit_nr;
1246
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001247repeat:
1248 wait->flags = 0;
1249 if (behavior == EXCLUSIVE) {
1250 wait->flags = WQ_FLAG_EXCLUSIVE;
1251 if (--unfairness < 0)
1252 wait->flags |= WQ_FLAG_CUSTOM;
1253 }
1254
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001255 /*
1256 * Do one last check whether we can get the
1257 * page bit synchronously.
1258 *
1259 * Do the SetPageWaiters() marking before that
1260 * to let any waker we _just_ missed know they
1261 * need to wake us up (otherwise they'll never
1262 * even go to the slow case that looks at the
1263 * page queue), and add ourselves to the wait
1264 * queue if we need to sleep.
1265 *
1266 * This part needs to be done under the queue
1267 * lock to avoid races.
1268 */
1269 spin_lock_irq(&q->lock);
1270 SetPageWaiters(page);
1271 if (!trylock_page_bit_common(page, bit_nr, wait))
1272 __add_wait_queue_entry_tail(q, wait);
1273 spin_unlock_irq(&q->lock);
1274
1275 /*
1276 * From now on, all the logic will be based on
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001277 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1278 * see whether the page bit testing has already
1279 * been done by the wake function.
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001280 *
1281 * We can drop our reference to the page.
1282 */
1283 if (behavior == DROP)
1284 put_page(page);
1285
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001286 /*
1287 * Note that until the "finish_wait()", or until
1288 * we see the WQ_FLAG_WOKEN flag, we need to
1289 * be very careful with the 'wait->flags', because
1290 * we may race with a waker that sets them.
1291 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001292 for (;;) {
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001293 unsigned int flags;
1294
Nicholas Piggin62906022016-12-25 13:00:30 +10001295 set_current_state(state);
1296
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001297 /* Loop until we've been woken or interrupted */
1298 flags = smp_load_acquire(&wait->flags);
1299 if (!(flags & WQ_FLAG_WOKEN)) {
1300 if (signal_pending_state(state, current))
1301 break;
1302
1303 io_schedule();
1304 continue;
1305 }
1306
1307 /* If we were non-exclusive, we're done */
1308 if (behavior != EXCLUSIVE)
Linus Torvaldsa8b169a2017-08-27 16:25:09 -07001309 break;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001310
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001311 /* If the waker got the lock for us, we're done */
1312 if (flags & WQ_FLAG_DONE)
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001313 break;
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001314
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001315 /*
1316 * Otherwise, if we're getting the lock, we need to
1317 * try to get it ourselves.
1318 *
1319 * And if that fails, we'll have to retry this all.
1320 */
1321 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1322 goto repeat;
1323
1324 wait->flags |= WQ_FLAG_DONE;
1325 break;
Nicholas Piggin62906022016-12-25 13:00:30 +10001326 }
1327
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001328 /*
1329 * If a signal happened, this 'finish_wait()' may remove the last
1330 * waiter from the wait-queues, but the PageWaiters bit will remain
1331 * set. That's ok. The next wakeup will take care of it, and trying
1332 * to do it here would be difficult and prone to races.
1333 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001334 finish_wait(q, wait);
1335
Johannes Weinereb414682018-10-26 15:06:27 -07001336 if (thrashing) {
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001337 if (delayacct)
Johannes Weinereb414682018-10-26 15:06:27 -07001338 delayacct_thrashing_end();
1339 psi_memstall_leave(&pflags);
1340 }
Johannes Weinerb1d29ba2018-10-26 15:06:08 -07001341
Nicholas Piggin62906022016-12-25 13:00:30 +10001342 /*
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001343 * NOTE! The wait->flags weren't stable until we've done the
1344 * 'finish_wait()', and we could have exited the loop above due
1345 * to a signal, and had a wakeup event happen after the signal
1346 * test but before the 'finish_wait()'.
1347 *
1348 * So only after the finish_wait() can we reliably determine
1349 * if we got woken up or not, so we can now figure out the final
1350 * return value based on that state without races.
1351 *
1352 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1353 * waiter, but an exclusive one requires WQ_FLAG_DONE.
Nicholas Piggin62906022016-12-25 13:00:30 +10001354 */
Linus Torvalds5ef64cc2020-09-13 14:05:35 -07001355 if (behavior == EXCLUSIVE)
1356 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
Nicholas Piggin62906022016-12-25 13:00:30 +10001357
Linus Torvalds2a9127f2020-07-23 10:16:49 -07001358 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
Nicholas Piggin62906022016-12-25 13:00:30 +10001359}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001360
Harvey Harrison920c7a52008-02-04 22:29:26 -08001361void wait_on_page_bit(struct page *page, int bit_nr)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001362{
Nicholas Piggin62906022016-12-25 13:00:30 +10001363 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001364 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001365}
1366EXPORT_SYMBOL(wait_on_page_bit);
1367
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001368int wait_on_page_bit_killable(struct page *page, int bit_nr)
1369{
Nicholas Piggin62906022016-12-25 13:00:30 +10001370 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001371 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001372}
David Howells4343d002017-11-02 15:27:52 +00001373EXPORT_SYMBOL(wait_on_page_bit_killable);
KOSAKI Motohirof62e00c2011-05-24 17:11:29 -07001374
Linus Torvalds1da177e2005-04-16 15:20:36 -07001375/**
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001376 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1377 * @page: The page to wait for.
Matthew Wilcox (Oracle)48054622021-02-24 12:02:02 -08001378 * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001379 *
1380 * The caller should hold a reference on @page. They expect the page to
1381 * become unlocked relatively soon, but do not wish to hold up migration
1382 * (for example) by holding the reference while waiting for the page to
1383 * come unlocked. After this function returns, the caller should not
1384 * dereference @page.
Matthew Wilcox (Oracle)48054622021-02-24 12:02:02 -08001385 *
1386 * Return: 0 if the page was unlocked or -EINTR if interrupted by a signal.
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001387 */
Matthew Wilcox (Oracle)48054622021-02-24 12:02:02 -08001388int put_and_wait_on_page_locked(struct page *page, int state)
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001389{
1390 wait_queue_head_t *q;
1391
1392 page = compound_head(page);
1393 q = page_waitqueue(page);
Matthew Wilcox (Oracle)48054622021-02-24 12:02:02 -08001394 return wait_on_page_bit_common(q, page, PG_locked, state, DROP);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001395}
1396
1397/**
David Howells385e1ca5f2009-04-03 16:42:39 +01001398 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
Randy Dunlap697f6192009-04-13 14:39:54 -07001399 * @page: Page defining the wait queue of interest
1400 * @waiter: Waiter to add to the queue
David Howells385e1ca5f2009-04-03 16:42:39 +01001401 *
1402 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1403 */
Ingo Molnarac6424b2017-06-20 12:06:13 +02001404void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
David Howells385e1ca5f2009-04-03 16:42:39 +01001405{
1406 wait_queue_head_t *q = page_waitqueue(page);
1407 unsigned long flags;
1408
1409 spin_lock_irqsave(&q->lock, flags);
Linus Torvalds9c3a8152017-08-28 16:45:40 -07001410 __add_wait_queue_entry_tail(q, waiter);
Nicholas Piggin62906022016-12-25 13:00:30 +10001411 SetPageWaiters(page);
David Howells385e1ca5f2009-04-03 16:42:39 +01001412 spin_unlock_irqrestore(&q->lock, flags);
1413}
1414EXPORT_SYMBOL_GPL(add_page_wait_queue);
1415
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001416#ifndef clear_bit_unlock_is_negative_byte
1417
1418/*
1419 * PG_waiters is the high bit in the same byte as PG_lock.
1420 *
1421 * On x86 (and on many other architectures), we can clear PG_lock and
1422 * test the sign bit at the same time. But if the architecture does
1423 * not support that special operation, we just do this all by hand
1424 * instead.
1425 *
1426 * The read of PG_waiters has to be after (or concurrently with) PG_locked
Ethon Paulffceeb62020-06-04 16:49:22 -07001427 * being cleared, but a memory barrier should be unnecessary since it is
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001428 * in the same byte as PG_locked.
1429 */
1430static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1431{
1432 clear_bit_unlock(nr, mem);
1433 /* smp_mb__after_atomic(); */
Olof Johansson98473f92016-12-29 14:16:07 -08001434 return test_bit(PG_waiters, mem);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001435}
1436
1437#endif
1438
David Howells385e1ca5f2009-04-03 16:42:39 +01001439/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001440 * unlock_page - unlock a locked page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001441 * @page: the page
1442 *
Miaohe Lin0e9aa672020-10-15 20:09:58 -07001443 * Unlocks the page and wakes up sleepers in wait_on_page_locked().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001444 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
Masanari Iidada3dae52014-09-09 01:27:23 +09001445 * mechanism between PageLocked pages and PageWriteback pages is shared.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001446 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1447 *
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001448 * Note that this depends on PG_waiters being the sign bit in the byte
1449 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1450 * clear the PG_locked bit and test PG_waiters at the same time fairly
1451 * portably (architectures that do LL/SC can test any bit, while x86 can
1452 * test the sign bit).
Linus Torvalds1da177e2005-04-16 15:20:36 -07001453 */
Harvey Harrison920c7a52008-02-04 22:29:26 -08001454void unlock_page(struct page *page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455{
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001456 BUILD_BUG_ON(PG_waiters != 7);
Kirill A. Shutemov48c935a2016-01-15 16:51:24 -08001457 page = compound_head(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001458 VM_BUG_ON_PAGE(!PageLocked(page), page);
Linus Torvaldsb91e1302016-12-27 11:40:38 -08001459 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1460 wake_up_page_bit(page, PG_locked);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001461}
1462EXPORT_SYMBOL(unlock_page);
1463
Randy Dunlap485bb992006-06-23 02:03:49 -07001464/**
David Howells73e10de2020-02-10 10:00:21 +00001465 * end_page_private_2 - Clear PG_private_2 and release any waiters
1466 * @page: The page
1467 *
1468 * Clear the PG_private_2 bit on a page and wake up any sleepers waiting for
1469 * this. The page ref held for PG_private_2 being set is released.
1470 *
1471 * This is, for example, used when a netfs page is being written to a local
1472 * disk cache, thereby allowing writes to the cache for the same page to be
1473 * serialised.
1474 */
1475void end_page_private_2(struct page *page)
1476{
1477 page = compound_head(page);
1478 VM_BUG_ON_PAGE(!PagePrivate2(page), page);
1479 clear_bit_unlock(PG_private_2, &page->flags);
1480 wake_up_page_bit(page, PG_private_2);
1481 put_page(page);
1482}
1483EXPORT_SYMBOL(end_page_private_2);
1484
1485/**
1486 * wait_on_page_private_2 - Wait for PG_private_2 to be cleared on a page
1487 * @page: The page to wait on
1488 *
1489 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page.
1490 */
1491void wait_on_page_private_2(struct page *page)
1492{
1493 page = compound_head(page);
1494 while (PagePrivate2(page))
1495 wait_on_page_bit(page, PG_private_2);
1496}
1497EXPORT_SYMBOL(wait_on_page_private_2);
1498
1499/**
1500 * wait_on_page_private_2_killable - Wait for PG_private_2 to be cleared on a page
1501 * @page: The page to wait on
1502 *
1503 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page or until a
1504 * fatal signal is received by the calling task.
1505 *
1506 * Return:
1507 * - 0 if successful.
1508 * - -EINTR if a fatal signal was encountered.
1509 */
1510int wait_on_page_private_2_killable(struct page *page)
1511{
1512 int ret = 0;
1513
1514 page = compound_head(page);
1515 while (PagePrivate2(page)) {
1516 ret = wait_on_page_bit_killable(page, PG_private_2);
1517 if (ret < 0)
1518 break;
1519 }
1520
1521 return ret;
1522}
1523EXPORT_SYMBOL(wait_on_page_private_2_killable);
1524
1525/**
Randy Dunlap485bb992006-06-23 02:03:49 -07001526 * end_page_writeback - end writeback against a page
1527 * @page: the page
Linus Torvalds1da177e2005-04-16 15:20:36 -07001528 */
1529void end_page_writeback(struct page *page)
1530{
Mel Gorman888cf2d2014-06-04 16:10:34 -07001531 /*
1532 * TestClearPageReclaim could be used here but it is an atomic
1533 * operation and overkill in this particular case. Failing to
1534 * shuffle a page marked for immediate reclaim is too mild to
1535 * justify taking an atomic operation penalty at the end of
1536 * ever page writeback.
1537 */
1538 if (PageReclaim(page)) {
1539 ClearPageReclaim(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001540 rotate_reclaimable_page(page);
Mel Gorman888cf2d2014-06-04 16:10:34 -07001541 }
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001542
Hugh Dickins073861e2020-11-24 08:46:43 -08001543 /*
1544 * Writeback does not hold a page reference of its own, relying
1545 * on truncation to wait for the clearing of PG_writeback.
1546 * But here we must make sure that the page is not freed and
1547 * reused before the wake_up_page().
1548 */
1549 get_page(page);
Miklos Szerediac6aadb2008-04-28 02:12:38 -07001550 if (!test_clear_page_writeback(page))
1551 BUG();
1552
Peter Zijlstra4e857c52014-03-17 18:06:10 +01001553 smp_mb__after_atomic();
Linus Torvalds1da177e2005-04-16 15:20:36 -07001554 wake_up_page(page, PG_writeback);
Hugh Dickins073861e2020-11-24 08:46:43 -08001555 put_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556}
1557EXPORT_SYMBOL(end_page_writeback);
1558
Matthew Wilcox57d99842014-06-04 16:07:45 -07001559/*
1560 * After completing I/O on a page, call this routine to update the page
1561 * flags appropriately
1562 */
Jens Axboec11f0c02016-08-05 08:11:04 -06001563void page_endio(struct page *page, bool is_write, int err)
Matthew Wilcox57d99842014-06-04 16:07:45 -07001564{
Jens Axboec11f0c02016-08-05 08:11:04 -06001565 if (!is_write) {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001566 if (!err) {
1567 SetPageUptodate(page);
1568 } else {
1569 ClearPageUptodate(page);
1570 SetPageError(page);
1571 }
1572 unlock_page(page);
Mike Christieabf54542016-08-04 14:23:34 -06001573 } else {
Matthew Wilcox57d99842014-06-04 16:07:45 -07001574 if (err) {
Minchan Kimdd8416c2017-02-24 14:59:59 -08001575 struct address_space *mapping;
1576
Matthew Wilcox57d99842014-06-04 16:07:45 -07001577 SetPageError(page);
Minchan Kimdd8416c2017-02-24 14:59:59 -08001578 mapping = page_mapping(page);
1579 if (mapping)
1580 mapping_set_error(mapping, err);
Matthew Wilcox57d99842014-06-04 16:07:45 -07001581 }
1582 end_page_writeback(page);
1583 }
1584}
1585EXPORT_SYMBOL_GPL(page_endio);
1586
Randy Dunlap485bb992006-06-23 02:03:49 -07001587/**
1588 * __lock_page - get a lock on the page, assuming we need to sleep to get it
Randy Dunlap87066752017-02-22 15:44:44 -08001589 * @__page: the page to lock
Linus Torvalds1da177e2005-04-16 15:20:36 -07001590 */
Nicholas Piggin62906022016-12-25 13:00:30 +10001591void __lock_page(struct page *__page)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001592{
Nicholas Piggin62906022016-12-25 13:00:30 +10001593 struct page *page = compound_head(__page);
1594 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001595 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1596 EXCLUSIVE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001597}
1598EXPORT_SYMBOL(__lock_page);
1599
Nicholas Piggin62906022016-12-25 13:00:30 +10001600int __lock_page_killable(struct page *__page)
Matthew Wilcox2687a352007-12-06 11:18:49 -05001601{
Nicholas Piggin62906022016-12-25 13:00:30 +10001602 struct page *page = compound_head(__page);
1603 wait_queue_head_t *q = page_waitqueue(page);
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001604 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1605 EXCLUSIVE);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001606}
Evgeniy Polyakov18bc0bb2009-02-09 17:02:42 +03001607EXPORT_SYMBOL_GPL(__lock_page_killable);
Matthew Wilcox2687a352007-12-06 11:18:49 -05001608
Jens Axboedd3e6d52020-05-22 09:12:09 -06001609int __lock_page_async(struct page *page, struct wait_page_queue *wait)
1610{
Matthew Wilcox (Oracle)f32b5dd2021-02-24 12:02:09 -08001611 struct wait_queue_head *q = page_waitqueue(page);
1612 int ret = 0;
1613
1614 wait->page = page;
1615 wait->bit_nr = PG_locked;
1616
1617 spin_lock_irq(&q->lock);
1618 __add_wait_queue_entry_tail(q, &wait->wait);
1619 SetPageWaiters(page);
1620 ret = !trylock_page(page);
1621 /*
1622 * If we were successful now, we know we're still on the
1623 * waitqueue as we're still under the lock. This means it's
1624 * safe to remove and return success, we know the callback
1625 * isn't going to trigger.
1626 */
1627 if (!ret)
1628 __remove_wait_queue(q, &wait->wait);
1629 else
1630 ret = -EIOCBQUEUED;
1631 spin_unlock_irq(&q->lock);
1632 return ret;
Jens Axboedd3e6d52020-05-22 09:12:09 -06001633}
1634
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001635/*
1636 * Return values:
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001637 * 1 - page is locked; mmap_lock is still held.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001638 * 0 - page is not locked.
Michel Lespinasse3e4e28c2020-06-08 21:33:51 -07001639 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001640 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001641 * which case mmap_lock is still held.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001642 *
1643 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001644 * with the page locked and the mmap_lock unperturbed.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07001645 */
Michel Lespinassed065bd82010-10-26 14:21:57 -07001646int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1647 unsigned int flags)
1648{
Peter Xu4064b982020-04-01 21:08:45 -07001649 if (fault_flag_allow_retry_first(flags)) {
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001650 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07001651 * CAUTION! In this case, mmap_lock is not released
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001652 * even though return 0.
1653 */
1654 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1655 return 0;
1656
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001657 mmap_read_unlock(mm);
KOSAKI Motohiro37b23e02011-05-24 17:11:30 -07001658 if (flags & FAULT_FLAG_KILLABLE)
1659 wait_on_page_locked_killable(page);
1660 else
Gleb Natapov318b2752011-03-22 16:30:51 -07001661 wait_on_page_locked(page);
Michel Lespinassed065bd82010-10-26 14:21:57 -07001662 return 0;
1663 }
Hailong Liu800bca72020-12-14 19:05:02 -08001664 if (flags & FAULT_FLAG_KILLABLE) {
1665 int ret;
1666
1667 ret = __lock_page_killable(page);
1668 if (ret) {
1669 mmap_read_unlock(mm);
1670 return 0;
1671 }
1672 } else {
1673 __lock_page(page);
1674 }
1675 return 1;
1676
Michel Lespinassed065bd82010-10-26 14:21:57 -07001677}
1678
Randy Dunlap485bb992006-06-23 02:03:49 -07001679/**
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001680 * page_cache_next_miss() - Find the next gap in the page cache.
1681 * @mapping: Mapping.
1682 * @index: Index.
1683 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001684 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001685 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1686 * gap with the lowest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001687 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001688 * This function may be called under the rcu_read_lock. However, this will
1689 * not atomically search a snapshot of the cache at a single point in time.
1690 * For example, if a gap is created at index 5, then subsequently a gap is
1691 * created at index 10, page_cache_next_miss covering both indices may
1692 * return 10 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001693 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001694 * Return: The index of the gap if found, otherwise an index outside the
1695 * range specified (in which case 'return - index >= max_scan' will be true).
1696 * In the rare case of index wrap-around, 0 will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001697 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001698pgoff_t page_cache_next_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001699 pgoff_t index, unsigned long max_scan)
1700{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001701 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001702
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001703 while (max_scan--) {
1704 void *entry = xas_next(&xas);
1705 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001706 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001707 if (xas.xa_index == 0)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001708 break;
1709 }
1710
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001711 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001712}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001713EXPORT_SYMBOL(page_cache_next_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001714
1715/**
Laurent Dufour2346a562019-05-13 17:21:29 -07001716 * page_cache_prev_miss() - Find the previous gap in the page cache.
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001717 * @mapping: Mapping.
1718 * @index: Index.
1719 * @max_scan: Maximum range to search.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001720 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001721 * Search the range [max(index - max_scan + 1, 0), index] for the
1722 * gap with the highest index.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001723 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001724 * This function may be called under the rcu_read_lock. However, this will
1725 * not atomically search a snapshot of the cache at a single point in time.
1726 * For example, if a gap is created at index 10, then subsequently a gap is
1727 * created at index 5, page_cache_prev_miss() covering both indices may
1728 * return 5 if called under the rcu_read_lock.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001729 *
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001730 * Return: The index of the gap if found, otherwise an index outside the
1731 * range specified (in which case 'index - return >= max_scan' will be true).
1732 * In the rare case of wrap-around, ULONG_MAX will be returned.
Johannes Weinere7b563b2014-04-03 14:47:44 -07001733 */
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001734pgoff_t page_cache_prev_miss(struct address_space *mapping,
Johannes Weinere7b563b2014-04-03 14:47:44 -07001735 pgoff_t index, unsigned long max_scan)
1736{
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001737 XA_STATE(xas, &mapping->i_pages, index);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001738
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001739 while (max_scan--) {
1740 void *entry = xas_prev(&xas);
1741 if (!entry || xa_is_value(entry))
Johannes Weinere7b563b2014-04-03 14:47:44 -07001742 break;
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001743 if (xas.xa_index == ULONG_MAX)
Johannes Weinere7b563b2014-04-03 14:47:44 -07001744 break;
1745 }
1746
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001747 return xas.xa_index;
Johannes Weinere7b563b2014-04-03 14:47:44 -07001748}
Matthew Wilcox0d3f9292017-11-21 14:07:06 -05001749EXPORT_SYMBOL(page_cache_prev_miss);
Johannes Weinere7b563b2014-04-03 14:47:44 -07001750
Matthew Wilcox (Oracle)44835d22021-02-25 17:15:36 -08001751/*
Matthew Wilcox (Oracle)bc5a3012021-02-25 17:15:40 -08001752 * mapping_get_entry - Get a page cache entry.
Randy Dunlap485bb992006-06-23 02:03:49 -07001753 * @mapping: the address_space to search
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001754 * @index: The page cache index.
Randy Dunlap485bb992006-06-23 02:03:49 -07001755 *
Rui Sun4b17f032021-04-29 22:55:38 -07001756 * Looks up the page cache slot at @mapping & @index. If there is a
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001757 * page cache page, the head page is returned with an increased refcount.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001758 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001759 * If the slot holds a shadow entry of a previously evicted page, or a
1760 * swap entry from shmem/tmpfs, it is returned.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001761 *
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001762 * Return: The head page or shadow entry, %NULL if nothing is found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001763 */
Matthew Wilcox (Oracle)bc5a3012021-02-25 17:15:40 -08001764static struct page *mapping_get_entry(struct address_space *mapping,
1765 pgoff_t index)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001766{
Matthew Wilcox (Oracle)a6de4b42020-10-13 16:51:34 -07001767 XA_STATE(xas, &mapping->i_pages, index);
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001768 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001769
Nick Piggina60637c2008-07-25 19:45:31 -07001770 rcu_read_lock();
1771repeat:
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001772 xas_reset(&xas);
1773 page = xas_load(&xas);
1774 if (xas_retry(&xas, page))
1775 goto repeat;
1776 /*
1777 * A shadow entry of a recently evicted page, or a swap entry from
1778 * shmem/tmpfs. Return it without attempting to raise page count.
1779 */
1780 if (!page || xa_is_value(page))
1781 goto out;
Kirill A. Shutemov83929372016-07-26 15:26:04 -07001782
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001783 if (!page_cache_get_speculative(page))
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001784 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001785
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001786 /*
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001787 * Has the page moved or been split?
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001788 * This is part of the lockless pagecache protocol. See
1789 * include/linux/pagemap.h for details.
1790 */
1791 if (unlikely(page != xas_reload(&xas))) {
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07001792 put_page(page);
Matthew Wilcox4c7472c2018-05-16 16:12:50 -04001793 goto repeat;
Nick Piggina60637c2008-07-25 19:45:31 -07001794 }
Nick Piggin27d20fd2010-11-11 14:05:19 -08001795out:
Nick Piggina60637c2008-07-25 19:45:31 -07001796 rcu_read_unlock();
1797
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798 return page;
1799}
Linus Torvalds1da177e2005-04-16 15:20:36 -07001800
Randy Dunlap485bb992006-06-23 02:03:49 -07001801/**
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001802 * pagecache_get_page - Find and get a reference to a page.
1803 * @mapping: The address_space to search.
1804 * @index: The page index.
1805 * @fgp_flags: %FGP flags modify how the page is returned.
1806 * @gfp_mask: Memory allocation flags to use if %FGP_CREAT is specified.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001807 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001808 * Looks up the page cache entry at @mapping & @index.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001809 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001810 * @fgp_flags can be zero or more of these flags:
Johannes Weiner0cd61442014-04-03 14:47:46 -07001811 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001812 * * %FGP_ACCESSED - The page will be marked accessed.
1813 * * %FGP_LOCK - The page is returned locked.
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001814 * * %FGP_HEAD - If the page is present and a THP, return the head page
1815 * rather than the exact page specified by the index.
Matthew Wilcox (Oracle)44835d22021-02-25 17:15:36 -08001816 * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1817 * instead of allocating a new page to replace it.
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001818 * * %FGP_CREAT - If no page is present then a new page is allocated using
1819 * @gfp_mask and added to the page cache and the VM's LRU list.
1820 * The page is returned locked and with an increased refcount.
1821 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1822 * page is already in cache. If the page was allocated, unlock it before
1823 * returning so the caller can do the same dance.
Yang Shi605cad82020-08-06 23:19:58 -07001824 * * %FGP_WRITE - The page will be written
1825 * * %FGP_NOFS - __GFP_FS will get cleared in gfp mask
1826 * * %FGP_NOWAIT - Don't get blocked by page lock
mchehab@s-opensource.com0e056eb2017-03-30 17:11:36 -03001827 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001828 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1829 * if the %GFP flags specified for %FGP_CREAT are atomic.
Mel Gorman2457aec2014-06-04 16:10:31 -07001830 *
1831 * If there is a page cache page, it is returned with an increased refcount.
Mike Rapoporta862f682019-03-05 15:48:42 -08001832 *
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001833 * Return: The found page or %NULL otherwise.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001834 */
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001835struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
1836 int fgp_flags, gfp_t gfp_mask)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001837{
Nick Piggineb2be182007-10-16 01:24:57 -07001838 struct page *page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001839
Linus Torvalds1da177e2005-04-16 15:20:36 -07001840repeat:
Matthew Wilcox (Oracle)bc5a3012021-02-25 17:15:40 -08001841 page = mapping_get_entry(mapping, index);
Matthew Wilcox (Oracle)44835d22021-02-25 17:15:36 -08001842 if (xa_is_value(page)) {
1843 if (fgp_flags & FGP_ENTRY)
1844 return page;
Mel Gorman2457aec2014-06-04 16:10:31 -07001845 page = NULL;
Matthew Wilcox (Oracle)44835d22021-02-25 17:15:36 -08001846 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001847 if (!page)
1848 goto no_page;
1849
1850 if (fgp_flags & FGP_LOCK) {
1851 if (fgp_flags & FGP_NOWAIT) {
1852 if (!trylock_page(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001853 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001854 return NULL;
1855 }
1856 } else {
1857 lock_page(page);
1858 }
1859
1860 /* Has the page been truncated? */
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001861 if (unlikely(page->mapping != mapping)) {
Mel Gorman2457aec2014-06-04 16:10:31 -07001862 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001863 put_page(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001864 goto repeat;
1865 }
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001866 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001867 }
1868
Kirill Tkhaic16eb002018-12-28 00:37:35 -08001869 if (fgp_flags & FGP_ACCESSED)
Mel Gorman2457aec2014-06-04 16:10:31 -07001870 mark_page_accessed(page);
Yang Shib9306a72020-08-06 23:19:55 -07001871 else if (fgp_flags & FGP_WRITE) {
1872 /* Clear idle flag for buffer write */
1873 if (page_is_idle(page))
1874 clear_page_idle(page);
1875 }
Matthew Wilcox (Oracle)a8cf7f22020-10-13 16:51:41 -07001876 if (!(fgp_flags & FGP_HEAD))
1877 page = find_subpage(page, index);
Mel Gorman2457aec2014-06-04 16:10:31 -07001878
1879no_page:
1880 if (!page && (fgp_flags & FGP_CREAT)) {
1881 int err;
Christoph Hellwigf56753a2020-09-24 08:51:40 +02001882 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
Michal Hocko45f87de2014-12-29 20:30:35 +01001883 gfp_mask |= __GFP_WRITE;
1884 if (fgp_flags & FGP_NOFS)
1885 gfp_mask &= ~__GFP_FS;
Mel Gorman2457aec2014-06-04 16:10:31 -07001886
Michal Hocko45f87de2014-12-29 20:30:35 +01001887 page = __page_cache_alloc(gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001888 if (!page)
1889 return NULL;
Mel Gorman2457aec2014-06-04 16:10:31 -07001890
Josef Bacika75d4c32019-03-13 11:44:14 -07001891 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
Mel Gorman2457aec2014-06-04 16:10:31 -07001892 fgp_flags |= FGP_LOCK;
1893
Hugh Dickinseb39d612014-08-06 16:06:43 -07001894 /* Init accessed so avoid atomic mark_page_accessed later */
Mel Gorman2457aec2014-06-04 16:10:31 -07001895 if (fgp_flags & FGP_ACCESSED)
Hugh Dickinseb39d612014-08-06 16:06:43 -07001896 __SetPageReferenced(page);
Mel Gorman2457aec2014-06-04 16:10:31 -07001897
Matthew Wilcox (Oracle)2294b322020-04-01 21:05:07 -07001898 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
Nick Piggineb2be182007-10-16 01:24:57 -07001899 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03001900 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07001901 page = NULL;
1902 if (err == -EEXIST)
1903 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001904 }
Josef Bacika75d4c32019-03-13 11:44:14 -07001905
1906 /*
1907 * add_to_page_cache_lru locks the page, and for mmap we expect
1908 * an unlocked page.
1909 */
1910 if (page && (fgp_flags & FGP_FOR_MMAP))
1911 unlock_page(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001912 }
Mel Gorman2457aec2014-06-04 16:10:31 -07001913
Linus Torvalds1da177e2005-04-16 15:20:36 -07001914 return page;
1915}
Mel Gorman2457aec2014-06-04 16:10:31 -07001916EXPORT_SYMBOL(pagecache_get_page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001917
Matthew Wilcox (Oracle)c7bad632021-02-25 17:15:44 -08001918static inline struct page *find_get_entry(struct xa_state *xas, pgoff_t max,
1919 xa_mark_t mark)
1920{
1921 struct page *page;
1922
1923retry:
1924 if (mark == XA_PRESENT)
1925 page = xas_find(xas, max);
1926 else
1927 page = xas_find_marked(xas, max, mark);
1928
1929 if (xas_retry(xas, page))
1930 goto retry;
1931 /*
1932 * A shadow entry of a recently evicted page, a swap
1933 * entry from shmem/tmpfs or a DAX entry. Return it
1934 * without attempting to raise page count.
1935 */
1936 if (!page || xa_is_value(page))
1937 return page;
1938
1939 if (!page_cache_get_speculative(page))
1940 goto reset;
1941
1942 /* Has the page moved or been split? */
1943 if (unlikely(page != xas_reload(xas))) {
1944 put_page(page);
1945 goto reset;
1946 }
1947
1948 return page;
1949reset:
1950 xas_reset(xas);
1951 goto retry;
1952}
1953
Linus Torvalds1da177e2005-04-16 15:20:36 -07001954/**
Johannes Weiner0cd61442014-04-03 14:47:46 -07001955 * find_get_entries - gang pagecache lookup
1956 * @mapping: The address_space to search
1957 * @start: The starting page cache index
Matthew Wilcox (Oracle)ca122fe42021-02-25 17:16:00 -08001958 * @end: The final page index (inclusive).
Matthew Wilcox (Oracle)cf2039a2021-02-25 17:16:11 -08001959 * @pvec: Where the resulting entries are placed.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001960 * @indices: The cache indices corresponding to the entries in @entries
1961 *
Matthew Wilcox (Oracle)cf2039a2021-02-25 17:16:11 -08001962 * find_get_entries() will search for and return a batch of entries in
1963 * the mapping. The entries are placed in @pvec. find_get_entries()
1964 * takes a reference on any actual pages it returns.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001965 *
1966 * The search returns a group of mapping-contiguous page cache entries
1967 * with ascending indexes. There may be holes in the indices due to
1968 * not-present pages.
1969 *
Johannes Weiner139b6a62014-05-06 12:50:05 -07001970 * Any shadow entries of evicted pages, or swap entries from
1971 * shmem/tmpfs, are included in the returned array.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001972 *
Hugh Dickins71725ed2020-04-06 20:07:57 -07001973 * If it finds a Transparent Huge Page, head or tail, find_get_entries()
1974 * stops at that page: the caller is likely to have a better way to handle
1975 * the compound page as a whole, and then skip its extent, than repeatedly
1976 * calling find_get_entries() to return all its tails.
1977 *
Mike Rapoporta862f682019-03-05 15:48:42 -08001978 * Return: the number of pages and shadow entries which were found.
Johannes Weiner0cd61442014-04-03 14:47:46 -07001979 */
Matthew Wilcox (Oracle)ca122fe42021-02-25 17:16:00 -08001980unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
Matthew Wilcox (Oracle)cf2039a2021-02-25 17:16:11 -08001981 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
Johannes Weiner0cd61442014-04-03 14:47:46 -07001982{
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04001983 XA_STATE(xas, &mapping->i_pages, start);
1984 struct page *page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001985 unsigned int ret = 0;
Matthew Wilcox (Oracle)cf2039a2021-02-25 17:16:11 -08001986 unsigned nr_entries = PAGEVEC_SIZE;
Johannes Weiner0cd61442014-04-03 14:47:46 -07001987
1988 rcu_read_lock();
Matthew Wilcox (Oracle)ca122fe42021-02-25 17:16:00 -08001989 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
Hugh Dickins71725ed2020-04-06 20:07:57 -07001990 /*
1991 * Terminate early on finding a THP, to allow the caller to
1992 * handle it all at once; but continue if this is hugetlbfs.
1993 */
Matthew Wilcox (Oracle)c7bad632021-02-25 17:15:44 -08001994 if (!xa_is_value(page) && PageTransHuge(page) &&
1995 !PageHuge(page)) {
Hugh Dickins71725ed2020-04-06 20:07:57 -07001996 page = find_subpage(page, xas.xa_index);
1997 nr_entries = ret + 1;
1998 }
Matthew Wilcox (Oracle)c7bad632021-02-25 17:15:44 -08001999
Matthew Wilcoxf280bf02018-05-16 17:20:45 -04002000 indices[ret] = xas.xa_index;
Matthew Wilcox (Oracle)cf2039a2021-02-25 17:16:11 -08002001 pvec->pages[ret] = page;
Johannes Weiner0cd61442014-04-03 14:47:46 -07002002 if (++ret == nr_entries)
2003 break;
2004 }
2005 rcu_read_unlock();
Matthew Wilcox (Oracle)cf2039a2021-02-25 17:16:11 -08002006
2007 pvec->nr = ret;
Johannes Weiner0cd61442014-04-03 14:47:46 -07002008 return ret;
2009}
2010
2011/**
Matthew Wilcox (Oracle)5c211ba2021-02-25 17:15:56 -08002012 * find_lock_entries - Find a batch of pagecache entries.
2013 * @mapping: The address_space to search.
2014 * @start: The starting page cache index.
2015 * @end: The final page index (inclusive).
2016 * @pvec: Where the resulting entries are placed.
2017 * @indices: The cache indices of the entries in @pvec.
2018 *
2019 * find_lock_entries() will return a batch of entries from @mapping.
2020 * Swap, shadow and DAX entries are included. Pages are returned
2021 * locked and with an incremented refcount. Pages which are locked by
2022 * somebody else or under writeback are skipped. Only the head page of
2023 * a THP is returned. Pages which are partially outside the range are
2024 * not returned.
2025 *
2026 * The entries have ascending indexes. The indices may not be consecutive
2027 * due to not-present entries, THP pages, pages which could not be locked
2028 * or pages under writeback.
2029 *
2030 * Return: The number of entries which were found.
2031 */
2032unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2033 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
2034{
2035 XA_STATE(xas, &mapping->i_pages, start);
2036 struct page *page;
2037
2038 rcu_read_lock();
2039 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2040 if (!xa_is_value(page)) {
2041 if (page->index < start)
2042 goto put;
2043 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2044 if (page->index + thp_nr_pages(page) - 1 > end)
2045 goto put;
2046 if (!trylock_page(page))
2047 goto put;
2048 if (page->mapping != mapping || PageWriteback(page))
2049 goto unlock;
2050 VM_BUG_ON_PAGE(!thp_contains(page, xas.xa_index),
2051 page);
2052 }
2053 indices[pvec->nr] = xas.xa_index;
2054 if (!pagevec_add(pvec, page))
2055 break;
2056 goto next;
2057unlock:
2058 unlock_page(page);
2059put:
2060 put_page(page);
2061next:
Hugh Dickins2d11e732021-04-23 14:28:57 -07002062 if (!xa_is_value(page) && PageTransHuge(page)) {
2063 unsigned int nr_pages = thp_nr_pages(page);
2064
2065 /* Final THP may cross MAX_LFS_FILESIZE on 32-bit */
2066 xas_set(&xas, page->index + nr_pages);
2067 if (xas.xa_index < nr_pages)
2068 break;
2069 }
Matthew Wilcox (Oracle)5c211ba2021-02-25 17:15:56 -08002070 }
2071 rcu_read_unlock();
2072
2073 return pagevec_count(pvec);
2074}
2075
2076/**
Jan Karab947cee2017-09-06 16:21:21 -07002077 * find_get_pages_range - gang pagecache lookup
Linus Torvalds1da177e2005-04-16 15:20:36 -07002078 * @mapping: The address_space to search
2079 * @start: The starting page index
Jan Karab947cee2017-09-06 16:21:21 -07002080 * @end: The final page index (inclusive)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002081 * @nr_pages: The maximum number of pages
2082 * @pages: Where the resulting pages are placed
2083 *
Jan Karab947cee2017-09-06 16:21:21 -07002084 * find_get_pages_range() will search for and return a group of up to @nr_pages
2085 * pages in the mapping starting at index @start and up to index @end
2086 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
2087 * a reference against the returned pages.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002088 *
2089 * The search returns a group of mapping-contiguous pages with ascending
2090 * indexes. There may be holes in the indices due to not-present pages.
Jan Karad72dc8a2017-09-06 16:21:18 -07002091 * We also update @start to index the next page for the traversal.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002092 *
Mike Rapoporta862f682019-03-05 15:48:42 -08002093 * Return: the number of pages which were found. If this number is
2094 * smaller than @nr_pages, the end of specified range has been
Jan Karab947cee2017-09-06 16:21:21 -07002095 * reached.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002096 */
Jan Karab947cee2017-09-06 16:21:21 -07002097unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
2098 pgoff_t end, unsigned int nr_pages,
2099 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002100{
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002101 XA_STATE(xas, &mapping->i_pages, *start);
2102 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002103 unsigned ret = 0;
2104
2105 if (unlikely(!nr_pages))
2106 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002107
Nick Piggina60637c2008-07-25 19:45:31 -07002108 rcu_read_lock();
Matthew Wilcox (Oracle)c7bad632021-02-25 17:15:44 -08002109 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002110 /* Skip over shadow, swap and DAX entries */
2111 if (xa_is_value(page))
Hugh Dickins8079b1c2011-08-03 16:21:28 -07002112 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07002113
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002114 pages[ret] = find_subpage(page, xas.xa_index);
Jan Karab947cee2017-09-06 16:21:21 -07002115 if (++ret == nr_pages) {
Yu Zhao5d3ee422019-03-05 15:49:17 -08002116 *start = xas.xa_index + 1;
Jan Karab947cee2017-09-06 16:21:21 -07002117 goto out;
2118 }
Nick Piggina60637c2008-07-25 19:45:31 -07002119 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07002120
Jan Karab947cee2017-09-06 16:21:21 -07002121 /*
2122 * We come here when there is no page beyond @end. We take care to not
2123 * overflow the index @start as it confuses some of the callers. This
Matthew Wilcoxfd1b3ce2018-05-16 17:38:56 -04002124 * breaks the iteration when there is a page at index -1 but that is
Jan Karab947cee2017-09-06 16:21:21 -07002125 * already broken anyway.
2126 */
2127 if (end == (pgoff_t)-1)
2128 *start = (pgoff_t)-1;
2129 else
2130 *start = end + 1;
2131out:
Nick Piggina60637c2008-07-25 19:45:31 -07002132 rcu_read_unlock();
Jan Karad72dc8a2017-09-06 16:21:18 -07002133
Linus Torvalds1da177e2005-04-16 15:20:36 -07002134 return ret;
2135}
2136
Jens Axboeebf43502006-04-27 08:46:01 +02002137/**
2138 * find_get_pages_contig - gang contiguous pagecache lookup
2139 * @mapping: The address_space to search
2140 * @index: The starting page index
2141 * @nr_pages: The maximum number of pages
2142 * @pages: Where the resulting pages are placed
2143 *
2144 * find_get_pages_contig() works exactly like find_get_pages(), except
2145 * that the returned number of pages are guaranteed to be contiguous.
2146 *
Mike Rapoporta862f682019-03-05 15:48:42 -08002147 * Return: the number of pages which were found.
Jens Axboeebf43502006-04-27 08:46:01 +02002148 */
2149unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2150 unsigned int nr_pages, struct page **pages)
2151{
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002152 XA_STATE(xas, &mapping->i_pages, index);
2153 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002154 unsigned int ret = 0;
2155
2156 if (unlikely(!nr_pages))
2157 return 0;
Jens Axboeebf43502006-04-27 08:46:01 +02002158
Nick Piggina60637c2008-07-25 19:45:31 -07002159 rcu_read_lock();
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002160 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002161 if (xas_retry(&xas, page))
2162 continue;
2163 /*
2164 * If the entry has been swapped out, we can stop looking.
2165 * No current caller is looking for DAX entries.
2166 */
2167 if (xa_is_value(page))
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002168 break;
Hugh Dickins9d8aa4e2011-03-22 16:33:06 -07002169
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002170 if (!page_cache_get_speculative(page))
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002171 goto retry;
Nick Piggina60637c2008-07-25 19:45:31 -07002172
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002173 /* Has the page moved or been split? */
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002174 if (unlikely(page != xas_reload(&xas)))
2175 goto put_page;
Nick Piggina60637c2008-07-25 19:45:31 -07002176
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002177 pages[ret] = find_subpage(page, xas.xa_index);
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002178 if (++ret == nr_pages)
2179 break;
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002180 continue;
2181put_page:
Matthew Wilcox (Oracle)41011962019-09-23 15:34:52 -07002182 put_page(page);
Matthew Wilcox3ece58a2018-05-16 18:00:33 -04002183retry:
2184 xas_reset(&xas);
Jens Axboeebf43502006-04-27 08:46:01 +02002185 }
Nick Piggina60637c2008-07-25 19:45:31 -07002186 rcu_read_unlock();
2187 return ret;
Jens Axboeebf43502006-04-27 08:46:01 +02002188}
David Howellsef71c152007-05-09 02:33:44 -07002189EXPORT_SYMBOL(find_get_pages_contig);
Jens Axboeebf43502006-04-27 08:46:01 +02002190
Randy Dunlap485bb992006-06-23 02:03:49 -07002191/**
Matthew Wilcox (Oracle)c49f50d2021-02-25 17:15:25 -08002192 * find_get_pages_range_tag - Find and return head pages matching @tag.
Randy Dunlap485bb992006-06-23 02:03:49 -07002193 * @mapping: the address_space to search
2194 * @index: the starting page index
Jan Kara72b045a2017-11-15 17:34:33 -08002195 * @end: The final page index (inclusive)
Randy Dunlap485bb992006-06-23 02:03:49 -07002196 * @tag: the tag index
2197 * @nr_pages: the maximum number of pages
2198 * @pages: where the resulting pages are placed
2199 *
Matthew Wilcox (Oracle)c49f50d2021-02-25 17:15:25 -08002200 * Like find_get_pages(), except we only return head pages which are tagged
2201 * with @tag. @index is updated to the index immediately after the last
2202 * page we return, ready for the next iteration.
Mike Rapoporta862f682019-03-05 15:48:42 -08002203 *
2204 * Return: the number of pages which were found.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002205 */
Jan Kara72b045a2017-11-15 17:34:33 -08002206unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002207 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
Jan Kara72b045a2017-11-15 17:34:33 -08002208 struct page **pages)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002209{
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002210 XA_STATE(xas, &mapping->i_pages, *index);
2211 struct page *page;
Konstantin Khlebnikov0fc9d102012-03-28 14:42:54 -07002212 unsigned ret = 0;
2213
2214 if (unlikely(!nr_pages))
2215 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002216
Nick Piggina60637c2008-07-25 19:45:31 -07002217 rcu_read_lock();
Matthew Wilcox (Oracle)c7bad632021-02-25 17:15:44 -08002218 while ((page = find_get_entry(&xas, end, tag))) {
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002219 /*
2220 * Shadow entries should never be tagged, but this iteration
2221 * is lockless so there is a window for page reclaim to evict
2222 * a page we saw tagged. Skip over it.
2223 */
2224 if (xa_is_value(page))
Johannes Weiner139b6a62014-05-06 12:50:05 -07002225 continue;
Nick Piggina60637c2008-07-25 19:45:31 -07002226
Matthew Wilcox (Oracle)c49f50d2021-02-25 17:15:25 -08002227 pages[ret] = page;
Jan Kara72b045a2017-11-15 17:34:33 -08002228 if (++ret == nr_pages) {
Matthew Wilcox (Oracle)c49f50d2021-02-25 17:15:25 -08002229 *index = page->index + thp_nr_pages(page);
Jan Kara72b045a2017-11-15 17:34:33 -08002230 goto out;
2231 }
Nick Piggina60637c2008-07-25 19:45:31 -07002232 }
Hugh Dickins5b280c02011-03-22 16:33:07 -07002233
Jan Kara72b045a2017-11-15 17:34:33 -08002234 /*
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002235 * We come here when we got to @end. We take care to not overflow the
Jan Kara72b045a2017-11-15 17:34:33 -08002236 * index @index as it confuses some of the callers. This breaks the
Matthew Wilcoxa6906972018-05-16 18:12:54 -04002237 * iteration when there is a page at index -1 but that is already
2238 * broken anyway.
Jan Kara72b045a2017-11-15 17:34:33 -08002239 */
2240 if (end == (pgoff_t)-1)
2241 *index = (pgoff_t)-1;
2242 else
2243 *index = end + 1;
2244out:
Nick Piggina60637c2008-07-25 19:45:31 -07002245 rcu_read_unlock();
2246
Linus Torvalds1da177e2005-04-16 15:20:36 -07002247 return ret;
2248}
Jan Kara72b045a2017-11-15 17:34:33 -08002249EXPORT_SYMBOL(find_get_pages_range_tag);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002250
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002251/*
2252 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2253 * a _large_ part of the i/o request. Imagine the worst scenario:
2254 *
2255 * ---R__________________________________________B__________
2256 * ^ reading here ^ bad block(assume 4k)
2257 *
2258 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2259 * => failing the whole request => read(R) => read(R+1) =>
2260 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2261 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2262 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2263 *
2264 * It is going insane. Fix it by quickly scaling down the readahead size.
2265 */
Souptick Joarder0f8e2db2020-04-01 21:04:50 -07002266static void shrink_readahead_size_eio(struct file_ra_state *ra)
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002267{
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002268 ra->ra_pages /= 4;
Wu Fengguang76d42bd2006-06-25 05:48:43 -07002269}
2270
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002271/*
2272 * filemap_get_read_batch - Get a batch of pages for read
2273 *
2274 * Get a batch of pages which represent a contiguous range of bytes
2275 * in the file. No tail pages will be returned. If @index is in the
2276 * middle of a THP, the entire THP will be returned. The last page in
2277 * the batch may have Readahead set or be not Uptodate so that the
2278 * caller can take the appropriate action.
2279 */
2280static void filemap_get_read_batch(struct address_space *mapping,
2281 pgoff_t index, pgoff_t max, struct pagevec *pvec)
2282{
2283 XA_STATE(xas, &mapping->i_pages, index);
2284 struct page *head;
2285
2286 rcu_read_lock();
2287 for (head = xas_load(&xas); head; head = xas_next(&xas)) {
2288 if (xas_retry(&xas, head))
2289 continue;
2290 if (xas.xa_index > max || xa_is_value(head))
2291 break;
2292 if (!page_cache_get_speculative(head))
2293 goto retry;
2294
2295 /* Has the page moved or been split? */
2296 if (unlikely(head != xas_reload(&xas)))
2297 goto put_page;
2298
2299 if (!pagevec_add(pvec, head))
2300 break;
2301 if (!PageUptodate(head))
2302 break;
2303 if (PageReadahead(head))
2304 break;
2305 xas.xa_index = head->index + thp_nr_pages(head) - 1;
2306 xas.xa_offset = (xas.xa_index >> xas.xa_shift) & XA_CHUNK_MASK;
2307 continue;
2308put_page:
2309 put_page(head);
2310retry:
2311 xas_reset(&xas);
2312 }
2313 rcu_read_unlock();
2314}
2315
Matthew Wilcox (Oracle)68430302021-02-24 12:02:15 -08002316static int filemap_read_page(struct file *file, struct address_space *mapping,
2317 struct page *page)
Kent Overstreet723ef242020-12-14 19:04:52 -08002318{
Kent Overstreet723ef242020-12-14 19:04:52 -08002319 int error;
2320
Kent Overstreet723ef242020-12-14 19:04:52 -08002321 /*
Matthew Wilcox (Oracle)68430302021-02-24 12:02:15 -08002322 * A previous I/O error may have been due to temporary failures,
2323 * eg. multipath errors. PG_error will be set again if readpage
2324 * fails.
Kent Overstreet723ef242020-12-14 19:04:52 -08002325 */
2326 ClearPageError(page);
2327 /* Start the actual read. The read will unlock the page. */
Matthew Wilcox (Oracle)68430302021-02-24 12:02:15 -08002328 error = mapping->a_ops->readpage(file, page);
2329 if (error)
2330 return error;
Kent Overstreet723ef242020-12-14 19:04:52 -08002331
Matthew Wilcox (Oracle)aa1ec2f2021-02-24 12:02:38 -08002332 error = wait_on_page_locked_killable(page);
Matthew Wilcox (Oracle)68430302021-02-24 12:02:15 -08002333 if (error)
2334 return error;
Matthew Wilcox (Oracle)aa1ec2f2021-02-24 12:02:38 -08002335 if (PageUptodate(page))
2336 return 0;
Matthew Wilcox (Oracle)aa1ec2f2021-02-24 12:02:38 -08002337 shrink_readahead_size_eio(&file->f_ra);
2338 return -EIO;
Kent Overstreet723ef242020-12-14 19:04:52 -08002339}
2340
Matthew Wilcox (Oracle)fce70da2021-02-24 12:02:28 -08002341static bool filemap_range_uptodate(struct address_space *mapping,
2342 loff_t pos, struct iov_iter *iter, struct page *page)
2343{
2344 int count;
2345
2346 if (PageUptodate(page))
2347 return true;
2348 /* pipes can't handle partially uptodate pages */
2349 if (iov_iter_is_pipe(iter))
2350 return false;
2351 if (!mapping->a_ops->is_partially_uptodate)
2352 return false;
2353 if (mapping->host->i_blkbits >= (PAGE_SHIFT + thp_order(page)))
2354 return false;
2355
2356 count = iter->count;
2357 if (page_offset(page) > pos) {
2358 count -= page_offset(page) - pos;
2359 pos = 0;
2360 } else {
2361 pos -= page_offset(page);
2362 }
2363
2364 return mapping->a_ops->is_partially_uptodate(page, pos, count);
2365}
2366
Matthew Wilcox (Oracle)4612aee2021-02-24 12:02:22 -08002367static int filemap_update_page(struct kiocb *iocb,
2368 struct address_space *mapping, struct iov_iter *iter,
Matthew Wilcox (Oracle)fce70da2021-02-24 12:02:28 -08002369 struct page *page)
Kent Overstreet723ef242020-12-14 19:04:52 -08002370{
Kent Overstreet723ef242020-12-14 19:04:52 -08002371 int error;
2372
Jan Kara730633f2021-01-28 19:19:45 +01002373 if (iocb->ki_flags & IOCB_NOWAIT) {
2374 if (!filemap_invalidate_trylock_shared(mapping))
Matthew Wilcox (Oracle)87d1d7b2021-02-24 12:02:25 -08002375 return -EAGAIN;
Jan Kara730633f2021-01-28 19:19:45 +01002376 } else {
2377 filemap_invalidate_lock_shared(mapping);
2378 }
2379
2380 if (!trylock_page(page)) {
2381 error = -EAGAIN;
2382 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2383 goto unlock_mapping;
Matthew Wilcox (Oracle)87d1d7b2021-02-24 12:02:25 -08002384 if (!(iocb->ki_flags & IOCB_WAITQ)) {
Jan Kara730633f2021-01-28 19:19:45 +01002385 filemap_invalidate_unlock_shared(mapping);
Matthew Wilcox (Oracle)bd8a1f32021-02-24 12:02:05 -08002386 put_and_wait_on_page_locked(page, TASK_KILLABLE);
Matthew Wilcox (Oracle)4612aee2021-02-24 12:02:22 -08002387 return AOP_TRUNCATED_PAGE;
Matthew Wilcox (Oracle)bd8a1f32021-02-24 12:02:05 -08002388 }
Matthew Wilcox (Oracle)87d1d7b2021-02-24 12:02:25 -08002389 error = __lock_page_async(page, iocb->ki_waitq);
2390 if (error)
Jan Kara730633f2021-01-28 19:19:45 +01002391 goto unlock_mapping;
Kent Overstreet723ef242020-12-14 19:04:52 -08002392 }
Kent Overstreet723ef242020-12-14 19:04:52 -08002393
Jan Kara730633f2021-01-28 19:19:45 +01002394 error = AOP_TRUNCATED_PAGE;
Matthew Wilcox (Oracle)bd8a1f32021-02-24 12:02:05 -08002395 if (!page->mapping)
Jan Kara730633f2021-01-28 19:19:45 +01002396 goto unlock;
Kent Overstreet723ef242020-12-14 19:04:52 -08002397
Matthew Wilcox (Oracle)fce70da2021-02-24 12:02:28 -08002398 error = 0;
2399 if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, page))
2400 goto unlock;
2401
2402 error = -EAGAIN;
2403 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2404 goto unlock;
2405
Matthew Wilcox (Oracle)68430302021-02-24 12:02:15 -08002406 error = filemap_read_page(iocb->ki_filp, mapping, page);
Jan Kara730633f2021-01-28 19:19:45 +01002407 goto unlock_mapping;
Matthew Wilcox (Oracle)fce70da2021-02-24 12:02:28 -08002408unlock:
2409 unlock_page(page);
Jan Kara730633f2021-01-28 19:19:45 +01002410unlock_mapping:
2411 filemap_invalidate_unlock_shared(mapping);
2412 if (error == AOP_TRUNCATED_PAGE)
2413 put_page(page);
Matthew Wilcox (Oracle)fce70da2021-02-24 12:02:28 -08002414 return error;
Kent Overstreet723ef242020-12-14 19:04:52 -08002415}
2416
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002417static int filemap_create_page(struct file *file,
2418 struct address_space *mapping, pgoff_t index,
2419 struct pagevec *pvec)
Kent Overstreet723ef242020-12-14 19:04:52 -08002420{
Kent Overstreet723ef242020-12-14 19:04:52 -08002421 struct page *page;
2422 int error;
2423
Kent Overstreet723ef242020-12-14 19:04:52 -08002424 page = page_cache_alloc(mapping);
2425 if (!page)
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002426 return -ENOMEM;
Kent Overstreet723ef242020-12-14 19:04:52 -08002427
Jan Kara730633f2021-01-28 19:19:45 +01002428 /*
2429 * Protect against truncate / hole punch. Grabbing invalidate_lock here
2430 * assures we cannot instantiate and bring uptodate new pagecache pages
2431 * after evicting page cache during truncate and before actually
2432 * freeing blocks. Note that we could release invalidate_lock after
2433 * inserting the page into page cache as the locked page would then be
2434 * enough to synchronize with hole punching. But there are code paths
2435 * such as filemap_update_page() filling in partially uptodate pages or
2436 * ->readpages() that need to hold invalidate_lock while mapping blocks
2437 * for IO so let's hold the lock here as well to keep locking rules
2438 * simple.
2439 */
2440 filemap_invalidate_lock_shared(mapping);
Kent Overstreet723ef242020-12-14 19:04:52 -08002441 error = add_to_page_cache_lru(page, mapping, index,
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002442 mapping_gfp_constraint(mapping, GFP_KERNEL));
2443 if (error == -EEXIST)
2444 error = AOP_TRUNCATED_PAGE;
2445 if (error)
2446 goto error;
2447
2448 error = filemap_read_page(file, mapping, page);
2449 if (error)
2450 goto error;
2451
Jan Kara730633f2021-01-28 19:19:45 +01002452 filemap_invalidate_unlock_shared(mapping);
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002453 pagevec_add(pvec, page);
2454 return 0;
2455error:
Jan Kara730633f2021-01-28 19:19:45 +01002456 filemap_invalidate_unlock_shared(mapping);
Matthew Wilcox (Oracle)68430302021-02-24 12:02:15 -08002457 put_page(page);
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002458 return error;
Kent Overstreet723ef242020-12-14 19:04:52 -08002459}
2460
Matthew Wilcox (Oracle)5963fe02021-02-24 12:02:32 -08002461static int filemap_readahead(struct kiocb *iocb, struct file *file,
2462 struct address_space *mapping, struct page *page,
2463 pgoff_t last_index)
2464{
2465 if (iocb->ki_flags & IOCB_NOIO)
2466 return -EAGAIN;
2467 page_cache_async_readahead(mapping, &file->f_ra, file, page,
2468 page->index, last_index - page->index);
2469 return 0;
2470}
2471
Matthew Wilcox (Oracle)3a6bae42021-02-24 12:01:49 -08002472static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002473 struct pagevec *pvec)
Kent Overstreet06c04442020-12-14 19:04:56 -08002474{
2475 struct file *filp = iocb->ki_filp;
2476 struct address_space *mapping = filp->f_mapping;
2477 struct file_ra_state *ra = &filp->f_ra;
2478 pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002479 pgoff_t last_index;
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002480 struct page *page;
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002481 int err = 0;
Kent Overstreet06c04442020-12-14 19:04:56 -08002482
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002483 last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002484retry:
Kent Overstreet06c04442020-12-14 19:04:56 -08002485 if (fatal_signal_pending(current))
2486 return -EINTR;
2487
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002488 filemap_get_read_batch(mapping, index, last_index, pvec);
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002489 if (!pagevec_count(pvec)) {
2490 if (iocb->ki_flags & IOCB_NOIO)
2491 return -EAGAIN;
2492 page_cache_sync_readahead(mapping, ra, filp, index,
2493 last_index - index);
2494 filemap_get_read_batch(mapping, index, last_index, pvec);
2495 }
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002496 if (!pagevec_count(pvec)) {
2497 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2498 return -EAGAIN;
2499 err = filemap_create_page(filp, mapping,
2500 iocb->ki_pos >> PAGE_SHIFT, pvec);
2501 if (err == AOP_TRUNCATED_PAGE)
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002502 goto retry;
Matthew Wilcox (Oracle)f253e182021-02-24 12:02:18 -08002503 return err;
2504 }
Kent Overstreet06c04442020-12-14 19:04:56 -08002505
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002506 page = pvec->pages[pagevec_count(pvec) - 1];
2507 if (PageReadahead(page)) {
2508 err = filemap_readahead(iocb, filp, mapping, page, last_index);
2509 if (err)
2510 goto err;
2511 }
2512 if (!PageUptodate(page)) {
2513 if ((iocb->ki_flags & IOCB_WAITQ) && pagevec_count(pvec) > 1)
2514 iocb->ki_flags |= IOCB_NOWAIT;
2515 err = filemap_update_page(iocb, mapping, iter, page);
2516 if (err)
2517 goto err;
Kent Overstreet06c04442020-12-14 19:04:56 -08002518 }
2519
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002520 return 0;
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002521err:
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002522 if (err < 0)
2523 put_page(page);
2524 if (likely(--pvec->nr))
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002525 return 0;
Matthew Wilcox (Oracle)4612aee2021-02-24 12:02:22 -08002526 if (err == AOP_TRUNCATED_PAGE)
Matthew Wilcox (Oracle)2642fca2021-02-24 12:02:35 -08002527 goto retry;
2528 return err;
Kent Overstreet06c04442020-12-14 19:04:56 -08002529}
2530
Randy Dunlap485bb992006-06-23 02:03:49 -07002531/**
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002532 * filemap_read - Read data from the page cache.
2533 * @iocb: The iocb to read.
2534 * @iter: Destination for the data.
2535 * @already_read: Number of bytes already read by the caller.
Randy Dunlap485bb992006-06-23 02:03:49 -07002536 *
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002537 * Copies data from the page cache. If the data is not currently present,
2538 * uses the readahead and readpage address_space operations to fetch it.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002539 *
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002540 * Return: Total number of bytes copied, including those already read by
2541 * the caller. If an error happens before any bytes are copied, returns
2542 * a negative error number.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002543 */
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002544ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2545 ssize_t already_read)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002546{
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002547 struct file *filp = iocb->ki_filp;
Kent Overstreet06c04442020-12-14 19:04:56 -08002548 struct file_ra_state *ra = &filp->f_ra;
Christoph Hellwig36e78912008-02-08 04:21:24 -08002549 struct address_space *mapping = filp->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002550 struct inode *inode = mapping->host;
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002551 struct pagevec pvec;
2552 int i, error = 0;
Kent Overstreet06c04442020-12-14 19:04:56 -08002553 bool writably_mapped;
2554 loff_t isize, end_offset;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002555
Kent Overstreet723ef242020-12-14 19:04:52 -08002556 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
Linus Torvaldsd05c5f72016-12-14 12:45:25 -08002557 return 0;
Kent Overstreet3644e2d2020-12-18 04:07:11 -05002558 if (unlikely(!iov_iter_count(iter)))
2559 return 0;
2560
Wei Fangc2a97372016-10-07 17:01:52 -07002561 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002562 pagevec_init(&pvec);
Wei Fangc2a97372016-10-07 17:01:52 -07002563
Kent Overstreet06c04442020-12-14 19:04:56 -08002564 do {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002565 cond_resched();
Kent Overstreet06c04442020-12-14 19:04:56 -08002566
2567 /*
2568 * If we've already successfully copied some data, then we
2569 * can no longer safely return -EIOCBQUEUED. Hence mark
2570 * an async read NOWAIT at that point.
2571 */
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002572 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
Kent Overstreet06c04442020-12-14 19:04:56 -08002573 iocb->ki_flags |= IOCB_NOWAIT;
2574
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002575 error = filemap_get_pages(iocb, iter, &pvec);
2576 if (error < 0)
Kent Overstreet06c04442020-12-14 19:04:56 -08002577 break;
Michal Hocko5abf1862017-02-03 13:13:29 -08002578
Kent Overstreet723ef242020-12-14 19:04:52 -08002579 /*
Kent Overstreet06c04442020-12-14 19:04:56 -08002580 * i_size must be checked after we know the pages are Uptodate.
2581 *
2582 * Checking i_size after the check allows us to calculate
2583 * the correct value for "nr", which means the zero-filled
2584 * part of the page is not copied back to userspace (unless
2585 * another truncate extends the file - this is desired though).
Kent Overstreet723ef242020-12-14 19:04:52 -08002586 */
Kent Overstreet06c04442020-12-14 19:04:56 -08002587 isize = i_size_read(inode);
2588 if (unlikely(iocb->ki_pos >= isize))
2589 goto put_pages;
Kent Overstreet06c04442020-12-14 19:04:56 -08002590 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2591
Kent Overstreet06c04442020-12-14 19:04:56 -08002592 /*
2593 * Once we start copying data, we don't want to be touching any
2594 * cachelines that might be contended:
2595 */
2596 writably_mapped = mapping_writably_mapped(mapping);
2597
2598 /*
2599 * When a sequential read accesses a page several times, only
2600 * mark it as accessed the first time.
2601 */
2602 if (iocb->ki_pos >> PAGE_SHIFT !=
2603 ra->prev_pos >> PAGE_SHIFT)
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002604 mark_page_accessed(pvec.pages[0]);
Kent Overstreet06c04442020-12-14 19:04:56 -08002605
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002606 for (i = 0; i < pagevec_count(&pvec); i++) {
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002607 struct page *page = pvec.pages[i];
2608 size_t page_size = thp_size(page);
2609 size_t offset = iocb->ki_pos & (page_size - 1);
2610 size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2611 page_size - offset);
2612 size_t copied;
Kent Overstreet06c04442020-12-14 19:04:56 -08002613
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002614 if (end_offset < page_offset(page))
2615 break;
2616 if (i > 0)
2617 mark_page_accessed(page);
Kent Overstreet06c04442020-12-14 19:04:56 -08002618 /*
2619 * If users can be writing to this page using arbitrary
2620 * virtual addresses, take care about potential aliasing
2621 * before reading the page on the kernel side.
2622 */
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002623 if (writably_mapped) {
2624 int j;
Kent Overstreet06c04442020-12-14 19:04:56 -08002625
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002626 for (j = 0; j < thp_nr_pages(page); j++)
2627 flush_dcache_page(page + j);
2628 }
2629
2630 copied = copy_page_to_iter(page, offset, bytes, iter);
Kent Overstreet06c04442020-12-14 19:04:56 -08002631
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002632 already_read += copied;
Kent Overstreet06c04442020-12-14 19:04:56 -08002633 iocb->ki_pos += copied;
2634 ra->prev_pos = iocb->ki_pos;
2635
2636 if (copied < bytes) {
2637 error = -EFAULT;
2638 break;
Kent Overstreet723ef242020-12-14 19:04:52 -08002639 }
Fengguang Wu3ea89ee2007-07-19 01:48:02 -07002640 }
Kent Overstreet06c04442020-12-14 19:04:56 -08002641put_pages:
Matthew Wilcox (Oracle)ff993ba2021-02-24 12:01:55 -08002642 for (i = 0; i < pagevec_count(&pvec); i++)
2643 put_page(pvec.pages[i]);
Matthew Wilcox (Oracle)cbd59c42021-02-24 12:01:59 -08002644 pagevec_reinit(&pvec);
Kent Overstreet06c04442020-12-14 19:04:56 -08002645 } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002646
Krishna Kumar0c6aa262008-10-15 22:01:13 -07002647 file_accessed(filp);
Kent Overstreet06c04442020-12-14 19:04:56 -08002648
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002649 return already_read ? already_read : error;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002650}
Christoph Hellwig87fa0f32021-02-24 12:02:42 -08002651EXPORT_SYMBOL_GPL(filemap_read);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002652
Randy Dunlap485bb992006-06-23 02:03:49 -07002653/**
Al Viro6abd2322014-04-04 14:20:57 -04002654 * generic_file_read_iter - generic filesystem read routine
Randy Dunlap485bb992006-06-23 02:03:49 -07002655 * @iocb: kernel I/O control block
Al Viro6abd2322014-04-04 14:20:57 -04002656 * @iter: destination for the data read
Randy Dunlap485bb992006-06-23 02:03:49 -07002657 *
Al Viro6abd2322014-04-04 14:20:57 -04002658 * This is the "read_iter()" routine for all filesystems
Linus Torvalds1da177e2005-04-16 15:20:36 -07002659 * that can use the page cache directly.
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002660 *
2661 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2662 * be returned when no data can be read without waiting for I/O requests
2663 * to complete; it doesn't prevent readahead.
2664 *
2665 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2666 * requests shall be made for the read or for readahead. When no data
2667 * can be read, -EAGAIN shall be returned. When readahead would be
2668 * triggered, a partial, possibly empty read shall be returned.
2669 *
Mike Rapoporta862f682019-03-05 15:48:42 -08002670 * Return:
2671 * * number of bytes copied, even for partial reads
Andreas Gruenbacher41da51b2019-11-21 23:25:07 +00002672 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
Linus Torvalds1da177e2005-04-16 15:20:36 -07002673 */
2674ssize_t
Al Viroed978a82014-03-05 22:53:04 -05002675generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002676{
Nicolai Stangee7080a42016-03-25 14:22:14 -07002677 size_t count = iov_iter_count(iter);
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002678 ssize_t retval = 0;
Nicolai Stangee7080a42016-03-25 14:22:14 -07002679
2680 if (!count)
Christoph Hellwig826ea862021-02-24 12:02:45 -08002681 return 0; /* skip atime */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002682
Al Viro2ba48ce2015-04-09 13:52:01 -04002683 if (iocb->ki_flags & IOCB_DIRECT) {
Christoph Hellwig47c27bc2017-08-29 16:13:18 +02002684 struct file *file = iocb->ki_filp;
Al Viroed978a82014-03-05 22:53:04 -05002685 struct address_space *mapping = file->f_mapping;
2686 struct inode *inode = mapping->host;
Badari Pulavarty543ade12006-09-30 23:28:48 -07002687 loff_t size;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002688
Linus Torvalds1da177e2005-04-16 15:20:36 -07002689 size = i_size_read(inode);
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002690 if (iocb->ki_flags & IOCB_NOWAIT) {
Jens Axboe7a60d6d2021-04-29 22:55:21 -07002691 if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2692 iocb->ki_pos + count - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002693 return -EAGAIN;
2694 } else {
2695 retval = filemap_write_and_wait_range(mapping,
2696 iocb->ki_pos,
2697 iocb->ki_pos + count - 1);
2698 if (retval < 0)
Christoph Hellwig826ea862021-02-24 12:02:45 -08002699 return retval;
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05002700 }
Al Viroed978a82014-03-05 22:53:04 -05002701
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002702 file_accessed(file);
2703
Al Viro5ecda132017-04-13 14:13:36 -04002704 retval = mapping->a_ops->direct_IO(iocb, iter);
Al Viroc3a69022016-10-10 13:26:27 -04002705 if (retval >= 0) {
Christoph Hellwigc64fb5c2016-04-07 08:51:55 -07002706 iocb->ki_pos += retval;
Al Viro5ecda132017-04-13 14:13:36 -04002707 count -= retval;
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002708 }
Pavel Begunkovab2125d2021-02-24 12:01:45 -08002709 if (retval != -EIOCBQUEUED)
2710 iov_iter_revert(iter, count - iov_iter_count(iter));
Josef Bacik66f998f2010-05-23 11:00:54 -04002711
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002712 /*
2713 * Btrfs can have a short DIO read if we encounter
2714 * compressed extents, so if there was an error, or if
2715 * we've already read everything we wanted to, or if
2716 * there was a short read because we hit EOF, go ahead
2717 * and return. Otherwise fallthrough to buffered io for
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08002718 * the rest of the read. Buffered reads will not work for
2719 * DAX files, so don't bother trying.
Steven Whitehouse9fe55ee2014-01-24 14:42:22 +00002720 */
Al Viro5ecda132017-04-13 14:13:36 -04002721 if (retval < 0 || !count || iocb->ki_pos >= size ||
Christoph Hellwig0d5b0cf2016-10-03 09:48:08 +11002722 IS_DAX(inode))
Christoph Hellwig826ea862021-02-24 12:02:45 -08002723 return retval;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002724 }
2725
Christoph Hellwig826ea862021-02-24 12:02:45 -08002726 return filemap_read(iocb, iter, retval);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002727}
Al Viroed978a82014-03-05 22:53:04 -05002728EXPORT_SYMBOL(generic_file_read_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002729
Matthew Wilcox (Oracle)54fa39a2021-02-25 17:15:52 -08002730static inline loff_t page_seek_hole_data(struct xa_state *xas,
2731 struct address_space *mapping, struct page *page,
2732 loff_t start, loff_t end, bool seek_data)
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002733{
Matthew Wilcox (Oracle)54fa39a2021-02-25 17:15:52 -08002734 const struct address_space_operations *ops = mapping->a_ops;
2735 size_t offset, bsz = i_blocksize(mapping->host);
2736
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002737 if (xa_is_value(page) || PageUptodate(page))
Matthew Wilcox (Oracle)54fa39a2021-02-25 17:15:52 -08002738 return seek_data ? start : end;
2739 if (!ops->is_partially_uptodate)
2740 return seek_data ? end : start;
2741
2742 xas_pause(xas);
2743 rcu_read_unlock();
2744 lock_page(page);
2745 if (unlikely(page->mapping != mapping))
2746 goto unlock;
2747
2748 offset = offset_in_thp(page, start) & ~(bsz - 1);
2749
2750 do {
2751 if (ops->is_partially_uptodate(page, offset, bsz) == seek_data)
2752 break;
2753 start = (start + bsz) & ~(bsz - 1);
2754 offset += bsz;
2755 } while (offset < thp_size(page));
2756unlock:
2757 unlock_page(page);
2758 rcu_read_lock();
2759 return start;
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002760}
2761
2762static inline
2763unsigned int seek_page_size(struct xa_state *xas, struct page *page)
2764{
2765 if (xa_is_value(page))
2766 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2767 return thp_size(page);
2768}
2769
2770/**
2771 * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2772 * @mapping: Address space to search.
2773 * @start: First byte to consider.
2774 * @end: Limit of search (exclusive).
2775 * @whence: Either SEEK_HOLE or SEEK_DATA.
2776 *
2777 * If the page cache knows which blocks contain holes and which blocks
2778 * contain data, your filesystem can use this function to implement
2779 * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are
2780 * entirely memory-based such as tmpfs, and filesystems which support
2781 * unwritten extents.
2782 *
Ingo Molnarf0953a12021-05-06 18:06:47 -07002783 * Return: The requested offset on success, or -ENXIO if @whence specifies
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002784 * SEEK_DATA and there is no data after @start. There is an implicit hole
2785 * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2786 * and @end contain data.
2787 */
2788loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2789 loff_t end, int whence)
2790{
2791 XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
Hugh Dickinsed98b012021-04-23 14:29:00 -07002792 pgoff_t max = (end - 1) >> PAGE_SHIFT;
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002793 bool seek_data = (whence == SEEK_DATA);
2794 struct page *page;
2795
2796 if (end <= start)
2797 return -ENXIO;
2798
2799 rcu_read_lock();
2800 while ((page = find_get_entry(&xas, max, XA_PRESENT))) {
Hugh Dickinsed98b012021-04-23 14:29:00 -07002801 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2802 unsigned int seek_size;
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002803
2804 if (start < pos) {
2805 if (!seek_data)
2806 goto unlock;
2807 start = pos;
2808 }
2809
Hugh Dickinsed98b012021-04-23 14:29:00 -07002810 seek_size = seek_page_size(&xas, page);
2811 pos = round_up(pos + 1, seek_size);
Matthew Wilcox (Oracle)54fa39a2021-02-25 17:15:52 -08002812 start = page_seek_hole_data(&xas, mapping, page, start, pos,
2813 seek_data);
2814 if (start < pos)
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002815 goto unlock;
Hugh Dickinsed98b012021-04-23 14:29:00 -07002816 if (start >= end)
2817 break;
2818 if (seek_size > PAGE_SIZE)
2819 xas_set(&xas, pos >> PAGE_SHIFT);
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002820 if (!xa_is_value(page))
2821 put_page(page);
2822 }
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002823 if (seek_data)
Hugh Dickinsed98b012021-04-23 14:29:00 -07002824 start = -ENXIO;
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002825unlock:
2826 rcu_read_unlock();
Hugh Dickinsed98b012021-04-23 14:29:00 -07002827 if (page && !xa_is_value(page))
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002828 put_page(page);
Matthew Wilcox (Oracle)41139aa2021-02-25 17:15:48 -08002829 if (start > end)
2830 return end;
2831 return start;
2832}
2833
Linus Torvalds1da177e2005-04-16 15:20:36 -07002834#ifdef CONFIG_MMU
Linus Torvalds1da177e2005-04-16 15:20:36 -07002835#define MMAP_LOTSAMISS (100)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002836/*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002837 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002838 * @vmf - the vm_fault for this fault.
2839 * @page - the page to lock.
2840 * @fpin - the pointer to the file we may pin (or is already pinned).
2841 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002842 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002843 * It differs in that it actually returns the page locked if it returns 1 and 0
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002844 * if it couldn't lock the page. If we did have to drop the mmap_lock then fpin
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002845 * will point to the pinned file and needs to be fput()'ed at a later point.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002846 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002847static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2848 struct file **fpin)
2849{
2850 if (trylock_page(page))
2851 return 1;
2852
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002853 /*
2854 * NOTE! This will make us return with VM_FAULT_RETRY, but with
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002855 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
Linus Torvalds8b0f9fa2019-03-15 11:26:07 -07002856 * is supposed to work. We have way too many special cases..
2857 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002858 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2859 return 0;
2860
2861 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2862 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2863 if (__lock_page_killable(page)) {
2864 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002865 * We didn't have the right flags to drop the mmap_lock,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002866 * but all fault_handlers only check for fatal signals
2867 * if we return VM_FAULT_RETRY, so we need to drop the
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002868 * mmap_lock here and return 0 if we don't have a fpin.
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002869 */
2870 if (*fpin == NULL)
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002871 mmap_read_unlock(vmf->vma->vm_mm);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002872 return 0;
2873 }
2874 } else
2875 __lock_page(page);
2876 return 1;
2877}
2878
2879
2880/*
2881 * Synchronous readahead happens when we don't even find a page in the page
2882 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2883 * to drop the mmap sem we return the file that was pinned in order for us to do
2884 * that. If we didn't pin a file then we return NULL. The file that is
2885 * returned needs to be fput()'ed when we're done with it.
2886 */
2887static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002888{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002889 struct file *file = vmf->vma->vm_file;
2890 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002891 struct address_space *mapping = file->f_mapping;
Matthew Wilcox (Oracle)fcd9ae42021-04-07 21:18:55 +01002892 DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002893 struct file *fpin = NULL;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002894 unsigned int mmap_miss;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002895
2896 /* If we don't want any read-ahead, don't bother */
Josef Bacik2a1180f2019-03-13 11:44:18 -07002897 if (vmf->vma->vm_flags & VM_RAND_READ)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002898 return fpin;
Wu Fengguang275b12b2011-05-24 17:12:28 -07002899 if (!ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002900 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002901
Josef Bacik2a1180f2019-03-13 11:44:18 -07002902 if (vmf->vma->vm_flags & VM_SEQ_READ) {
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002903 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Matthew Wilcox (Oracle)fcd9ae42021-04-07 21:18:55 +01002904 page_cache_sync_ra(&ractl, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002905 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002906 }
2907
Andi Kleen207d04b2011-05-24 17:12:29 -07002908 /* Avoid banging the cache line if not needed */
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002909 mmap_miss = READ_ONCE(ra->mmap_miss);
2910 if (mmap_miss < MMAP_LOTSAMISS * 10)
2911 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
Linus Torvaldsef00e082009-06-16 15:31:25 -07002912
2913 /*
2914 * Do we miss much more than hit in this file? If so,
2915 * stop bothering with read-ahead. It will only hurt.
2916 */
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002917 if (mmap_miss > MMAP_LOTSAMISS)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002918 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002919
Wu Fengguangd30a1102009-06-16 15:31:30 -07002920 /*
2921 * mmap read-around
2922 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002923 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
David Howellsdb660d42020-10-15 20:06:31 -07002924 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
Roman Gushchin600e19a2015-11-05 18:47:08 -08002925 ra->size = ra->ra_pages;
2926 ra->async_size = ra->ra_pages / 4;
David Howellsdb660d42020-10-15 20:06:31 -07002927 ractl._index = ra->start;
2928 do_page_cache_ra(&ractl, ra->size, ra->async_size);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002929 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002930}
2931
2932/*
2933 * Asynchronous readahead happens when we find the page and PG_readahead,
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002934 * so we want to possibly extend the readahead further. We return the file that
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002935 * was pinned if we have to drop the mmap_lock in order to do IO.
Linus Torvaldsef00e082009-06-16 15:31:25 -07002936 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002937static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2938 struct page *page)
Linus Torvaldsef00e082009-06-16 15:31:25 -07002939{
Josef Bacik2a1180f2019-03-13 11:44:18 -07002940 struct file *file = vmf->vma->vm_file;
2941 struct file_ra_state *ra = &file->f_ra;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002942 struct address_space *mapping = file->f_mapping;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002943 struct file *fpin = NULL;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002944 unsigned int mmap_miss;
Josef Bacik2a1180f2019-03-13 11:44:18 -07002945 pgoff_t offset = vmf->pgoff;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002946
2947 /* If we don't want any read-ahead, don't bother */
Jan Kara5c72fee2020-04-01 21:04:40 -07002948 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002949 return fpin;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07002950 mmap_miss = READ_ONCE(ra->mmap_miss);
2951 if (mmap_miss)
2952 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002953 if (PageReadahead(page)) {
2954 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Wu Fengguang2fad6f52009-06-16 15:31:29 -07002955 page_cache_async_readahead(mapping, ra, file,
2956 page, offset, ra->ra_pages);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002957 }
2958 return fpin;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002959}
2960
Randy Dunlap485bb992006-06-23 02:03:49 -07002961/**
Nick Piggin54cb8822007-07-19 01:46:59 -07002962 * filemap_fault - read in file data for page fault handling
Nick Piggind0217ac2007-07-19 01:47:03 -07002963 * @vmf: struct vm_fault containing details of the fault
Randy Dunlap485bb992006-06-23 02:03:49 -07002964 *
Nick Piggin54cb8822007-07-19 01:46:59 -07002965 * filemap_fault() is invoked via the vma operations vector for a
Linus Torvalds1da177e2005-04-16 15:20:36 -07002966 * mapped memory region to read in file data during a page fault.
2967 *
2968 * The goto's are kind of ugly, but this streamlines the normal case of having
2969 * it in the page cache, and handles the special cases reasonably without
2970 * having a lot of duplicated code.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002971 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002972 * vma->vm_mm->mmap_lock must be held on entry.
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002973 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002974 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
Yang Shia4985832019-07-11 20:55:29 -07002975 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002976 *
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07002977 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
Paul Cassella9a95f3c2014-08-06 16:07:24 -07002978 * has not been released.
2979 *
2980 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
Mike Rapoporta862f682019-03-05 15:48:42 -08002981 *
2982 * Return: bitwise-OR of %VM_FAULT_ codes.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002983 */
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002984vm_fault_t filemap_fault(struct vm_fault *vmf)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002985{
2986 int error;
Dave Jiang11bac802017-02-24 14:56:41 -08002987 struct file *file = vmf->vma->vm_file;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07002988 struct file *fpin = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002989 struct address_space *mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002990 struct inode *inode = mapping->host;
Linus Torvaldsef00e082009-06-16 15:31:25 -07002991 pgoff_t offset = vmf->pgoff;
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002992 pgoff_t max_off;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002993 struct page *page;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07002994 vm_fault_t ret = 0;
Jan Kara730633f2021-01-28 19:19:45 +01002995 bool mapping_locked = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002996
Matthew Wilcox9ab25942017-05-03 14:53:29 -07002997 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2998 if (unlikely(offset >= max_off))
Linus Torvalds5307cc12007-10-31 09:19:46 -07002999 return VM_FAULT_SIGBUS;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003000
Linus Torvalds1da177e2005-04-16 15:20:36 -07003001 /*
Johannes Weiner49426422013-10-16 13:46:59 -07003002 * Do we have something in the page cache already?
Linus Torvalds1da177e2005-04-16 15:20:36 -07003003 */
Linus Torvaldsef00e082009-06-16 15:31:25 -07003004 page = find_get_page(mapping, offset);
Jan Kara730633f2021-01-28 19:19:45 +01003005 if (likely(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07003006 /*
Jan Kara730633f2021-01-28 19:19:45 +01003007 * We found the page, so try async readahead before waiting for
3008 * the lock.
Linus Torvalds1da177e2005-04-16 15:20:36 -07003009 */
Jan Kara730633f2021-01-28 19:19:45 +01003010 if (!(vmf->flags & FAULT_FLAG_TRIED))
3011 fpin = do_async_mmap_readahead(vmf, page);
3012 if (unlikely(!PageUptodate(page))) {
3013 filemap_invalidate_lock_shared(mapping);
3014 mapping_locked = true;
3015 }
3016 } else {
Linus Torvaldsef00e082009-06-16 15:31:25 -07003017 /* No page in the page cache at all */
Linus Torvaldsef00e082009-06-16 15:31:25 -07003018 count_vm_event(PGMAJFAULT);
Roman Gushchin22621852017-07-06 15:40:25 -07003019 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
Linus Torvaldsef00e082009-06-16 15:31:25 -07003020 ret = VM_FAULT_MAJOR;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003021 fpin = do_sync_mmap_readahead(vmf);
Linus Torvaldsef00e082009-06-16 15:31:25 -07003022retry_find:
Jan Kara730633f2021-01-28 19:19:45 +01003023 /*
3024 * See comment in filemap_create_page() why we need
3025 * invalidate_lock
3026 */
3027 if (!mapping_locked) {
3028 filemap_invalidate_lock_shared(mapping);
3029 mapping_locked = true;
3030 }
Josef Bacika75d4c32019-03-13 11:44:14 -07003031 page = pagecache_get_page(mapping, offset,
3032 FGP_CREAT|FGP_FOR_MMAP,
3033 vmf->gfp_mask);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003034 if (!page) {
3035 if (fpin)
3036 goto out_retry;
Jan Kara730633f2021-01-28 19:19:45 +01003037 filemap_invalidate_unlock_shared(mapping);
Matthew Wilcox (Oracle)e520e932020-04-01 21:04:53 -07003038 return VM_FAULT_OOM;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003039 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003040 }
3041
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003042 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
3043 goto out_retry;
Michel Lespinasseb522c942010-10-26 14:21:56 -07003044
3045 /* Did it get truncated? */
Song Liu585e5a72019-09-23 15:37:44 -07003046 if (unlikely(compound_head(page)->mapping != mapping)) {
Michel Lespinasseb522c942010-10-26 14:21:56 -07003047 unlock_page(page);
3048 put_page(page);
3049 goto retry_find;
3050 }
Song Liu520e5ba2019-09-23 15:37:50 -07003051 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
Michel Lespinasseb522c942010-10-26 14:21:56 -07003052
Linus Torvalds1da177e2005-04-16 15:20:36 -07003053 /*
Nick Piggind00806b2007-07-19 01:46:57 -07003054 * We have a locked page in the page cache, now we need to check
3055 * that it's up-to-date. If not, it is going to be due to an error.
Linus Torvalds1da177e2005-04-16 15:20:36 -07003056 */
Jan Kara730633f2021-01-28 19:19:45 +01003057 if (unlikely(!PageUptodate(page))) {
3058 /*
3059 * The page was in cache and uptodate and now it is not.
3060 * Strange but possible since we didn't hold the page lock all
3061 * the time. Let's drop everything get the invalidate lock and
3062 * try again.
3063 */
3064 if (!mapping_locked) {
3065 unlock_page(page);
3066 put_page(page);
3067 goto retry_find;
3068 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003069 goto page_not_uptodate;
Jan Kara730633f2021-01-28 19:19:45 +01003070 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003071
Linus Torvaldsef00e082009-06-16 15:31:25 -07003072 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07003073 * We've made it this far and we had to drop our mmap_lock, now is the
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003074 * time to return to the upper layer and have it re-find the vma and
3075 * redo the fault.
3076 */
3077 if (fpin) {
3078 unlock_page(page);
3079 goto out_retry;
3080 }
Jan Kara730633f2021-01-28 19:19:45 +01003081 if (mapping_locked)
3082 filemap_invalidate_unlock_shared(mapping);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003083
3084 /*
Linus Torvaldsef00e082009-06-16 15:31:25 -07003085 * Found the page and have a reference on it.
3086 * We must recheck i_size under page lock.
3087 */
Matthew Wilcox9ab25942017-05-03 14:53:29 -07003088 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3089 if (unlikely(offset >= max_off)) {
Nick Piggind00806b2007-07-19 01:46:57 -07003090 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003091 put_page(page);
Linus Torvalds5307cc12007-10-31 09:19:46 -07003092 return VM_FAULT_SIGBUS;
Nick Piggind00806b2007-07-19 01:46:57 -07003093 }
3094
Nick Piggind0217ac2007-07-19 01:47:03 -07003095 vmf->page = page;
Nick Piggin83c54072007-07-19 01:47:05 -07003096 return ret | VM_FAULT_LOCKED;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003097
Linus Torvalds1da177e2005-04-16 15:20:36 -07003098page_not_uptodate:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003099 /*
3100 * Umm, take care of errors if the page isn't up-to-date.
3101 * Try to re-read it _once_. We do this synchronously,
3102 * because there really aren't any performance issues here
3103 * and we need to check for errors.
3104 */
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003105 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
Matthew Wilcox (Oracle)d31fa862021-04-29 22:55:26 -07003106 error = filemap_read_page(file, mapping, page);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003107 if (fpin)
3108 goto out_retry;
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003109 put_page(page);
Nick Piggind00806b2007-07-19 01:46:57 -07003110
3111 if (!error || error == AOP_TRUNCATED_PAGE)
3112 goto retry_find;
Jan Kara730633f2021-01-28 19:19:45 +01003113 filemap_invalidate_unlock_shared(mapping);
Nick Piggind00806b2007-07-19 01:46:57 -07003114
Nick Piggind0217ac2007-07-19 01:47:03 -07003115 return VM_FAULT_SIGBUS;
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003116
3117out_retry:
3118 /*
Michel Lespinassec1e8d7c2020-06-08 21:33:54 -07003119 * We dropped the mmap_lock, we need to return to the fault handler to
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003120 * re-find the vma and come back and find our hopefully still populated
3121 * page.
3122 */
3123 if (page)
3124 put_page(page);
Jan Kara730633f2021-01-28 19:19:45 +01003125 if (mapping_locked)
3126 filemap_invalidate_unlock_shared(mapping);
Josef Bacik6b4c9f42019-03-13 11:44:22 -07003127 if (fpin)
3128 fput(fpin);
3129 return ret | VM_FAULT_RETRY;
Nick Piggin54cb8822007-07-19 01:46:59 -07003130}
3131EXPORT_SYMBOL(filemap_fault);
3132
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003133static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003134{
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003135 struct mm_struct *mm = vmf->vma->vm_mm;
3136
3137 /* Huge page is mapped? No need to proceed. */
3138 if (pmd_trans_huge(*vmf->pmd)) {
3139 unlock_page(page);
3140 put_page(page);
3141 return true;
3142 }
3143
3144 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3145 vm_fault_t ret = do_set_pmd(vmf, page);
3146 if (!ret) {
3147 /* The page is mapped successfully, reference consumed. */
3148 unlock_page(page);
3149 return true;
3150 }
3151 }
3152
3153 if (pmd_none(*vmf->pmd)) {
3154 vmf->ptl = pmd_lock(mm, vmf->pmd);
3155 if (likely(pmd_none(*vmf->pmd))) {
3156 mm_inc_nr_ptes(mm);
3157 pmd_populate(mm, vmf->pmd, vmf->prealloc_pte);
3158 vmf->prealloc_pte = NULL;
3159 }
3160 spin_unlock(vmf->ptl);
3161 }
3162
3163 /* See comment in handle_pte_fault() */
3164 if (pmd_devmap_trans_unstable(vmf->pmd)) {
3165 unlock_page(page);
3166 put_page(page);
3167 return true;
3168 }
3169
3170 return false;
3171}
3172
3173static struct page *next_uptodate_page(struct page *page,
3174 struct address_space *mapping,
3175 struct xa_state *xas, pgoff_t end_pgoff)
3176{
3177 unsigned long max_idx;
3178
3179 do {
3180 if (!page)
3181 return NULL;
3182 if (xas_retry(xas, page))
3183 continue;
3184 if (xa_is_value(page))
3185 continue;
3186 if (PageLocked(page))
3187 continue;
3188 if (!page_cache_get_speculative(page))
3189 continue;
3190 /* Has the page moved or been split? */
3191 if (unlikely(page != xas_reload(xas)))
3192 goto skip;
3193 if (!PageUptodate(page) || PageReadahead(page))
3194 goto skip;
3195 if (PageHWPoison(page))
3196 goto skip;
3197 if (!trylock_page(page))
3198 goto skip;
3199 if (page->mapping != mapping)
3200 goto unlock;
3201 if (!PageUptodate(page))
3202 goto unlock;
3203 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3204 if (xas->xa_index >= max_idx)
3205 goto unlock;
3206 return page;
3207unlock:
3208 unlock_page(page);
3209skip:
3210 put_page(page);
3211 } while ((page = xas_next_entry(xas, end_pgoff)) != NULL);
3212
3213 return NULL;
3214}
3215
3216static inline struct page *first_map_page(struct address_space *mapping,
3217 struct xa_state *xas,
3218 pgoff_t end_pgoff)
3219{
3220 return next_uptodate_page(xas_find(xas, end_pgoff),
3221 mapping, xas, end_pgoff);
3222}
3223
3224static inline struct page *next_map_page(struct address_space *mapping,
3225 struct xa_state *xas,
3226 pgoff_t end_pgoff)
3227{
3228 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3229 mapping, xas, end_pgoff);
3230}
3231
3232vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3233 pgoff_t start_pgoff, pgoff_t end_pgoff)
3234{
3235 struct vm_area_struct *vma = vmf->vma;
3236 struct file *file = vma->vm_file;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003237 struct address_space *mapping = file->f_mapping;
Kirill A. Shutemovbae473a2016-07-26 15:25:20 -07003238 pgoff_t last_pgoff = start_pgoff;
Will Deacon9d3af4b2021-01-14 15:24:19 +00003239 unsigned long addr;
Matthew Wilcox070e8072018-05-17 00:08:30 -04003240 XA_STATE(xas, &mapping->i_pages, start_pgoff);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003241 struct page *head, *page;
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003242 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003243 vm_fault_t ret = 0;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003244
3245 rcu_read_lock();
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003246 head = first_map_page(mapping, &xas, end_pgoff);
3247 if (!head)
3248 goto out;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003249
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003250 if (filemap_map_pmd(vmf, head)) {
3251 ret = VM_FAULT_NOPAGE;
3252 goto out;
3253 }
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003254
Will Deacon9d3af4b2021-01-14 15:24:19 +00003255 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3256 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003257 do {
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003258 page = find_subpage(head, xas.xa_index);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003259 if (PageHWPoison(page))
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003260 goto unlock;
3261
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003262 if (mmap_miss > 0)
3263 mmap_miss--;
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07003264
Will Deacon9d3af4b2021-01-14 15:24:19 +00003265 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003266 vmf->pte += xas.xa_index - last_pgoff;
Matthew Wilcox070e8072018-05-17 00:08:30 -04003267 last_pgoff = xas.xa_index;
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003268
3269 if (!pte_none(*vmf->pte))
Kirill A. Shutemov7267ec002016-07-26 15:25:23 -07003270 goto unlock;
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003271
Will Deacon46bdb422020-11-24 18:48:26 +00003272 /* We're about to handle the fault */
Will Deacon9d3af4b2021-01-14 15:24:19 +00003273 if (vmf->address == addr)
Will Deacon46bdb422020-11-24 18:48:26 +00003274 ret = VM_FAULT_NOPAGE;
Will Deacon46bdb422020-11-24 18:48:26 +00003275
Will Deacon9d3af4b2021-01-14 15:24:19 +00003276 do_set_pte(vmf, page, addr);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003277 /* no need to invalidate: a not-present page won't be cached */
Will Deacon9d3af4b2021-01-14 15:24:19 +00003278 update_mmu_cache(vma, addr, vmf->pte);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003279 unlock_page(head);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003280 continue;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003281unlock:
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003282 unlock_page(head);
Matthew Wilcox (Oracle)27a83a62020-10-13 16:51:44 -07003283 put_page(head);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003284 } while ((head = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3285 pte_unmap_unlock(vmf->pte, vmf->ptl);
3286out:
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003287 rcu_read_unlock();
Kirill A. Shutemove630bfa2020-08-14 17:31:27 -07003288 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
Kirill A. Shutemovf9ce0be2020-12-19 15:19:23 +03003289 return ret;
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003290}
3291EXPORT_SYMBOL(filemap_map_pages);
3292
Souptick Joarder2bcd6452018-06-07 17:08:00 -07003293vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Jan Kara4fcf1c62012-06-12 16:20:29 +02003294{
Christoph Hellwig5df1a672020-11-16 14:33:37 +01003295 struct address_space *mapping = vmf->vma->vm_file->f_mapping;
Jan Kara4fcf1c62012-06-12 16:20:29 +02003296 struct page *page = vmf->page;
Souptick Joarder2bcd6452018-06-07 17:08:00 -07003297 vm_fault_t ret = VM_FAULT_LOCKED;
Jan Kara4fcf1c62012-06-12 16:20:29 +02003298
Christoph Hellwig5df1a672020-11-16 14:33:37 +01003299 sb_start_pagefault(mapping->host->i_sb);
Dave Jiang11bac802017-02-24 14:56:41 -08003300 file_update_time(vmf->vma->vm_file);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003301 lock_page(page);
Christoph Hellwig5df1a672020-11-16 14:33:37 +01003302 if (page->mapping != mapping) {
Jan Kara4fcf1c62012-06-12 16:20:29 +02003303 unlock_page(page);
3304 ret = VM_FAULT_NOPAGE;
3305 goto out;
3306 }
Jan Kara14da9202012-06-12 16:20:37 +02003307 /*
3308 * We mark the page dirty already here so that when freeze is in
3309 * progress, we are guaranteed that writeback during freezing will
3310 * see the dirty page and writeprotect it again.
3311 */
3312 set_page_dirty(page);
Darrick J. Wong1d1d1a72013-02-21 16:42:51 -08003313 wait_for_stable_page(page);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003314out:
Christoph Hellwig5df1a672020-11-16 14:33:37 +01003315 sb_end_pagefault(mapping->host->i_sb);
Jan Kara4fcf1c62012-06-12 16:20:29 +02003316 return ret;
3317}
Jan Kara4fcf1c62012-06-12 16:20:29 +02003318
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04003319const struct vm_operations_struct generic_file_vm_ops = {
Nick Piggin54cb8822007-07-19 01:46:59 -07003320 .fault = filemap_fault,
Kirill A. Shutemovf1820362014-04-07 15:37:19 -07003321 .map_pages = filemap_map_pages,
Jan Kara4fcf1c62012-06-12 16:20:29 +02003322 .page_mkwrite = filemap_page_mkwrite,
Linus Torvalds1da177e2005-04-16 15:20:36 -07003323};
3324
3325/* This is used for a general mmap of a disk file */
3326
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07003327int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003328{
3329 struct address_space *mapping = file->f_mapping;
3330
3331 if (!mapping->a_ops->readpage)
3332 return -ENOEXEC;
3333 file_accessed(file);
3334 vma->vm_ops = &generic_file_vm_ops;
3335 return 0;
3336}
Linus Torvalds1da177e2005-04-16 15:20:36 -07003337
3338/*
3339 * This is for filesystems which do not implement ->writepage.
3340 */
3341int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3342{
3343 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3344 return -EINVAL;
3345 return generic_file_mmap(file, vma);
3346}
3347#else
Souptick Joarder4b96a372018-10-26 15:04:03 -07003348vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
Arnd Bergmann453972282018-04-13 15:35:27 -07003349{
Souptick Joarder4b96a372018-10-26 15:04:03 -07003350 return VM_FAULT_SIGBUS;
Arnd Bergmann453972282018-04-13 15:35:27 -07003351}
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07003352int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003353{
3354 return -ENOSYS;
3355}
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07003356int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003357{
3358 return -ENOSYS;
3359}
3360#endif /* CONFIG_MMU */
3361
Arnd Bergmann453972282018-04-13 15:35:27 -07003362EXPORT_SYMBOL(filemap_page_mkwrite);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003363EXPORT_SYMBOL(generic_file_mmap);
3364EXPORT_SYMBOL(generic_file_readonly_mmap);
3365
Sasha Levin67f9fd92014-04-03 14:48:18 -07003366static struct page *wait_on_page_read(struct page *page)
3367{
3368 if (!IS_ERR(page)) {
3369 wait_on_page_locked(page);
3370 if (!PageUptodate(page)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003371 put_page(page);
Sasha Levin67f9fd92014-04-03 14:48:18 -07003372 page = ERR_PTR(-EIO);
3373 }
3374 }
3375 return page;
3376}
3377
Mel Gorman32b63522016-03-15 14:55:36 -07003378static struct page *do_read_cache_page(struct address_space *mapping,
Fengguang Wu57f6b962007-10-16 01:24:37 -07003379 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003380 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003381 void *data,
3382 gfp_t gfp)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003383{
Nick Piggineb2be182007-10-16 01:24:57 -07003384 struct page *page;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003385 int err;
3386repeat:
3387 page = find_get_page(mapping, index);
3388 if (!page) {
Mel Gorman453f85d2017-11-15 17:38:03 -08003389 page = __page_cache_alloc(gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07003390 if (!page)
3391 return ERR_PTR(-ENOMEM);
Dave Kleikampe6f67b82011-12-21 11:05:48 -06003392 err = add_to_page_cache_lru(page, mapping, index, gfp);
Nick Piggineb2be182007-10-16 01:24:57 -07003393 if (unlikely(err)) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003394 put_page(page);
Nick Piggineb2be182007-10-16 01:24:57 -07003395 if (err == -EEXIST)
3396 goto repeat;
Matthew Wilcox22ecdb42017-12-04 04:02:00 -05003397 /* Presumably ENOMEM for xarray node */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003398 return ERR_PTR(err);
3399 }
Mel Gorman32b63522016-03-15 14:55:36 -07003400
3401filler:
Christoph Hellwig6c45b452019-07-11 20:55:20 -07003402 if (filler)
3403 err = filler(data, page);
3404 else
3405 err = mapping->a_ops->readpage(data, page);
3406
Linus Torvalds1da177e2005-04-16 15:20:36 -07003407 if (err < 0) {
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003408 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003409 return ERR_PTR(err);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003410 }
Mel Gorman32b63522016-03-15 14:55:36 -07003411
3412 page = wait_on_page_read(page);
3413 if (IS_ERR(page))
3414 return page;
3415 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003416 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003417 if (PageUptodate(page))
3418 goto out;
3419
Mel Gormanebded022016-03-15 14:55:39 -07003420 /*
Miaohe Lin0e9aa672020-10-15 20:09:58 -07003421 * Page is not up to date and may be locked due to one of the following
Mel Gormanebded022016-03-15 14:55:39 -07003422 * case a: Page is being filled and the page lock is held
3423 * case b: Read/write error clearing the page uptodate status
3424 * case c: Truncation in progress (page locked)
3425 * case d: Reclaim in progress
3426 *
3427 * Case a, the page will be up to date when the page is unlocked.
3428 * There is no need to serialise on the page lock here as the page
3429 * is pinned so the lock gives no additional protection. Even if the
Randy Dunlapce89fddf2020-08-11 18:32:53 -07003430 * page is truncated, the data is still valid if PageUptodate as
Mel Gormanebded022016-03-15 14:55:39 -07003431 * it's a race vs truncate race.
3432 * Case b, the page will not be up to date
3433 * Case c, the page may be truncated but in itself, the data may still
3434 * be valid after IO completes as it's a read vs truncate race. The
3435 * operation must restart if the page is not uptodate on unlock but
3436 * otherwise serialising on page lock to stabilise the mapping gives
3437 * no additional guarantees to the caller as the page lock is
3438 * released before return.
3439 * Case d, similar to truncation. If reclaim holds the page lock, it
3440 * will be a race with remove_mapping that determines if the mapping
3441 * is valid on unlock but otherwise the data is valid and there is
3442 * no need to serialise with page lock.
3443 *
3444 * As the page lock gives no additional guarantee, we optimistically
3445 * wait on the page to be unlocked and check if it's up to date and
3446 * use the page if it is. Otherwise, the page lock is required to
3447 * distinguish between the different cases. The motivation is that we
3448 * avoid spurious serialisations and wakeups when multiple processes
3449 * wait on the same page for IO to complete.
3450 */
3451 wait_on_page_locked(page);
3452 if (PageUptodate(page))
3453 goto out;
3454
3455 /* Distinguish between all the cases under the safety of the lock */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003456 lock_page(page);
Mel Gormanebded022016-03-15 14:55:39 -07003457
3458 /* Case c or d, restart the operation */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003459 if (!page->mapping) {
3460 unlock_page(page);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003461 put_page(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003462 goto repeat;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003463 }
Mel Gormanebded022016-03-15 14:55:39 -07003464
3465 /* Someone else locked and filled the page in a very small window */
Linus Torvalds1da177e2005-04-16 15:20:36 -07003466 if (PageUptodate(page)) {
3467 unlock_page(page);
3468 goto out;
3469 }
Xianting Tianfaffdfa2020-04-01 21:04:47 -07003470
3471 /*
3472 * A previous I/O error may have been due to temporary
3473 * failures.
3474 * Clear page error before actual read, PG_error will be
3475 * set again if read page fails.
3476 */
3477 ClearPageError(page);
Mel Gorman32b63522016-03-15 14:55:36 -07003478 goto filler;
3479
David Howellsc855ff32007-05-09 13:42:20 +01003480out:
Nick Piggin6fe69002007-05-06 14:49:04 -07003481 mark_page_accessed(page);
3482 return page;
3483}
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003484
3485/**
Sasha Levin67f9fd92014-04-03 14:48:18 -07003486 * read_cache_page - read into page cache, fill it if needed
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003487 * @mapping: the page's address_space
3488 * @index: the page index
3489 * @filler: function to perform the read
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003490 * @data: first arg to filler(data, page) function, often left as NULL
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003491 *
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003492 * Read into the page cache. If a page already exists, and PageUptodate() is
Sasha Levin67f9fd92014-04-03 14:48:18 -07003493 * not set, try to fill the page and wait for it to become unlocked.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003494 *
3495 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08003496 *
Jan Kara730633f2021-01-28 19:19:45 +01003497 * The function expects mapping->invalidate_lock to be already held.
3498 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003499 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003500 */
Sasha Levin67f9fd92014-04-03 14:48:18 -07003501struct page *read_cache_page(struct address_space *mapping,
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003502 pgoff_t index,
Hugh Dickins5e5358e2011-07-25 17:12:23 -07003503 int (*filler)(void *, struct page *),
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003504 void *data)
3505{
Christoph Hellwigd322a8e2019-07-11 20:55:17 -07003506 return do_read_cache_page(mapping, index, filler, data,
3507 mapping_gfp_mask(mapping));
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003508}
Sasha Levin67f9fd92014-04-03 14:48:18 -07003509EXPORT_SYMBOL(read_cache_page);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003510
3511/**
3512 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3513 * @mapping: the page's address_space
3514 * @index: the page index
3515 * @gfp: the page allocator flags to use if allocating
3516 *
3517 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
Dave Kleikampe6f67b82011-12-21 11:05:48 -06003518 * any new page allocations done using the specified allocation flags.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003519 *
3520 * If the page does not get brought uptodate, return -EIO.
Mike Rapoporta862f682019-03-05 15:48:42 -08003521 *
Jan Kara730633f2021-01-28 19:19:45 +01003522 * The function expects mapping->invalidate_lock to be already held.
3523 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003524 * Return: up to date page on success, ERR_PTR() on failure.
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003525 */
3526struct page *read_cache_page_gfp(struct address_space *mapping,
3527 pgoff_t index,
3528 gfp_t gfp)
3529{
Christoph Hellwig6c45b452019-07-11 20:55:20 -07003530 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
Linus Torvalds0531b2a2010-01-27 09:20:03 -08003531}
3532EXPORT_SYMBOL(read_cache_page_gfp);
3533
Nick Pigginafddba42007-10-16 01:25:01 -07003534int pagecache_write_begin(struct file *file, struct address_space *mapping,
3535 loff_t pos, unsigned len, unsigned flags,
3536 struct page **pagep, void **fsdata)
3537{
3538 const struct address_space_operations *aops = mapping->a_ops;
3539
Nick Piggin4e02ed42008-10-29 14:00:55 -07003540 return aops->write_begin(file, mapping, pos, len, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003541 pagep, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003542}
3543EXPORT_SYMBOL(pagecache_write_begin);
3544
3545int pagecache_write_end(struct file *file, struct address_space *mapping,
3546 loff_t pos, unsigned len, unsigned copied,
3547 struct page *page, void *fsdata)
3548{
3549 const struct address_space_operations *aops = mapping->a_ops;
Nick Pigginafddba42007-10-16 01:25:01 -07003550
Nick Piggin4e02ed42008-10-29 14:00:55 -07003551 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
Nick Pigginafddba42007-10-16 01:25:01 -07003552}
3553EXPORT_SYMBOL(pagecache_write_end);
3554
Konstantin Khlebnikova92853b2019-11-30 17:49:44 -08003555/*
3556 * Warn about a page cache invalidation failure during a direct I/O write.
3557 */
3558void dio_warn_stale_pagecache(struct file *filp)
3559{
3560 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3561 char pathname[128];
Konstantin Khlebnikova92853b2019-11-30 17:49:44 -08003562 char *path;
3563
Christoph Hellwig5df1a672020-11-16 14:33:37 +01003564 errseq_set(&filp->f_mapping->wb_err, -EIO);
Konstantin Khlebnikova92853b2019-11-30 17:49:44 -08003565 if (__ratelimit(&_rs)) {
3566 path = file_path(filp, pathname, sizeof(pathname));
3567 if (IS_ERR(path))
3568 path = "(unknown)";
3569 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3570 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3571 current->comm);
3572 }
3573}
3574
Linus Torvalds1da177e2005-04-16 15:20:36 -07003575ssize_t
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003576generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003577{
3578 struct file *file = iocb->ki_filp;
3579 struct address_space *mapping = file->f_mapping;
3580 struct inode *inode = mapping->host;
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003581 loff_t pos = iocb->ki_pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003582 ssize_t written;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003583 size_t write_len;
3584 pgoff_t end;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003585
Al Viro0c949332014-03-22 06:51:37 -04003586 write_len = iov_iter_count(from);
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003587 end = (pos + write_len - 1) >> PAGE_SHIFT;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003588
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003589 if (iocb->ki_flags & IOCB_NOWAIT) {
3590 /* If there are pages to writeback, return */
Christoph Hellwig5df1a672020-11-16 14:33:37 +01003591 if (filemap_range_has_page(file->f_mapping, pos,
zhengbin35f12f02019-03-05 15:44:21 -08003592 pos + write_len - 1))
Goldwyn Rodrigues6be96d32017-06-20 07:05:44 -05003593 return -EAGAIN;
3594 } else {
3595 written = filemap_write_and_wait_range(mapping, pos,
3596 pos + write_len - 1);
3597 if (written)
3598 goto out;
3599 }
Christoph Hellwiga969e902008-07-23 21:27:04 -07003600
3601 /*
3602 * After a write we want buffered reads to be sure to go to disk to get
3603 * the new data. We invalidate clean cached page from the region we're
3604 * about to write. We do this *before* the write so that we can return
Hisashi Hifumi6ccfa802008-09-02 14:35:40 -07003605 * without clobbering -EIOCBQUEUED from ->direct_IO().
Christoph Hellwiga969e902008-07-23 21:27:04 -07003606 */
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003607 written = invalidate_inode_pages2_range(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003608 pos >> PAGE_SHIFT, end);
Andrey Ryabinin55635ba2017-05-03 14:55:59 -07003609 /*
3610 * If a page can not be invalidated, return 0 to fall back
3611 * to buffered write.
3612 */
3613 if (written) {
3614 if (written == -EBUSY)
3615 return 0;
3616 goto out;
Christoph Hellwiga969e902008-07-23 21:27:04 -07003617 }
3618
Al Viro639a93a52017-04-13 14:10:15 -04003619 written = mapping->a_ops->direct_IO(iocb, from);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003620
3621 /*
3622 * Finally, try again to invalidate clean pages which might have been
3623 * cached by non-direct readahead, or faulted in by get_user_pages()
3624 * if the source of the write was an mmap'ed region of the file
3625 * we're writing. Either one is a pretty crazy thing to do,
3626 * so we don't support it 100%. If this invalidation
3627 * fails, tough, the write still worked...
Lukas Czerner332391a2017-09-21 08:16:29 -06003628 *
3629 * Most of the time we do not need this since dio_complete() will do
3630 * the invalidation for us. However there are some file systems that
3631 * do not end up with dio_complete() being called, so let's not break
Konstantin Khlebnikov80c1fe92019-11-30 17:49:41 -08003632 * them by removing it completely.
3633 *
Konstantin Khlebnikov9266a142019-11-30 17:49:47 -08003634 * Noticeable example is a blkdev_direct_IO().
3635 *
Konstantin Khlebnikov80c1fe92019-11-30 17:49:41 -08003636 * Skip invalidation for async writes or if mapping has no pages.
Christoph Hellwiga969e902008-07-23 21:27:04 -07003637 */
Konstantin Khlebnikov9266a142019-11-30 17:49:47 -08003638 if (written > 0 && mapping->nrpages &&
3639 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3640 dio_warn_stale_pagecache(file);
Christoph Hellwiga969e902008-07-23 21:27:04 -07003641
Linus Torvalds1da177e2005-04-16 15:20:36 -07003642 if (written > 0) {
Namhyung Kim01166512010-10-26 14:21:58 -07003643 pos += written;
Al Viro639a93a52017-04-13 14:10:15 -04003644 write_len -= written;
Namhyung Kim01166512010-10-26 14:21:58 -07003645 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3646 i_size_write(inode, pos);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003647 mark_inode_dirty(inode);
3648 }
Al Viro5cb6c6c2014-02-11 20:58:20 -05003649 iocb->ki_pos = pos;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003650 }
Pavel Begunkovab2125d2021-02-24 12:01:45 -08003651 if (written != -EIOCBQUEUED)
3652 iov_iter_revert(from, write_len - iov_iter_count(from));
Christoph Hellwiga969e902008-07-23 21:27:04 -07003653out:
Linus Torvalds1da177e2005-04-16 15:20:36 -07003654 return written;
3655}
3656EXPORT_SYMBOL(generic_file_direct_write);
3657
Nick Piggineb2be182007-10-16 01:24:57 -07003658/*
3659 * Find or create a page at the given pagecache position. Return the locked
3660 * page. This function is specifically for buffered writes.
3661 */
Nick Piggin54566b22009-01-04 12:00:53 -08003662struct page *grab_cache_page_write_begin(struct address_space *mapping,
3663 pgoff_t index, unsigned flags)
Nick Piggineb2be182007-10-16 01:24:57 -07003664{
Nick Piggineb2be182007-10-16 01:24:57 -07003665 struct page *page;
Johannes Weinerbbddabe2016-05-20 16:56:28 -07003666 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
Johannes Weiner0faa70c2012-01-10 15:07:53 -08003667
Nick Piggin54566b22009-01-04 12:00:53 -08003668 if (flags & AOP_FLAG_NOFS)
Mel Gorman2457aec2014-06-04 16:10:31 -07003669 fgp_flags |= FGP_NOFS;
Nick Piggineb2be182007-10-16 01:24:57 -07003670
Mel Gorman2457aec2014-06-04 16:10:31 -07003671 page = pagecache_get_page(mapping, index, fgp_flags,
Michal Hocko45f87de2014-12-29 20:30:35 +01003672 mapping_gfp_mask(mapping));
Mel Gorman2457aec2014-06-04 16:10:31 -07003673 if (page)
3674 wait_for_stable_page(page);
3675
Nick Piggineb2be182007-10-16 01:24:57 -07003676 return page;
3677}
Nick Piggin54566b22009-01-04 12:00:53 -08003678EXPORT_SYMBOL(grab_cache_page_write_begin);
Nick Piggineb2be182007-10-16 01:24:57 -07003679
Al Viro3b93f912014-02-11 21:34:08 -05003680ssize_t generic_perform_write(struct file *file,
Nick Pigginafddba42007-10-16 01:25:01 -07003681 struct iov_iter *i, loff_t pos)
3682{
3683 struct address_space *mapping = file->f_mapping;
3684 const struct address_space_operations *a_ops = mapping->a_ops;
3685 long status = 0;
3686 ssize_t written = 0;
Nick Piggin674b8922007-10-16 01:25:03 -07003687 unsigned int flags = 0;
3688
Nick Pigginafddba42007-10-16 01:25:01 -07003689 do {
3690 struct page *page;
Nick Pigginafddba42007-10-16 01:25:01 -07003691 unsigned long offset; /* Offset into pagecache page */
3692 unsigned long bytes; /* Bytes to write to page */
3693 size_t copied; /* Bytes copied from user */
3694 void *fsdata;
3695
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003696 offset = (pos & (PAGE_SIZE - 1));
3697 bytes = min_t(unsigned long, PAGE_SIZE - offset,
Nick Pigginafddba42007-10-16 01:25:01 -07003698 iov_iter_count(i));
3699
3700again:
Linus Torvalds00a3d662015-10-07 08:32:38 +01003701 /*
3702 * Bring in the user page that we will copy from _first_.
3703 * Otherwise there's a nasty deadlock on copying from the
3704 * same page as we're writing to, without it being marked
3705 * up-to-date.
Linus Torvalds00a3d662015-10-07 08:32:38 +01003706 */
3707 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3708 status = -EFAULT;
3709 break;
3710 }
3711
Jan Kara296291c2015-10-22 13:32:21 -07003712 if (fatal_signal_pending(current)) {
3713 status = -EINTR;
3714 break;
3715 }
3716
Nick Piggin674b8922007-10-16 01:25:03 -07003717 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
Nick Pigginafddba42007-10-16 01:25:01 -07003718 &page, &fsdata);
Mel Gorman2457aec2014-06-04 16:10:31 -07003719 if (unlikely(status < 0))
Nick Pigginafddba42007-10-16 01:25:01 -07003720 break;
3721
anfei zhou931e80e2010-02-02 13:44:02 -08003722 if (mapping_writably_mapped(mapping))
3723 flush_dcache_page(page);
Linus Torvalds00a3d662015-10-07 08:32:38 +01003724
Al Virof0b65f32021-04-30 10:26:41 -04003725 copied = copy_page_from_iter_atomic(page, offset, bytes, i);
Nick Pigginafddba42007-10-16 01:25:01 -07003726 flush_dcache_page(page);
3727
3728 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3729 page, fsdata);
Al Virof0b65f32021-04-30 10:26:41 -04003730 if (unlikely(status != copied)) {
3731 iov_iter_revert(i, copied - max(status, 0L));
3732 if (unlikely(status < 0))
3733 break;
3734 }
Nick Pigginafddba42007-10-16 01:25:01 -07003735 cond_resched();
3736
Al Virobc1bb412021-05-31 00:32:44 -04003737 if (unlikely(status == 0)) {
Nick Pigginafddba42007-10-16 01:25:01 -07003738 /*
Al Virobc1bb412021-05-31 00:32:44 -04003739 * A short copy made ->write_end() reject the
3740 * thing entirely. Might be memory poisoning
3741 * halfway through, might be a race with munmap,
3742 * might be severe memory pressure.
Nick Pigginafddba42007-10-16 01:25:01 -07003743 */
Al Virobc1bb412021-05-31 00:32:44 -04003744 if (copied)
3745 bytes = copied;
Nick Pigginafddba42007-10-16 01:25:01 -07003746 goto again;
3747 }
Al Virof0b65f32021-04-30 10:26:41 -04003748 pos += status;
3749 written += status;
Nick Pigginafddba42007-10-16 01:25:01 -07003750
3751 balance_dirty_pages_ratelimited(mapping);
Nick Pigginafddba42007-10-16 01:25:01 -07003752 } while (iov_iter_count(i));
3753
3754 return written ? written : status;
3755}
Al Viro3b93f912014-02-11 21:34:08 -05003756EXPORT_SYMBOL(generic_perform_write);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003757
Jan Karae4dd9de2009-08-17 18:10:06 +02003758/**
Al Viro81742022014-04-03 03:17:43 -04003759 * __generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003760 * @iocb: IO state structure (file, offset, etc.)
Al Viro81742022014-04-03 03:17:43 -04003761 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003762 *
3763 * This function does all the work needed for actually writing data to a
3764 * file. It does all basic checks, removes SUID from the file, updates
3765 * modification times and calls proper subroutines depending on whether we
3766 * do direct IO or a standard buffered write.
3767 *
Jan Kara96087032021-04-12 15:50:21 +02003768 * It expects i_rwsem to be grabbed unless we work on a block device or similar
Jan Karae4dd9de2009-08-17 18:10:06 +02003769 * object which does not need locking at all.
3770 *
3771 * This function does *not* take care of syncing data in case of O_SYNC write.
3772 * A caller has to handle it. This is mainly due to the fact that we want to
Jan Kara96087032021-04-12 15:50:21 +02003773 * avoid syncing under i_rwsem.
Mike Rapoporta862f682019-03-05 15:48:42 -08003774 *
3775 * Return:
3776 * * number of bytes written, even for truncated writes
3777 * * negative error code if no data has been written at all
Jan Karae4dd9de2009-08-17 18:10:06 +02003778 */
Al Viro81742022014-04-03 03:17:43 -04003779ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003780{
3781 struct file *file = iocb->ki_filp;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07003782 struct address_space *mapping = file->f_mapping;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003783 struct inode *inode = mapping->host;
Al Viro3b93f912014-02-11 21:34:08 -05003784 ssize_t written = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003785 ssize_t err;
Al Viro3b93f912014-02-11 21:34:08 -05003786 ssize_t status;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003787
Linus Torvalds1da177e2005-04-16 15:20:36 -07003788 /* We can write back this queue in page reclaim */
Christoph Hellwigde1414a2015-01-14 10:42:36 +01003789 current->backing_dev_info = inode_to_bdi(inode);
Jan Kara5fa8e0a2015-05-21 16:05:53 +02003790 err = file_remove_privs(file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003791 if (err)
3792 goto out;
3793
Josef Bacikc3b2da32012-03-26 09:59:21 -04003794 err = file_update_time(file);
3795 if (err)
3796 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003797
Al Viro2ba48ce2015-04-09 13:52:01 -04003798 if (iocb->ki_flags & IOCB_DIRECT) {
Al Viro0b8def92015-04-07 10:22:53 -04003799 loff_t pos, endbyte;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003800
Christoph Hellwig1af5bb42016-04-07 08:51:56 -07003801 written = generic_file_direct_write(iocb, from);
Matthew Wilcoxfbbbad42015-02-16 15:58:53 -08003802 /*
3803 * If the write stopped short of completing, fall back to
3804 * buffered writes. Some filesystems do this for writes to
3805 * holes, for example. For DAX files, a buffered write will
3806 * not succeed (even if it did, DAX does not handle dirty
3807 * page-cache pages correctly).
3808 */
Al Viro0b8def92015-04-07 10:22:53 -04003809 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07003810 goto out;
Al Viro3b93f912014-02-11 21:34:08 -05003811
Al Viro0b8def92015-04-07 10:22:53 -04003812 status = generic_perform_write(file, from, pos = iocb->ki_pos);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003813 /*
Al Viro3b93f912014-02-11 21:34:08 -05003814 * If generic_perform_write() returned a synchronous error
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003815 * then we want to return the number of bytes which were
3816 * direct-written, or the error code if that was zero. Note
3817 * that this differs from normal direct-io semantics, which
3818 * will return -EFOO even if some bytes were written.
3819 */
Al Viro60bb4522014-08-08 12:39:16 -04003820 if (unlikely(status < 0)) {
Al Viro3b93f912014-02-11 21:34:08 -05003821 err = status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003822 goto out;
3823 }
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003824 /*
3825 * We need to ensure that the page cache pages are written to
3826 * disk and invalidated to preserve the expected O_DIRECT
3827 * semantics.
3828 */
Al Viro3b93f912014-02-11 21:34:08 -05003829 endbyte = pos + status - 1;
Al Viro0b8def92015-04-07 10:22:53 -04003830 err = filemap_write_and_wait_range(mapping, pos, endbyte);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003831 if (err == 0) {
Al Viro0b8def92015-04-07 10:22:53 -04003832 iocb->ki_pos = endbyte + 1;
Al Viro3b93f912014-02-11 21:34:08 -05003833 written += status;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003834 invalidate_mapping_pages(mapping,
Kirill A. Shutemov09cbfea2016-04-01 15:29:47 +03003835 pos >> PAGE_SHIFT,
3836 endbyte >> PAGE_SHIFT);
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003837 } else {
3838 /*
3839 * We don't know how much we wrote, so just return
3840 * the number of bytes which were direct-written
3841 */
3842 }
3843 } else {
Al Viro0b8def92015-04-07 10:22:53 -04003844 written = generic_perform_write(file, from, iocb->ki_pos);
3845 if (likely(written > 0))
3846 iocb->ki_pos += written;
Jeff Moyerfb5527e2006-10-19 23:28:13 -07003847 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07003848out:
3849 current->backing_dev_info = NULL;
3850 return written ? written : err;
3851}
Al Viro81742022014-04-03 03:17:43 -04003852EXPORT_SYMBOL(__generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003853
Jan Karae4dd9de2009-08-17 18:10:06 +02003854/**
Al Viro81742022014-04-03 03:17:43 -04003855 * generic_file_write_iter - write data to a file
Jan Karae4dd9de2009-08-17 18:10:06 +02003856 * @iocb: IO state structure
Al Viro81742022014-04-03 03:17:43 -04003857 * @from: iov_iter with data to write
Jan Karae4dd9de2009-08-17 18:10:06 +02003858 *
Al Viro81742022014-04-03 03:17:43 -04003859 * This is a wrapper around __generic_file_write_iter() to be used by most
Jan Karae4dd9de2009-08-17 18:10:06 +02003860 * filesystems. It takes care of syncing the file in case of O_SYNC file
Jan Kara96087032021-04-12 15:50:21 +02003861 * and acquires i_rwsem as needed.
Mike Rapoporta862f682019-03-05 15:48:42 -08003862 * Return:
3863 * * negative error code if no data has been written at all of
3864 * vfs_fsync_range() failed for a synchronous write
3865 * * number of bytes written, even for truncated writes
Jan Karae4dd9de2009-08-17 18:10:06 +02003866 */
Al Viro81742022014-04-03 03:17:43 -04003867ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Linus Torvalds1da177e2005-04-16 15:20:36 -07003868{
3869 struct file *file = iocb->ki_filp;
Jan Kara148f9482009-08-17 19:52:36 +02003870 struct inode *inode = file->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003871 ssize_t ret;
Linus Torvalds1da177e2005-04-16 15:20:36 -07003872
Al Viro59551022016-01-22 15:40:57 -05003873 inode_lock(inode);
Al Viro3309dd02015-04-09 12:55:47 -04003874 ret = generic_write_checks(iocb, from);
3875 if (ret > 0)
Al Viro5f380c72015-04-07 11:28:12 -04003876 ret = __generic_file_write_iter(iocb, from);
Al Viro59551022016-01-22 15:40:57 -05003877 inode_unlock(inode);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003878
Christoph Hellwige2592212016-04-07 08:52:01 -07003879 if (ret > 0)
3880 ret = generic_write_sync(iocb, ret);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003881 return ret;
3882}
Al Viro81742022014-04-03 03:17:43 -04003883EXPORT_SYMBOL(generic_file_write_iter);
Linus Torvalds1da177e2005-04-16 15:20:36 -07003884
David Howellscf9a2ae2006-08-29 19:05:54 +01003885/**
3886 * try_to_release_page() - release old fs-specific metadata on a page
3887 *
3888 * @page: the page which the kernel is trying to free
3889 * @gfp_mask: memory allocation flags (and I/O mode)
3890 *
3891 * The address_space is to try to release any data against the page
Mike Rapoporta862f682019-03-05 15:48:42 -08003892 * (presumably at page->private).
David Howellscf9a2ae2006-08-29 19:05:54 +01003893 *
David Howells266cf652009-04-03 16:42:36 +01003894 * This may also be called if PG_fscache is set on a page, indicating that the
3895 * page is known to the local caching routines.
3896 *
David Howellscf9a2ae2006-08-29 19:05:54 +01003897 * The @gfp_mask argument specifies whether I/O may be performed to release
Mel Gorman71baba42015-11-06 16:28:28 -08003898 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
David Howellscf9a2ae2006-08-29 19:05:54 +01003899 *
Mike Rapoporta862f682019-03-05 15:48:42 -08003900 * Return: %1 if the release was successful, otherwise return zero.
David Howellscf9a2ae2006-08-29 19:05:54 +01003901 */
3902int try_to_release_page(struct page *page, gfp_t gfp_mask)
3903{
3904 struct address_space * const mapping = page->mapping;
3905
3906 BUG_ON(!PageLocked(page));
3907 if (PageWriteback(page))
3908 return 0;
3909
3910 if (mapping && mapping->a_ops->releasepage)
3911 return mapping->a_ops->releasepage(page, gfp_mask);
3912 return try_to_free_buffers(page);
3913}
3914
3915EXPORT_SYMBOL(try_to_release_page);