iomap: use filemap_range_needs_writeback() for O_DIRECT reads
[linux-block.git] / mm / filemap.c
CommitLineData
457c8996 1// SPDX-License-Identifier: GPL-2.0-only
1da177e4
LT
2/*
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 */
b95f1b31 13#include <linux/export.h>
1da177e4 14#include <linux/compiler.h>
f9fe48be 15#include <linux/dax.h>
1da177e4 16#include <linux/fs.h>
3f07c014 17#include <linux/sched/signal.h>
c22ce143 18#include <linux/uaccess.h>
c59ede7b 19#include <linux/capability.h>
1da177e4 20#include <linux/kernel_stat.h>
5a0e3ad6 21#include <linux/gfp.h>
1da177e4
LT
22#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>
cfcbfb13 28#include <linux/error-injection.h>
1da177e4
LT
29#include <linux/hash.h>
30#include <linux/writeback.h>
53253383 31#include <linux/backing-dev.h>
1da177e4
LT
32#include <linux/pagevec.h>
33#include <linux/blkdev.h>
34#include <linux/security.h>
44110fe3 35#include <linux/cpuset.h>
00501b53 36#include <linux/hugetlb.h>
8a9f3ccd 37#include <linux/memcontrol.h>
c515e1fd 38#include <linux/cleancache.h>
c7df8ad2 39#include <linux/shmem_fs.h>
f1820361 40#include <linux/rmap.h>
b1d29ba8 41#include <linux/delayacct.h>
eb414681 42#include <linux/psi.h>
d0e6a582 43#include <linux/ramfs.h>
b9306a79 44#include <linux/page_idle.h>
f9ce0be7 45#include <asm/pgalloc.h>
de591a82 46#include <asm/tlbflush.h>
0f8053a5
NP
47#include "internal.h"
48
fe0bfaaf
RJ
49#define CREATE_TRACE_POINTS
50#include <trace/events/filemap.h>
51
1da177e4 52/*
1da177e4
LT
53 * FIXME: remove all knowledge of the buffer layer from the core VM
54 */
148f948b 55#include <linux/buffer_head.h> /* for try_to_free_buffers */
1da177e4 56
1da177e4
LT
57#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 *
c8c06efa 74 * ->i_mmap_rwsem (truncate_pagecache)
1da177e4 75 * ->private_lock (__free_pte->__set_page_dirty_buffers)
5d337b91 76 * ->swap_lock (exclusive_swap_page, others)
b93b0163 77 * ->i_pages lock
1da177e4 78 *
1b1dcc1b 79 * ->i_mutex
c8c06efa 80 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
1da177e4 81 *
c1e8d7c6 82 * ->mmap_lock
c8c06efa 83 * ->i_mmap_rwsem
b8072f09 84 * ->page_table_lock or pte_lock (various, mainly in memory.c)
b93b0163 85 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
1da177e4 86 *
c1e8d7c6 87 * ->mmap_lock
1da177e4
LT
88 * ->lock_page (access_process_vm)
89 *
ccad2365 90 * ->i_mutex (generic_perform_write)
c1e8d7c6 91 * ->mmap_lock (fault_in_pages_readable->do_page_fault)
1da177e4 92 *
f758eeab 93 * bdi->wb.list_lock
a66979ab 94 * sb_lock (fs/fs-writeback.c)
b93b0163 95 * ->i_pages lock (__sync_single_inode)
1da177e4 96 *
c8c06efa 97 * ->i_mmap_rwsem
1da177e4
LT
98 * ->anon_vma.lock (vma_adjust)
99 *
100 * ->anon_vma.lock
b8072f09 101 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
1da177e4 102 *
b8072f09 103 * ->page_table_lock or pte_lock
5d337b91 104 * ->swap_lock (try_to_unmap_one)
1da177e4 105 * ->private_lock (try_to_unmap_one)
b93b0163 106 * ->i_pages lock (try_to_unmap_one)
15b44736
HD
107 * ->lruvec->lru_lock (follow_page->mark_page_accessed)
108 * ->lruvec->lru_lock (check_pte_range->isolate_lru_page)
1da177e4 109 * ->private_lock (page_remove_rmap->set_page_dirty)
b93b0163 110 * ->i_pages lock (page_remove_rmap->set_page_dirty)
f758eeab 111 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
250df6ed 112 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
81f8c3a4 113 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
f758eeab 114 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
250df6ed 115 * ->inode->i_lock (zap_pte_range->set_page_dirty)
1da177e4
LT
116 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
117 *
c8c06efa 118 * ->i_mmap_rwsem
9a3c531d 119 * ->tasklist_lock (memory_failure, collect_procs_ao)
1da177e4
LT
120 */
121
5c024e6a 122static void page_cache_delete(struct address_space *mapping,
91b0abe3
JW
123 struct page *page, void *shadow)
124{
5c024e6a
MW
125 XA_STATE(xas, &mapping->i_pages, page->index);
126 unsigned int nr = 1;
c70b647d 127
5c024e6a 128 mapping_set_update(&xas, mapping);
c70b647d 129
5c024e6a
MW
130 /* hugetlb pages are represented by a single entry in the xarray */
131 if (!PageHuge(page)) {
132 xas_set_order(&xas, page->index, compound_order(page));
d8c6546b 133 nr = compound_nr(page);
5c024e6a 134 }
91b0abe3 135
83929372
KS
136 VM_BUG_ON_PAGE(!PageLocked(page), page);
137 VM_BUG_ON_PAGE(PageTail(page), page);
138 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
449dd698 139
5c024e6a
MW
140 xas_store(&xas, shadow);
141 xas_init_marks(&xas);
d3798ae8 142
2300638b
JK
143 page->mapping = NULL;
144 /* Leave page->index set: truncation lookup relies upon it */
145
d3798ae8
JW
146 if (shadow) {
147 mapping->nrexceptional += nr;
148 /*
149 * Make sure the nrexceptional update is committed before
150 * the nrpages update so that final truncate racing
151 * with reclaim does not see both counters 0 at the
152 * same time and miss a shadow entry.
153 */
154 smp_wmb();
155 }
156 mapping->nrpages -= nr;
91b0abe3
JW
157}
158
5ecc4d85
JK
159static void unaccount_page_cache_page(struct address_space *mapping,
160 struct page *page)
1da177e4 161{
5ecc4d85 162 int nr;
1da177e4 163
c515e1fd
DM
164 /*
165 * if we're uptodate, flush out into the cleancache, otherwise
166 * invalidate any existing cleancache entries. We can't leave
167 * stale data around in the cleancache once our page is gone
168 */
169 if (PageUptodate(page) && PageMappedToDisk(page))
170 cleancache_put_page(page);
171 else
3167760f 172 cleancache_invalidate_page(mapping, page);
c515e1fd 173
83929372 174 VM_BUG_ON_PAGE(PageTail(page), page);
06b241f3
HD
175 VM_BUG_ON_PAGE(page_mapped(page), page);
176 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
177 int mapcount;
178
179 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
180 current->comm, page_to_pfn(page));
181 dump_page(page, "still mapped when deleted");
182 dump_stack();
183 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
184
185 mapcount = page_mapcount(page);
186 if (mapping_exiting(mapping) &&
187 page_count(page) >= mapcount + 2) {
188 /*
189 * All vmas have already been torn down, so it's
190 * a good bet that actually the page is unmapped,
191 * and we'd prefer not to leak it: if we're wrong,
192 * some other bad page check should catch it later.
193 */
194 page_mapcount_reset(page);
6d061f9f 195 page_ref_sub(page, mapcount);
06b241f3
HD
196 }
197 }
198
4165b9b4 199 /* hugetlb pages do not participate in page cache accounting. */
5ecc4d85
JK
200 if (PageHuge(page))
201 return;
09612fa6 202
6c357848 203 nr = thp_nr_pages(page);
5ecc4d85 204
0d1c2072 205 __mod_lruvec_page_state(page, NR_FILE_PAGES, -nr);
5ecc4d85 206 if (PageSwapBacked(page)) {
0d1c2072 207 __mod_lruvec_page_state(page, NR_SHMEM, -nr);
5ecc4d85 208 if (PageTransHuge(page))
57b2847d 209 __mod_lruvec_page_state(page, NR_SHMEM_THPS, -nr);
99cb0dbd 210 } else if (PageTransHuge(page)) {
bf9ecead 211 __mod_lruvec_page_state(page, NR_FILE_THPS, -nr);
09d91cda 212 filemap_nr_thps_dec(mapping);
800d8c63 213 }
5ecc4d85
JK
214
215 /*
216 * At this point page must be either written or cleaned by
217 * truncate. Dirty page here signals a bug and loss of
218 * unwritten data.
219 *
220 * This fixes dirty accounting after removing the page entirely
221 * but leaves PageDirty set: it has no effect for truncated
222 * page and anyway will be cleared before returning page into
223 * buddy allocator.
224 */
225 if (WARN_ON_ONCE(PageDirty(page)))
226 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
227}
228
229/*
230 * Delete a page from the page cache and free it. Caller has to make
231 * sure the page is locked and that nobody else uses it - or that usage
b93b0163 232 * is safe. The caller must hold the i_pages lock.
5ecc4d85
JK
233 */
234void __delete_from_page_cache(struct page *page, void *shadow)
235{
236 struct address_space *mapping = page->mapping;
237
238 trace_mm_filemap_delete_from_page_cache(page);
239
240 unaccount_page_cache_page(mapping, page);
5c024e6a 241 page_cache_delete(mapping, page, shadow);
1da177e4
LT
242}
243
59c66c5f
JK
244static void page_cache_free_page(struct address_space *mapping,
245 struct page *page)
246{
247 void (*freepage)(struct page *);
248
249 freepage = mapping->a_ops->freepage;
250 if (freepage)
251 freepage(page);
252
253 if (PageTransHuge(page) && !PageHuge(page)) {
887b22c6 254 page_ref_sub(page, thp_nr_pages(page));
59c66c5f
JK
255 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
256 } else {
257 put_page(page);
258 }
259}
260
702cfbf9
MK
261/**
262 * delete_from_page_cache - delete page from page cache
263 * @page: the page which the kernel is trying to remove from page cache
264 *
265 * This must be called only on pages that have been verified to be in the page
266 * cache and locked. It will never put the page into the free list, the caller
267 * has a reference on the page.
268 */
269void delete_from_page_cache(struct page *page)
1da177e4 270{
83929372 271 struct address_space *mapping = page_mapping(page);
c4843a75 272 unsigned long flags;
1da177e4 273
cd7619d6 274 BUG_ON(!PageLocked(page));
b93b0163 275 xa_lock_irqsave(&mapping->i_pages, flags);
62cccb8c 276 __delete_from_page_cache(page, NULL);
b93b0163 277 xa_unlock_irqrestore(&mapping->i_pages, flags);
6072d13c 278
59c66c5f 279 page_cache_free_page(mapping, page);
97cecb5a
MK
280}
281EXPORT_SYMBOL(delete_from_page_cache);
282
aa65c29c 283/*
ef8e5717 284 * page_cache_delete_batch - delete several pages from page cache
aa65c29c
JK
285 * @mapping: the mapping to which pages belong
286 * @pvec: pagevec with pages to delete
287 *
b93b0163 288 * The function walks over mapping->i_pages and removes pages passed in @pvec
4101196b
MWO
289 * from the mapping. The function expects @pvec to be sorted by page index
290 * and is optimised for it to be dense.
b93b0163 291 * It tolerates holes in @pvec (mapping entries at those indices are not
aa65c29c 292 * modified). The function expects only THP head pages to be present in the
4101196b 293 * @pvec.
aa65c29c 294 *
b93b0163 295 * The function expects the i_pages lock to be held.
aa65c29c 296 */
ef8e5717 297static void page_cache_delete_batch(struct address_space *mapping,
aa65c29c
JK
298 struct pagevec *pvec)
299{
ef8e5717 300 XA_STATE(xas, &mapping->i_pages, pvec->pages[0]->index);
aa65c29c 301 int total_pages = 0;
4101196b 302 int i = 0;
aa65c29c 303 struct page *page;
aa65c29c 304
ef8e5717
MW
305 mapping_set_update(&xas, mapping);
306 xas_for_each(&xas, page, ULONG_MAX) {
4101196b 307 if (i >= pagevec_count(pvec))
aa65c29c 308 break;
4101196b
MWO
309
310 /* A swap/dax/shadow entry got inserted? Skip it. */
3159f943 311 if (xa_is_value(page))
aa65c29c 312 continue;
4101196b
MWO
313 /*
314 * A page got inserted in our range? Skip it. We have our
315 * pages locked so they are protected from being removed.
316 * If we see a page whose index is higher than ours, it
317 * means our page has been removed, which shouldn't be
318 * possible because we're holding the PageLock.
319 */
320 if (page != pvec->pages[i]) {
321 VM_BUG_ON_PAGE(page->index > pvec->pages[i]->index,
322 page);
323 continue;
324 }
325
326 WARN_ON_ONCE(!PageLocked(page));
327
328 if (page->index == xas.xa_index)
aa65c29c 329 page->mapping = NULL;
4101196b
MWO
330 /* Leave page->index set: truncation lookup relies on it */
331
332 /*
333 * Move to the next page in the vector if this is a regular
334 * page or the index is of the last sub-page of this compound
335 * page.
336 */
337 if (page->index + compound_nr(page) - 1 == xas.xa_index)
aa65c29c 338 i++;
ef8e5717 339 xas_store(&xas, NULL);
aa65c29c
JK
340 total_pages++;
341 }
342 mapping->nrpages -= total_pages;
343}
344
345void delete_from_page_cache_batch(struct address_space *mapping,
346 struct pagevec *pvec)
347{
348 int i;
349 unsigned long flags;
350
351 if (!pagevec_count(pvec))
352 return;
353
b93b0163 354 xa_lock_irqsave(&mapping->i_pages, flags);
aa65c29c
JK
355 for (i = 0; i < pagevec_count(pvec); i++) {
356 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
357
358 unaccount_page_cache_page(mapping, pvec->pages[i]);
359 }
ef8e5717 360 page_cache_delete_batch(mapping, pvec);
b93b0163 361 xa_unlock_irqrestore(&mapping->i_pages, flags);
aa65c29c
JK
362
363 for (i = 0; i < pagevec_count(pvec); i++)
364 page_cache_free_page(mapping, pvec->pages[i]);
365}
366
d72d9e2a 367int filemap_check_errors(struct address_space *mapping)
865ffef3
DM
368{
369 int ret = 0;
370 /* Check for outstanding write errors */
7fcbbaf1
JA
371 if (test_bit(AS_ENOSPC, &mapping->flags) &&
372 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
865ffef3 373 ret = -ENOSPC;
7fcbbaf1
JA
374 if (test_bit(AS_EIO, &mapping->flags) &&
375 test_and_clear_bit(AS_EIO, &mapping->flags))
865ffef3
DM
376 ret = -EIO;
377 return ret;
378}
d72d9e2a 379EXPORT_SYMBOL(filemap_check_errors);
865ffef3 380
76341cab
JL
381static int filemap_check_and_keep_errors(struct address_space *mapping)
382{
383 /* Check for outstanding write errors */
384 if (test_bit(AS_EIO, &mapping->flags))
385 return -EIO;
386 if (test_bit(AS_ENOSPC, &mapping->flags))
387 return -ENOSPC;
388 return 0;
389}
390
1da177e4 391/**
485bb99b 392 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
67be2dd1
MW
393 * @mapping: address space structure to write
394 * @start: offset in bytes where the range starts
469eb4d0 395 * @end: offset in bytes where the range ends (inclusive)
67be2dd1 396 * @sync_mode: enable synchronous operation
1da177e4 397 *
485bb99b
RD
398 * Start writeback against all of a mapping's dirty pages that lie
399 * within the byte offsets <start, end> inclusive.
400 *
1da177e4 401 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
485bb99b 402 * opposed to a regular memory cleansing writeback. The difference between
1da177e4
LT
403 * these two operations is that if a dirty page/buffer is encountered, it must
404 * be waited upon, and not just skipped over.
a862f68a
MR
405 *
406 * Return: %0 on success, negative error code otherwise.
1da177e4 407 */
ebcf28e1
AM
408int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
409 loff_t end, int sync_mode)
1da177e4
LT
410{
411 int ret;
412 struct writeback_control wbc = {
413 .sync_mode = sync_mode,
05fe478d 414 .nr_to_write = LONG_MAX,
111ebb6e
OH
415 .range_start = start,
416 .range_end = end,
1da177e4
LT
417 };
418
f56753ac 419 if (!mapping_can_writeback(mapping) ||
c3aab9a0 420 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
1da177e4
LT
421 return 0;
422
b16b1deb 423 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
1da177e4 424 ret = do_writepages(mapping, &wbc);
b16b1deb 425 wbc_detach_inode(&wbc);
1da177e4
LT
426 return ret;
427}
428
429static inline int __filemap_fdatawrite(struct address_space *mapping,
430 int sync_mode)
431{
111ebb6e 432 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
1da177e4
LT
433}
434
435int filemap_fdatawrite(struct address_space *mapping)
436{
437 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
438}
439EXPORT_SYMBOL(filemap_fdatawrite);
440
f4c0a0fd 441int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
ebcf28e1 442 loff_t end)
1da177e4
LT
443{
444 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
445}
f4c0a0fd 446EXPORT_SYMBOL(filemap_fdatawrite_range);
1da177e4 447
485bb99b
RD
448/**
449 * filemap_flush - mostly a non-blocking flush
450 * @mapping: target address_space
451 *
1da177e4
LT
452 * This is a mostly non-blocking flush. Not suitable for data-integrity
453 * purposes - I/O may not be started against all dirty pages.
a862f68a
MR
454 *
455 * Return: %0 on success, negative error code otherwise.
1da177e4
LT
456 */
457int filemap_flush(struct address_space *mapping)
458{
459 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
460}
461EXPORT_SYMBOL(filemap_flush);
462
7fc9e472
GR
463/**
464 * filemap_range_has_page - check if a page exists in range.
465 * @mapping: address space within which to check
466 * @start_byte: offset in bytes where the range starts
467 * @end_byte: offset in bytes where the range ends (inclusive)
468 *
469 * Find at least one page in the range supplied, usually used to check if
470 * direct writing in this range will trigger a writeback.
a862f68a
MR
471 *
472 * Return: %true if at least one page exists in the specified range,
473 * %false otherwise.
7fc9e472
GR
474 */
475bool filemap_range_has_page(struct address_space *mapping,
476 loff_t start_byte, loff_t end_byte)
477{
f7b68046 478 struct page *page;
8fa8e538
MW
479 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
480 pgoff_t max = end_byte >> PAGE_SHIFT;
7fc9e472
GR
481
482 if (end_byte < start_byte)
483 return false;
484
8fa8e538
MW
485 rcu_read_lock();
486 for (;;) {
487 page = xas_find(&xas, max);
488 if (xas_retry(&xas, page))
489 continue;
490 /* Shadow entries don't count */
491 if (xa_is_value(page))
492 continue;
493 /*
494 * We don't need to try to pin this page; we're about to
495 * release the RCU lock anyway. It is enough to know that
496 * there was a page here recently.
497 */
498 break;
499 }
500 rcu_read_unlock();
7fc9e472 501
8fa8e538 502 return page != NULL;
7fc9e472
GR
503}
504EXPORT_SYMBOL(filemap_range_has_page);
505
5e8fcc1a 506static void __filemap_fdatawait_range(struct address_space *mapping,
aa750fd7 507 loff_t start_byte, loff_t end_byte)
1da177e4 508{
09cbfeaf
KS
509 pgoff_t index = start_byte >> PAGE_SHIFT;
510 pgoff_t end = end_byte >> PAGE_SHIFT;
1da177e4
LT
511 struct pagevec pvec;
512 int nr_pages;
1da177e4 513
94004ed7 514 if (end_byte < start_byte)
5e8fcc1a 515 return;
1da177e4 516
86679820 517 pagevec_init(&pvec);
312e9d2f 518 while (index <= end) {
1da177e4
LT
519 unsigned i;
520
312e9d2f 521 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
67fd707f 522 end, PAGECACHE_TAG_WRITEBACK);
312e9d2f
JK
523 if (!nr_pages)
524 break;
525
1da177e4
LT
526 for (i = 0; i < nr_pages; i++) {
527 struct page *page = pvec.pages[i];
528
1da177e4 529 wait_on_page_writeback(page);
5e8fcc1a 530 ClearPageError(page);
1da177e4
LT
531 }
532 pagevec_release(&pvec);
533 cond_resched();
534 }
aa750fd7
JN
535}
536
537/**
538 * filemap_fdatawait_range - wait for writeback to complete
539 * @mapping: address space structure to wait for
540 * @start_byte: offset in bytes where the range starts
541 * @end_byte: offset in bytes where the range ends (inclusive)
542 *
543 * Walk the list of under-writeback pages of the given address space
544 * in the given range and wait for all of them. Check error status of
545 * the address space and return it.
546 *
547 * Since the error status of the address space is cleared by this function,
548 * callers are responsible for checking the return value and handling and/or
549 * reporting the error.
a862f68a
MR
550 *
551 * Return: error status of the address space.
aa750fd7
JN
552 */
553int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
554 loff_t end_byte)
555{
5e8fcc1a
JL
556 __filemap_fdatawait_range(mapping, start_byte, end_byte);
557 return filemap_check_errors(mapping);
1da177e4 558}
d3bccb6f
JK
559EXPORT_SYMBOL(filemap_fdatawait_range);
560
aa0bfcd9
RZ
561/**
562 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
563 * @mapping: address space structure to wait for
564 * @start_byte: offset in bytes where the range starts
565 * @end_byte: offset in bytes where the range ends (inclusive)
566 *
567 * Walk the list of under-writeback pages of the given address space in the
568 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
569 * this function does not clear error status of the address space.
570 *
571 * Use this function if callers don't handle errors themselves. Expected
572 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
573 * fsfreeze(8)
574 */
575int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
576 loff_t start_byte, loff_t end_byte)
577{
578 __filemap_fdatawait_range(mapping, start_byte, end_byte);
579 return filemap_check_and_keep_errors(mapping);
580}
581EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
582
a823e458
JL
583/**
584 * file_fdatawait_range - wait for writeback to complete
585 * @file: file pointing to address space structure to wait for
586 * @start_byte: offset in bytes where the range starts
587 * @end_byte: offset in bytes where the range ends (inclusive)
588 *
589 * Walk the list of under-writeback pages of the address space that file
590 * refers to, in the given range and wait for all of them. Check error
591 * status of the address space vs. the file->f_wb_err cursor and return it.
592 *
593 * Since the error status of the file is advanced by this function,
594 * callers are responsible for checking the return value and handling and/or
595 * reporting the error.
a862f68a
MR
596 *
597 * Return: error status of the address space vs. the file->f_wb_err cursor.
a823e458
JL
598 */
599int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
600{
601 struct address_space *mapping = file->f_mapping;
602
603 __filemap_fdatawait_range(mapping, start_byte, end_byte);
604 return file_check_and_advance_wb_err(file);
605}
606EXPORT_SYMBOL(file_fdatawait_range);
d3bccb6f 607
aa750fd7
JN
608/**
609 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
610 * @mapping: address space structure to wait for
611 *
612 * Walk the list of under-writeback pages of the given address space
613 * and wait for all of them. Unlike filemap_fdatawait(), this function
614 * does not clear error status of the address space.
615 *
616 * Use this function if callers don't handle errors themselves. Expected
617 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
618 * fsfreeze(8)
a862f68a
MR
619 *
620 * Return: error status of the address space.
aa750fd7 621 */
76341cab 622int filemap_fdatawait_keep_errors(struct address_space *mapping)
aa750fd7 623{
ffb959bb 624 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
76341cab 625 return filemap_check_and_keep_errors(mapping);
aa750fd7 626}
76341cab 627EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
aa750fd7 628
875d91b1 629/* Returns true if writeback might be needed or already in progress. */
9326c9b2 630static bool mapping_needs_writeback(struct address_space *mapping)
1da177e4 631{
875d91b1
KK
632 if (dax_mapping(mapping))
633 return mapping->nrexceptional;
634
635 return mapping->nrpages;
1da177e4 636}
1da177e4 637
63135aa3
JA
638/**
639 * filemap_range_needs_writeback - check if range potentially needs writeback
640 * @mapping: address space within which to check
641 * @start_byte: offset in bytes where the range starts
642 * @end_byte: offset in bytes where the range ends (inclusive)
643 *
644 * Find at least one page in the range supplied, usually used to check if
645 * direct writing in this range will trigger a writeback. Used by O_DIRECT
646 * read/write with IOCB_NOWAIT, to see if the caller needs to do
647 * filemap_write_and_wait_range() before proceeding.
648 *
649 * Return: %true if the caller should do filemap_write_and_wait_range() before
650 * doing O_DIRECT to a page in this range, %false otherwise.
651 */
652bool filemap_range_needs_writeback(struct address_space *mapping,
653 loff_t start_byte, loff_t end_byte)
654{
655 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
656 pgoff_t max = end_byte >> PAGE_SHIFT;
657 struct page *page;
658
659 if (!mapping_needs_writeback(mapping))
660 return false;
661 if (!mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
662 !mapping_tagged(mapping, PAGECACHE_TAG_WRITEBACK))
663 return false;
664 if (end_byte < start_byte)
665 return false;
666
667 rcu_read_lock();
668 xas_for_each(&xas, page, max) {
669 if (xas_retry(&xas, page))
670 continue;
671 if (xa_is_value(page))
672 continue;
673 if (PageDirty(page) || PageLocked(page) || PageWriteback(page))
674 break;
675 }
676 rcu_read_unlock();
677 return page != NULL;
678}
679EXPORT_SYMBOL_GPL(filemap_range_needs_writeback);
680
485bb99b
RD
681/**
682 * filemap_write_and_wait_range - write out & wait on a file range
683 * @mapping: the address_space for the pages
684 * @lstart: offset in bytes where the range starts
685 * @lend: offset in bytes where the range ends (inclusive)
686 *
469eb4d0
AM
687 * Write out and wait upon file offsets lstart->lend, inclusive.
688 *
0e056eb5 689 * Note that @lend is inclusive (describes the last byte to be written) so
469eb4d0 690 * that this function can be used to write to the very end-of-file (end = -1).
a862f68a
MR
691 *
692 * Return: error status of the address space.
469eb4d0 693 */
1da177e4
LT
694int filemap_write_and_wait_range(struct address_space *mapping,
695 loff_t lstart, loff_t lend)
696{
28fd1298 697 int err = 0;
1da177e4 698
9326c9b2 699 if (mapping_needs_writeback(mapping)) {
28fd1298
OH
700 err = __filemap_fdatawrite_range(mapping, lstart, lend,
701 WB_SYNC_ALL);
ddf8f376
IW
702 /*
703 * Even if the above returned error, the pages may be
704 * written partially (e.g. -ENOSPC), so we wait for it.
705 * But the -EIO is special case, it may indicate the worst
706 * thing (e.g. bug) happened, so we avoid waiting for it.
707 */
28fd1298 708 if (err != -EIO) {
94004ed7
CH
709 int err2 = filemap_fdatawait_range(mapping,
710 lstart, lend);
28fd1298
OH
711 if (!err)
712 err = err2;
cbeaf951
JL
713 } else {
714 /* Clear any previously stored errors */
715 filemap_check_errors(mapping);
28fd1298 716 }
865ffef3
DM
717 } else {
718 err = filemap_check_errors(mapping);
1da177e4 719 }
28fd1298 720 return err;
1da177e4 721}
f6995585 722EXPORT_SYMBOL(filemap_write_and_wait_range);
1da177e4 723
5660e13d
JL
724void __filemap_set_wb_err(struct address_space *mapping, int err)
725{
3acdfd28 726 errseq_t eseq = errseq_set(&mapping->wb_err, err);
5660e13d
JL
727
728 trace_filemap_set_wb_err(mapping, eseq);
729}
730EXPORT_SYMBOL(__filemap_set_wb_err);
731
732/**
733 * file_check_and_advance_wb_err - report wb error (if any) that was previously
734 * and advance wb_err to current one
735 * @file: struct file on which the error is being reported
736 *
737 * When userland calls fsync (or something like nfsd does the equivalent), we
738 * want to report any writeback errors that occurred since the last fsync (or
739 * since the file was opened if there haven't been any).
740 *
741 * Grab the wb_err from the mapping. If it matches what we have in the file,
742 * then just quickly return 0. The file is all caught up.
743 *
744 * If it doesn't match, then take the mapping value, set the "seen" flag in
745 * it and try to swap it into place. If it works, or another task beat us
746 * to it with the new value, then update the f_wb_err and return the error
747 * portion. The error at this point must be reported via proper channels
748 * (a'la fsync, or NFS COMMIT operation, etc.).
749 *
750 * While we handle mapping->wb_err with atomic operations, the f_wb_err
751 * value is protected by the f_lock since we must ensure that it reflects
752 * the latest value swapped in for this file descriptor.
a862f68a
MR
753 *
754 * Return: %0 on success, negative error code otherwise.
5660e13d
JL
755 */
756int file_check_and_advance_wb_err(struct file *file)
757{
758 int err = 0;
759 errseq_t old = READ_ONCE(file->f_wb_err);
760 struct address_space *mapping = file->f_mapping;
761
762 /* Locklessly handle the common case where nothing has changed */
763 if (errseq_check(&mapping->wb_err, old)) {
764 /* Something changed, must use slow path */
765 spin_lock(&file->f_lock);
766 old = file->f_wb_err;
767 err = errseq_check_and_advance(&mapping->wb_err,
768 &file->f_wb_err);
769 trace_file_check_and_advance_wb_err(file, old);
770 spin_unlock(&file->f_lock);
771 }
f4e222c5
JL
772
773 /*
774 * We're mostly using this function as a drop in replacement for
775 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
776 * that the legacy code would have had on these flags.
777 */
778 clear_bit(AS_EIO, &mapping->flags);
779 clear_bit(AS_ENOSPC, &mapping->flags);
5660e13d
JL
780 return err;
781}
782EXPORT_SYMBOL(file_check_and_advance_wb_err);
783
784/**
785 * file_write_and_wait_range - write out & wait on a file range
786 * @file: file pointing to address_space with pages
787 * @lstart: offset in bytes where the range starts
788 * @lend: offset in bytes where the range ends (inclusive)
789 *
790 * Write out and wait upon file offsets lstart->lend, inclusive.
791 *
792 * Note that @lend is inclusive (describes the last byte to be written) so
793 * that this function can be used to write to the very end-of-file (end = -1).
794 *
795 * After writing out and waiting on the data, we check and advance the
796 * f_wb_err cursor to the latest value, and return any errors detected there.
a862f68a
MR
797 *
798 * Return: %0 on success, negative error code otherwise.
5660e13d
JL
799 */
800int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
801{
802 int err = 0, err2;
803 struct address_space *mapping = file->f_mapping;
804
9326c9b2 805 if (mapping_needs_writeback(mapping)) {
5660e13d
JL
806 err = __filemap_fdatawrite_range(mapping, lstart, lend,
807 WB_SYNC_ALL);
808 /* See comment of filemap_write_and_wait() */
809 if (err != -EIO)
810 __filemap_fdatawait_range(mapping, lstart, lend);
811 }
812 err2 = file_check_and_advance_wb_err(file);
813 if (!err)
814 err = err2;
815 return err;
816}
817EXPORT_SYMBOL(file_write_and_wait_range);
818
ef6a3c63
MS
819/**
820 * replace_page_cache_page - replace a pagecache page with a new one
821 * @old: page to be replaced
822 * @new: page to replace with
ef6a3c63
MS
823 *
824 * This function replaces a page in the pagecache with a new one. On
825 * success it acquires the pagecache reference for the new page and
826 * drops it for the old page. Both the old and new pages must be
827 * locked. This function does not add the new page to the LRU, the
828 * caller must do that.
829 *
74d60958 830 * The remove + add is atomic. This function cannot fail.
ef6a3c63 831 */
1f7ef657 832void replace_page_cache_page(struct page *old, struct page *new)
ef6a3c63 833{
74d60958
MW
834 struct address_space *mapping = old->mapping;
835 void (*freepage)(struct page *) = mapping->a_ops->freepage;
836 pgoff_t offset = old->index;
837 XA_STATE(xas, &mapping->i_pages, offset);
838 unsigned long flags;
ef6a3c63 839
309381fe
SL
840 VM_BUG_ON_PAGE(!PageLocked(old), old);
841 VM_BUG_ON_PAGE(!PageLocked(new), new);
842 VM_BUG_ON_PAGE(new->mapping, new);
ef6a3c63 843
74d60958
MW
844 get_page(new);
845 new->mapping = mapping;
846 new->index = offset;
ef6a3c63 847
0d1c2072
JW
848 mem_cgroup_migrate(old, new);
849
74d60958
MW
850 xas_lock_irqsave(&xas, flags);
851 xas_store(&xas, new);
4165b9b4 852
74d60958
MW
853 old->mapping = NULL;
854 /* hugetlb pages do not participate in page cache accounting. */
855 if (!PageHuge(old))
0d1c2072 856 __dec_lruvec_page_state(old, NR_FILE_PAGES);
74d60958 857 if (!PageHuge(new))
0d1c2072 858 __inc_lruvec_page_state(new, NR_FILE_PAGES);
74d60958 859 if (PageSwapBacked(old))
0d1c2072 860 __dec_lruvec_page_state(old, NR_SHMEM);
74d60958 861 if (PageSwapBacked(new))
0d1c2072 862 __inc_lruvec_page_state(new, NR_SHMEM);
74d60958 863 xas_unlock_irqrestore(&xas, flags);
74d60958
MW
864 if (freepage)
865 freepage(old);
866 put_page(old);
ef6a3c63
MS
867}
868EXPORT_SYMBOL_GPL(replace_page_cache_page);
869
16c0cc0c 870noinline int __add_to_page_cache_locked(struct page *page,
76cd6173 871 struct address_space *mapping,
c4cf498d 872 pgoff_t offset, gfp_t gfp,
76cd6173 873 void **shadowp)
1da177e4 874{
74d60958 875 XA_STATE(xas, &mapping->i_pages, offset);
00501b53 876 int huge = PageHuge(page);
e286781d 877 int error;
da74240e 878 bool charged = false;
e286781d 879
309381fe
SL
880 VM_BUG_ON_PAGE(!PageLocked(page), page);
881 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
74d60958 882 mapping_set_update(&xas, mapping);
e286781d 883
09cbfeaf 884 get_page(page);
66a0c8ee
KS
885 page->mapping = mapping;
886 page->index = offset;
887
3fea5a49 888 if (!huge) {
198b62f8 889 error = mem_cgroup_charge(page, current->mm, gfp);
3fea5a49
JW
890 if (error)
891 goto error;
da74240e 892 charged = true;
3fea5a49
JW
893 }
894
198b62f8
MWO
895 gfp &= GFP_RECLAIM_MASK;
896
74d60958 897 do {
198b62f8
MWO
898 unsigned int order = xa_get_order(xas.xa, xas.xa_index);
899 void *entry, *old = NULL;
900
901 if (order > thp_order(page))
902 xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
903 order, gfp);
74d60958 904 xas_lock_irq(&xas);
198b62f8
MWO
905 xas_for_each_conflict(&xas, entry) {
906 old = entry;
907 if (!xa_is_value(entry)) {
908 xas_set_err(&xas, -EEXIST);
909 goto unlock;
910 }
911 }
912
913 if (old) {
914 if (shadowp)
915 *shadowp = old;
916 /* entry may have been split before we acquired lock */
917 order = xa_get_order(xas.xa, xas.xa_index);
918 if (order > thp_order(page)) {
919 xas_split(&xas, old, order);
920 xas_reset(&xas);
921 }
922 }
923
74d60958
MW
924 xas_store(&xas, page);
925 if (xas_error(&xas))
926 goto unlock;
927
198b62f8 928 if (old)
74d60958 929 mapping->nrexceptional--;
74d60958
MW
930 mapping->nrpages++;
931
932 /* hugetlb pages do not participate in page cache accounting */
933 if (!huge)
0d1c2072 934 __inc_lruvec_page_state(page, NR_FILE_PAGES);
74d60958
MW
935unlock:
936 xas_unlock_irq(&xas);
198b62f8 937 } while (xas_nomem(&xas, gfp));
74d60958 938
3fea5a49
JW
939 if (xas_error(&xas)) {
940 error = xas_error(&xas);
da74240e
WL
941 if (charged)
942 mem_cgroup_uncharge(page);
74d60958 943 goto error;
3fea5a49 944 }
4165b9b4 945
66a0c8ee
KS
946 trace_mm_filemap_add_to_page_cache(page);
947 return 0;
74d60958 948error:
66a0c8ee
KS
949 page->mapping = NULL;
950 /* Leave page->index set: truncation relies upon it */
09cbfeaf 951 put_page(page);
3fea5a49 952 return error;
1da177e4 953}
cfcbfb13 954ALLOW_ERROR_INJECTION(__add_to_page_cache_locked, ERRNO);
a528910e
JW
955
956/**
957 * add_to_page_cache_locked - add a locked page to the pagecache
958 * @page: page to add
959 * @mapping: the page's address_space
960 * @offset: page index
961 * @gfp_mask: page allocation mode
962 *
963 * This function is used to add a page to the pagecache. It must be locked.
964 * This function does not add the page to the LRU. The caller must do that.
a862f68a
MR
965 *
966 * Return: %0 on success, negative error code otherwise.
a528910e
JW
967 */
968int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
969 pgoff_t offset, gfp_t gfp_mask)
970{
971 return __add_to_page_cache_locked(page, mapping, offset,
972 gfp_mask, NULL);
973}
e286781d 974EXPORT_SYMBOL(add_to_page_cache_locked);
1da177e4
LT
975
976int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
6daa0e28 977 pgoff_t offset, gfp_t gfp_mask)
1da177e4 978{
a528910e 979 void *shadow = NULL;
4f98a2fe
RR
980 int ret;
981
48c935ad 982 __SetPageLocked(page);
a528910e
JW
983 ret = __add_to_page_cache_locked(page, mapping, offset,
984 gfp_mask, &shadow);
985 if (unlikely(ret))
48c935ad 986 __ClearPageLocked(page);
a528910e
JW
987 else {
988 /*
989 * The page might have been evicted from cache only
990 * recently, in which case it should be activated like
991 * any other repeatedly accessed page.
f0281a00
RR
992 * The exception is pages getting rewritten; evicting other
993 * data from the working set, only to cache data that will
994 * get overwritten with something else, is a waste of memory.
a528910e 995 */
1899ad18
JW
996 WARN_ON_ONCE(PageActive(page));
997 if (!(gfp_mask & __GFP_WRITE) && shadow)
998 workingset_refault(page, shadow);
a528910e
JW
999 lru_cache_add(page);
1000 }
1da177e4
LT
1001 return ret;
1002}
18bc0bbd 1003EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
1da177e4 1004
44110fe3 1005#ifdef CONFIG_NUMA
2ae88149 1006struct page *__page_cache_alloc(gfp_t gfp)
44110fe3 1007{
c0ff7453
MX
1008 int n;
1009 struct page *page;
1010
44110fe3 1011 if (cpuset_do_page_mem_spread()) {
cc9a6c87
MG
1012 unsigned int cpuset_mems_cookie;
1013 do {
d26914d1 1014 cpuset_mems_cookie = read_mems_allowed_begin();
cc9a6c87 1015 n = cpuset_mem_spread_node();
96db800f 1016 page = __alloc_pages_node(n, gfp, 0);
d26914d1 1017 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
cc9a6c87 1018
c0ff7453 1019 return page;
44110fe3 1020 }
2ae88149 1021 return alloc_pages(gfp, 0);
44110fe3 1022}
2ae88149 1023EXPORT_SYMBOL(__page_cache_alloc);
44110fe3
PJ
1024#endif
1025
1da177e4
LT
1026/*
1027 * In order to wait for pages to become available there must be
1028 * waitqueues associated with pages. By using a hash table of
1029 * waitqueues where the bucket discipline is to maintain all
1030 * waiters on the same queue and wake all when any of the pages
1031 * become available, and for the woken contexts to check to be
1032 * sure the appropriate page became available, this saves space
1033 * at a cost of "thundering herd" phenomena during rare hash
1034 * collisions.
1035 */
62906027
NP
1036#define PAGE_WAIT_TABLE_BITS 8
1037#define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1038static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
1039
1040static wait_queue_head_t *page_waitqueue(struct page *page)
1da177e4 1041{
62906027 1042 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
1da177e4 1043}
1da177e4 1044
62906027 1045void __init pagecache_init(void)
1da177e4 1046{
62906027 1047 int i;
1da177e4 1048
62906027
NP
1049 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1050 init_waitqueue_head(&page_wait_table[i]);
1051
1052 page_writeback_init();
1da177e4 1053}
1da177e4 1054
5ef64cc8
LT
1055/*
1056 * The page wait code treats the "wait->flags" somewhat unusually, because
5868ec26 1057 * we have multiple different kinds of waits, not just the usual "exclusive"
5ef64cc8
LT
1058 * one.
1059 *
1060 * We have:
1061 *
1062 * (a) no special bits set:
1063 *
1064 * We're just waiting for the bit to be released, and when a waker
1065 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
1066 * and remove it from the wait queue.
1067 *
1068 * Simple and straightforward.
1069 *
1070 * (b) WQ_FLAG_EXCLUSIVE:
1071 *
1072 * The waiter is waiting to get the lock, and only one waiter should
1073 * be woken up to avoid any thundering herd behavior. We'll set the
1074 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
1075 *
1076 * This is the traditional exclusive wait.
1077 *
5868ec26 1078 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
5ef64cc8
LT
1079 *
1080 * The waiter is waiting to get the bit, and additionally wants the
1081 * lock to be transferred to it for fair lock behavior. If the lock
1082 * cannot be taken, we stop walking the wait queue without waking
1083 * the waiter.
1084 *
1085 * This is the "fair lock handoff" case, and in addition to setting
1086 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
1087 * that it now has the lock.
1088 */
ac6424b9 1089static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
f62e00cc 1090{
5ef64cc8 1091 unsigned int flags;
62906027
NP
1092 struct wait_page_key *key = arg;
1093 struct wait_page_queue *wait_page
1094 = container_of(wait, struct wait_page_queue, wait);
1095
cdc8fcb4 1096 if (!wake_page_match(wait_page, key))
62906027 1097 return 0;
3510ca20 1098
9a1ea439 1099 /*
5ef64cc8
LT
1100 * If it's a lock handoff wait, we get the bit for it, and
1101 * stop walking (and do not wake it up) if we can't.
9a1ea439 1102 */
5ef64cc8
LT
1103 flags = wait->flags;
1104 if (flags & WQ_FLAG_EXCLUSIVE) {
1105 if (test_bit(key->bit_nr, &key->page->flags))
2a9127fc 1106 return -1;
5ef64cc8
LT
1107 if (flags & WQ_FLAG_CUSTOM) {
1108 if (test_and_set_bit(key->bit_nr, &key->page->flags))
1109 return -1;
1110 flags |= WQ_FLAG_DONE;
1111 }
2a9127fc 1112 }
f62e00cc 1113
5ef64cc8
LT
1114 /*
1115 * We are holding the wait-queue lock, but the waiter that
1116 * is waiting for this will be checking the flags without
1117 * any locking.
1118 *
1119 * So update the flags atomically, and wake up the waiter
1120 * afterwards to avoid any races. This store-release pairs
1121 * with the load-acquire in wait_on_page_bit_common().
1122 */
1123 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
2a9127fc
LT
1124 wake_up_state(wait->private, mode);
1125
1126 /*
1127 * Ok, we have successfully done what we're waiting for,
1128 * and we can unconditionally remove the wait entry.
1129 *
5ef64cc8
LT
1130 * Note that this pairs with the "finish_wait()" in the
1131 * waiter, and has to be the absolute last thing we do.
1132 * After this list_del_init(&wait->entry) the wait entry
2a9127fc
LT
1133 * might be de-allocated and the process might even have
1134 * exited.
2a9127fc 1135 */
c6fe44d9 1136 list_del_init_careful(&wait->entry);
5ef64cc8 1137 return (flags & WQ_FLAG_EXCLUSIVE) != 0;
f62e00cc
KM
1138}
1139
74d81bfa 1140static void wake_up_page_bit(struct page *page, int bit_nr)
cbbce822 1141{
62906027
NP
1142 wait_queue_head_t *q = page_waitqueue(page);
1143 struct wait_page_key key;
1144 unsigned long flags;
11a19c7b 1145 wait_queue_entry_t bookmark;
cbbce822 1146
62906027
NP
1147 key.page = page;
1148 key.bit_nr = bit_nr;
1149 key.page_match = 0;
1150
11a19c7b
TC
1151 bookmark.flags = 0;
1152 bookmark.private = NULL;
1153 bookmark.func = NULL;
1154 INIT_LIST_HEAD(&bookmark.entry);
1155
62906027 1156 spin_lock_irqsave(&q->lock, flags);
11a19c7b
TC
1157 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1158
1159 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1160 /*
1161 * Take a breather from holding the lock,
1162 * allow pages that finish wake up asynchronously
1163 * to acquire the lock and remove themselves
1164 * from wait queue
1165 */
1166 spin_unlock_irqrestore(&q->lock, flags);
1167 cpu_relax();
1168 spin_lock_irqsave(&q->lock, flags);
1169 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1170 }
1171
62906027
NP
1172 /*
1173 * It is possible for other pages to have collided on the waitqueue
1174 * hash, so in that case check for a page match. That prevents a long-
1175 * term waiter
1176 *
1177 * It is still possible to miss a case here, when we woke page waiters
1178 * and removed them from the waitqueue, but there are still other
1179 * page waiters.
1180 */
1181 if (!waitqueue_active(q) || !key.page_match) {
1182 ClearPageWaiters(page);
1183 /*
1184 * It's possible to miss clearing Waiters here, when we woke
1185 * our page waiters, but the hashed waitqueue has waiters for
1186 * other pages on it.
1187 *
1188 * That's okay, it's a rare case. The next waker will clear it.
1189 */
1190 }
1191 spin_unlock_irqrestore(&q->lock, flags);
1192}
74d81bfa
NP
1193
1194static void wake_up_page(struct page *page, int bit)
1195{
1196 if (!PageWaiters(page))
1197 return;
1198 wake_up_page_bit(page, bit);
1199}
62906027 1200
9a1ea439
HD
1201/*
1202 * A choice of three behaviors for wait_on_page_bit_common():
1203 */
1204enum behavior {
1205 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like
1206 * __lock_page() waiting on then setting PG_locked.
1207 */
1208 SHARED, /* Hold ref to page and check the bit when woken, like
1209 * wait_on_page_writeback() waiting on PG_writeback.
1210 */
1211 DROP, /* Drop ref to page before wait, no check when woken,
1212 * like put_and_wait_on_page_locked() on PG_locked.
1213 */
1214};
1215
2a9127fc 1216/*
5ef64cc8
LT
1217 * Attempt to check (or get) the page bit, and mark us done
1218 * if successful.
2a9127fc
LT
1219 */
1220static inline bool trylock_page_bit_common(struct page *page, int bit_nr,
1221 struct wait_queue_entry *wait)
1222{
1223 if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1224 if (test_and_set_bit(bit_nr, &page->flags))
1225 return false;
1226 } else if (test_bit(bit_nr, &page->flags))
1227 return false;
1228
5ef64cc8 1229 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
2a9127fc
LT
1230 return true;
1231}
1232
5ef64cc8
LT
1233/* How many times do we accept lock stealing from under a waiter? */
1234int sysctl_page_lock_unfairness = 5;
1235
62906027 1236static inline int wait_on_page_bit_common(wait_queue_head_t *q,
9a1ea439 1237 struct page *page, int bit_nr, int state, enum behavior behavior)
62906027 1238{
5ef64cc8 1239 int unfairness = sysctl_page_lock_unfairness;
62906027 1240 struct wait_page_queue wait_page;
ac6424b9 1241 wait_queue_entry_t *wait = &wait_page.wait;
b1d29ba8 1242 bool thrashing = false;
9a1ea439 1243 bool delayacct = false;
eb414681 1244 unsigned long pflags;
62906027 1245
eb414681 1246 if (bit_nr == PG_locked &&
b1d29ba8 1247 !PageUptodate(page) && PageWorkingset(page)) {
9a1ea439 1248 if (!PageSwapBacked(page)) {
eb414681 1249 delayacct_thrashing_start();
9a1ea439
HD
1250 delayacct = true;
1251 }
eb414681 1252 psi_memstall_enter(&pflags);
b1d29ba8
JW
1253 thrashing = true;
1254 }
1255
62906027
NP
1256 init_wait(wait);
1257 wait->func = wake_page_function;
1258 wait_page.page = page;
1259 wait_page.bit_nr = bit_nr;
1260
5ef64cc8
LT
1261repeat:
1262 wait->flags = 0;
1263 if (behavior == EXCLUSIVE) {
1264 wait->flags = WQ_FLAG_EXCLUSIVE;
1265 if (--unfairness < 0)
1266 wait->flags |= WQ_FLAG_CUSTOM;
1267 }
1268
2a9127fc
LT
1269 /*
1270 * Do one last check whether we can get the
1271 * page bit synchronously.
1272 *
1273 * Do the SetPageWaiters() marking before that
1274 * to let any waker we _just_ missed know they
1275 * need to wake us up (otherwise they'll never
1276 * even go to the slow case that looks at the
1277 * page queue), and add ourselves to the wait
1278 * queue if we need to sleep.
1279 *
1280 * This part needs to be done under the queue
1281 * lock to avoid races.
1282 */
1283 spin_lock_irq(&q->lock);
1284 SetPageWaiters(page);
1285 if (!trylock_page_bit_common(page, bit_nr, wait))
1286 __add_wait_queue_entry_tail(q, wait);
1287 spin_unlock_irq(&q->lock);
62906027 1288
2a9127fc
LT
1289 /*
1290 * From now on, all the logic will be based on
5ef64cc8
LT
1291 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
1292 * see whether the page bit testing has already
1293 * been done by the wake function.
2a9127fc
LT
1294 *
1295 * We can drop our reference to the page.
1296 */
1297 if (behavior == DROP)
1298 put_page(page);
62906027 1299
5ef64cc8
LT
1300 /*
1301 * Note that until the "finish_wait()", or until
1302 * we see the WQ_FLAG_WOKEN flag, we need to
1303 * be very careful with the 'wait->flags', because
1304 * we may race with a waker that sets them.
1305 */
2a9127fc 1306 for (;;) {
5ef64cc8
LT
1307 unsigned int flags;
1308
62906027
NP
1309 set_current_state(state);
1310
5ef64cc8
LT
1311 /* Loop until we've been woken or interrupted */
1312 flags = smp_load_acquire(&wait->flags);
1313 if (!(flags & WQ_FLAG_WOKEN)) {
1314 if (signal_pending_state(state, current))
1315 break;
1316
1317 io_schedule();
1318 continue;
1319 }
1320
1321 /* If we were non-exclusive, we're done */
1322 if (behavior != EXCLUSIVE)
a8b169af 1323 break;
9a1ea439 1324
5ef64cc8
LT
1325 /* If the waker got the lock for us, we're done */
1326 if (flags & WQ_FLAG_DONE)
9a1ea439 1327 break;
2a9127fc 1328
5ef64cc8
LT
1329 /*
1330 * Otherwise, if we're getting the lock, we need to
1331 * try to get it ourselves.
1332 *
1333 * And if that fails, we'll have to retry this all.
1334 */
1335 if (unlikely(test_and_set_bit(bit_nr, &page->flags)))
1336 goto repeat;
1337
1338 wait->flags |= WQ_FLAG_DONE;
1339 break;
62906027
NP
1340 }
1341
5ef64cc8
LT
1342 /*
1343 * If a signal happened, this 'finish_wait()' may remove the last
1344 * waiter from the wait-queues, but the PageWaiters bit will remain
1345 * set. That's ok. The next wakeup will take care of it, and trying
1346 * to do it here would be difficult and prone to races.
1347 */
62906027
NP
1348 finish_wait(q, wait);
1349
eb414681 1350 if (thrashing) {
9a1ea439 1351 if (delayacct)
eb414681
JW
1352 delayacct_thrashing_end();
1353 psi_memstall_leave(&pflags);
1354 }
b1d29ba8 1355
62906027 1356 /*
5ef64cc8
LT
1357 * NOTE! The wait->flags weren't stable until we've done the
1358 * 'finish_wait()', and we could have exited the loop above due
1359 * to a signal, and had a wakeup event happen after the signal
1360 * test but before the 'finish_wait()'.
1361 *
1362 * So only after the finish_wait() can we reliably determine
1363 * if we got woken up or not, so we can now figure out the final
1364 * return value based on that state without races.
1365 *
1366 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
1367 * waiter, but an exclusive one requires WQ_FLAG_DONE.
62906027 1368 */
5ef64cc8
LT
1369 if (behavior == EXCLUSIVE)
1370 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
62906027 1371
2a9127fc 1372 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
62906027
NP
1373}
1374
1375void wait_on_page_bit(struct page *page, int bit_nr)
1376{
1377 wait_queue_head_t *q = page_waitqueue(page);
9a1ea439 1378 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
62906027
NP
1379}
1380EXPORT_SYMBOL(wait_on_page_bit);
1381
1382int wait_on_page_bit_killable(struct page *page, int bit_nr)
1383{
1384 wait_queue_head_t *q = page_waitqueue(page);
9a1ea439 1385 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, SHARED);
cbbce822 1386}
4343d008 1387EXPORT_SYMBOL(wait_on_page_bit_killable);
cbbce822 1388
9a1ea439
HD
1389/**
1390 * put_and_wait_on_page_locked - Drop a reference and wait for it to be unlocked
1391 * @page: The page to wait for.
48054625 1392 * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
9a1ea439
HD
1393 *
1394 * The caller should hold a reference on @page. They expect the page to
1395 * become unlocked relatively soon, but do not wish to hold up migration
1396 * (for example) by holding the reference while waiting for the page to
1397 * come unlocked. After this function returns, the caller should not
1398 * dereference @page.
48054625
MWO
1399 *
1400 * Return: 0 if the page was unlocked or -EINTR if interrupted by a signal.
9a1ea439 1401 */
48054625 1402int put_and_wait_on_page_locked(struct page *page, int state)
9a1ea439
HD
1403{
1404 wait_queue_head_t *q;
1405
1406 page = compound_head(page);
1407 q = page_waitqueue(page);
48054625 1408 return wait_on_page_bit_common(q, page, PG_locked, state, DROP);
9a1ea439
HD
1409}
1410
385e1ca5
DH
1411/**
1412 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
697f619f
RD
1413 * @page: Page defining the wait queue of interest
1414 * @waiter: Waiter to add to the queue
385e1ca5
DH
1415 *
1416 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1417 */
ac6424b9 1418void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
385e1ca5
DH
1419{
1420 wait_queue_head_t *q = page_waitqueue(page);
1421 unsigned long flags;
1422
1423 spin_lock_irqsave(&q->lock, flags);
9c3a815f 1424 __add_wait_queue_entry_tail(q, waiter);
62906027 1425 SetPageWaiters(page);
385e1ca5
DH
1426 spin_unlock_irqrestore(&q->lock, flags);
1427}
1428EXPORT_SYMBOL_GPL(add_page_wait_queue);
1429
b91e1302
LT
1430#ifndef clear_bit_unlock_is_negative_byte
1431
1432/*
1433 * PG_waiters is the high bit in the same byte as PG_lock.
1434 *
1435 * On x86 (and on many other architectures), we can clear PG_lock and
1436 * test the sign bit at the same time. But if the architecture does
1437 * not support that special operation, we just do this all by hand
1438 * instead.
1439 *
1440 * The read of PG_waiters has to be after (or concurrently with) PG_locked
ffceeb62 1441 * being cleared, but a memory barrier should be unnecessary since it is
b91e1302
LT
1442 * in the same byte as PG_locked.
1443 */
1444static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1445{
1446 clear_bit_unlock(nr, mem);
1447 /* smp_mb__after_atomic(); */
98473f9f 1448 return test_bit(PG_waiters, mem);
b91e1302
LT
1449}
1450
1451#endif
1452
1da177e4 1453/**
485bb99b 1454 * unlock_page - unlock a locked page
1da177e4
LT
1455 * @page: the page
1456 *
0e9aa675 1457 * Unlocks the page and wakes up sleepers in wait_on_page_locked().
1da177e4 1458 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
da3dae54 1459 * mechanism between PageLocked pages and PageWriteback pages is shared.
1da177e4
LT
1460 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1461 *
b91e1302
LT
1462 * Note that this depends on PG_waiters being the sign bit in the byte
1463 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1464 * clear the PG_locked bit and test PG_waiters at the same time fairly
1465 * portably (architectures that do LL/SC can test any bit, while x86 can
1466 * test the sign bit).
1da177e4 1467 */
920c7a5d 1468void unlock_page(struct page *page)
1da177e4 1469{
b91e1302 1470 BUILD_BUG_ON(PG_waiters != 7);
48c935ad 1471 page = compound_head(page);
309381fe 1472 VM_BUG_ON_PAGE(!PageLocked(page), page);
b91e1302
LT
1473 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1474 wake_up_page_bit(page, PG_locked);
1da177e4
LT
1475}
1476EXPORT_SYMBOL(unlock_page);
1477
73e10ded
DH
1478/**
1479 * end_page_private_2 - Clear PG_private_2 and release any waiters
1480 * @page: The page
1481 *
1482 * Clear the PG_private_2 bit on a page and wake up any sleepers waiting for
1483 * this. The page ref held for PG_private_2 being set is released.
1484 *
1485 * This is, for example, used when a netfs page is being written to a local
1486 * disk cache, thereby allowing writes to the cache for the same page to be
1487 * serialised.
1488 */
1489void end_page_private_2(struct page *page)
1490{
1491 page = compound_head(page);
1492 VM_BUG_ON_PAGE(!PagePrivate2(page), page);
1493 clear_bit_unlock(PG_private_2, &page->flags);
1494 wake_up_page_bit(page, PG_private_2);
1495 put_page(page);
1496}
1497EXPORT_SYMBOL(end_page_private_2);
1498
1499/**
1500 * wait_on_page_private_2 - 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.
1504 */
1505void wait_on_page_private_2(struct page *page)
1506{
1507 page = compound_head(page);
1508 while (PagePrivate2(page))
1509 wait_on_page_bit(page, PG_private_2);
1510}
1511EXPORT_SYMBOL(wait_on_page_private_2);
1512
1513/**
1514 * wait_on_page_private_2_killable - Wait for PG_private_2 to be cleared on a page
1515 * @page: The page to wait on
1516 *
1517 * Wait for PG_private_2 (aka PG_fscache) to be cleared on a page or until a
1518 * fatal signal is received by the calling task.
1519 *
1520 * Return:
1521 * - 0 if successful.
1522 * - -EINTR if a fatal signal was encountered.
1523 */
1524int wait_on_page_private_2_killable(struct page *page)
1525{
1526 int ret = 0;
1527
1528 page = compound_head(page);
1529 while (PagePrivate2(page)) {
1530 ret = wait_on_page_bit_killable(page, PG_private_2);
1531 if (ret < 0)
1532 break;
1533 }
1534
1535 return ret;
1536}
1537EXPORT_SYMBOL(wait_on_page_private_2_killable);
1538
485bb99b
RD
1539/**
1540 * end_page_writeback - end writeback against a page
1541 * @page: the page
1da177e4
LT
1542 */
1543void end_page_writeback(struct page *page)
1544{
888cf2db
MG
1545 /*
1546 * TestClearPageReclaim could be used here but it is an atomic
1547 * operation and overkill in this particular case. Failing to
1548 * shuffle a page marked for immediate reclaim is too mild to
1549 * justify taking an atomic operation penalty at the end of
1550 * ever page writeback.
1551 */
1552 if (PageReclaim(page)) {
1553 ClearPageReclaim(page);
ac6aadb2 1554 rotate_reclaimable_page(page);
888cf2db 1555 }
ac6aadb2 1556
073861ed
HD
1557 /*
1558 * Writeback does not hold a page reference of its own, relying
1559 * on truncation to wait for the clearing of PG_writeback.
1560 * But here we must make sure that the page is not freed and
1561 * reused before the wake_up_page().
1562 */
1563 get_page(page);
ac6aadb2
MS
1564 if (!test_clear_page_writeback(page))
1565 BUG();
1566
4e857c58 1567 smp_mb__after_atomic();
1da177e4 1568 wake_up_page(page, PG_writeback);
073861ed 1569 put_page(page);
1da177e4
LT
1570}
1571EXPORT_SYMBOL(end_page_writeback);
1572
57d99845
MW
1573/*
1574 * After completing I/O on a page, call this routine to update the page
1575 * flags appropriately
1576 */
c11f0c0b 1577void page_endio(struct page *page, bool is_write, int err)
57d99845 1578{
c11f0c0b 1579 if (!is_write) {
57d99845
MW
1580 if (!err) {
1581 SetPageUptodate(page);
1582 } else {
1583 ClearPageUptodate(page);
1584 SetPageError(page);
1585 }
1586 unlock_page(page);
abf54548 1587 } else {
57d99845 1588 if (err) {
dd8416c4
MK
1589 struct address_space *mapping;
1590
57d99845 1591 SetPageError(page);
dd8416c4
MK
1592 mapping = page_mapping(page);
1593 if (mapping)
1594 mapping_set_error(mapping, err);
57d99845
MW
1595 }
1596 end_page_writeback(page);
1597 }
1598}
1599EXPORT_SYMBOL_GPL(page_endio);
1600
485bb99b
RD
1601/**
1602 * __lock_page - get a lock on the page, assuming we need to sleep to get it
87066755 1603 * @__page: the page to lock
1da177e4 1604 */
62906027 1605void __lock_page(struct page *__page)
1da177e4 1606{
62906027
NP
1607 struct page *page = compound_head(__page);
1608 wait_queue_head_t *q = page_waitqueue(page);
9a1ea439
HD
1609 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE,
1610 EXCLUSIVE);
1da177e4
LT
1611}
1612EXPORT_SYMBOL(__lock_page);
1613
62906027 1614int __lock_page_killable(struct page *__page)
2687a356 1615{
62906027
NP
1616 struct page *page = compound_head(__page);
1617 wait_queue_head_t *q = page_waitqueue(page);
9a1ea439
HD
1618 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE,
1619 EXCLUSIVE);
2687a356 1620}
18bc0bbd 1621EXPORT_SYMBOL_GPL(__lock_page_killable);
2687a356 1622
dd3e6d50
JA
1623int __lock_page_async(struct page *page, struct wait_page_queue *wait)
1624{
f32b5dd7
MWO
1625 struct wait_queue_head *q = page_waitqueue(page);
1626 int ret = 0;
1627
1628 wait->page = page;
1629 wait->bit_nr = PG_locked;
1630
1631 spin_lock_irq(&q->lock);
1632 __add_wait_queue_entry_tail(q, &wait->wait);
1633 SetPageWaiters(page);
1634 ret = !trylock_page(page);
1635 /*
1636 * If we were successful now, we know we're still on the
1637 * waitqueue as we're still under the lock. This means it's
1638 * safe to remove and return success, we know the callback
1639 * isn't going to trigger.
1640 */
1641 if (!ret)
1642 __remove_wait_queue(q, &wait->wait);
1643 else
1644 ret = -EIOCBQUEUED;
1645 spin_unlock_irq(&q->lock);
1646 return ret;
dd3e6d50
JA
1647}
1648
9a95f3cf
PC
1649/*
1650 * Return values:
c1e8d7c6 1651 * 1 - page is locked; mmap_lock is still held.
9a95f3cf 1652 * 0 - page is not locked.
3e4e28c5 1653 * mmap_lock has been released (mmap_read_unlock(), unless flags had both
9a95f3cf 1654 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
c1e8d7c6 1655 * which case mmap_lock is still held.
9a95f3cf
PC
1656 *
1657 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
c1e8d7c6 1658 * with the page locked and the mmap_lock unperturbed.
9a95f3cf 1659 */
d065bd81
ML
1660int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1661 unsigned int flags)
1662{
4064b982 1663 if (fault_flag_allow_retry_first(flags)) {
37b23e05 1664 /*
c1e8d7c6 1665 * CAUTION! In this case, mmap_lock is not released
37b23e05
KM
1666 * even though return 0.
1667 */
1668 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1669 return 0;
1670
d8ed45c5 1671 mmap_read_unlock(mm);
37b23e05
KM
1672 if (flags & FAULT_FLAG_KILLABLE)
1673 wait_on_page_locked_killable(page);
1674 else
318b275f 1675 wait_on_page_locked(page);
d065bd81 1676 return 0;
800bca7c
HL
1677 }
1678 if (flags & FAULT_FLAG_KILLABLE) {
1679 int ret;
37b23e05 1680
800bca7c
HL
1681 ret = __lock_page_killable(page);
1682 if (ret) {
1683 mmap_read_unlock(mm);
1684 return 0;
1685 }
1686 } else {
1687 __lock_page(page);
d065bd81 1688 }
800bca7c
HL
1689 return 1;
1690
d065bd81
ML
1691}
1692
e7b563bb 1693/**
0d3f9296
MW
1694 * page_cache_next_miss() - Find the next gap in the page cache.
1695 * @mapping: Mapping.
1696 * @index: Index.
1697 * @max_scan: Maximum range to search.
e7b563bb 1698 *
0d3f9296
MW
1699 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
1700 * gap with the lowest index.
e7b563bb 1701 *
0d3f9296
MW
1702 * This function may be called under the rcu_read_lock. However, this will
1703 * not atomically search a snapshot of the cache at a single point in time.
1704 * For example, if a gap is created at index 5, then subsequently a gap is
1705 * created at index 10, page_cache_next_miss covering both indices may
1706 * return 10 if called under the rcu_read_lock.
e7b563bb 1707 *
0d3f9296
MW
1708 * Return: The index of the gap if found, otherwise an index outside the
1709 * range specified (in which case 'return - index >= max_scan' will be true).
1710 * In the rare case of index wrap-around, 0 will be returned.
e7b563bb 1711 */
0d3f9296 1712pgoff_t page_cache_next_miss(struct address_space *mapping,
e7b563bb
JW
1713 pgoff_t index, unsigned long max_scan)
1714{
0d3f9296 1715 XA_STATE(xas, &mapping->i_pages, index);
e7b563bb 1716
0d3f9296
MW
1717 while (max_scan--) {
1718 void *entry = xas_next(&xas);
1719 if (!entry || xa_is_value(entry))
e7b563bb 1720 break;
0d3f9296 1721 if (xas.xa_index == 0)
e7b563bb
JW
1722 break;
1723 }
1724
0d3f9296 1725 return xas.xa_index;
e7b563bb 1726}
0d3f9296 1727EXPORT_SYMBOL(page_cache_next_miss);
e7b563bb
JW
1728
1729/**
2346a560 1730 * page_cache_prev_miss() - Find the previous gap in the page cache.
0d3f9296
MW
1731 * @mapping: Mapping.
1732 * @index: Index.
1733 * @max_scan: Maximum range to search.
e7b563bb 1734 *
0d3f9296
MW
1735 * Search the range [max(index - max_scan + 1, 0), index] for the
1736 * gap with the highest index.
e7b563bb 1737 *
0d3f9296
MW
1738 * This function may be called under the rcu_read_lock. However, this will
1739 * not atomically search a snapshot of the cache at a single point in time.
1740 * For example, if a gap is created at index 10, then subsequently a gap is
1741 * created at index 5, page_cache_prev_miss() covering both indices may
1742 * return 5 if called under the rcu_read_lock.
e7b563bb 1743 *
0d3f9296
MW
1744 * Return: The index of the gap if found, otherwise an index outside the
1745 * range specified (in which case 'index - return >= max_scan' will be true).
1746 * In the rare case of wrap-around, ULONG_MAX will be returned.
e7b563bb 1747 */
0d3f9296 1748pgoff_t page_cache_prev_miss(struct address_space *mapping,
e7b563bb
JW
1749 pgoff_t index, unsigned long max_scan)
1750{
0d3f9296 1751 XA_STATE(xas, &mapping->i_pages, index);
e7b563bb 1752
0d3f9296
MW
1753 while (max_scan--) {
1754 void *entry = xas_prev(&xas);
1755 if (!entry || xa_is_value(entry))
e7b563bb 1756 break;
0d3f9296 1757 if (xas.xa_index == ULONG_MAX)
e7b563bb
JW
1758 break;
1759 }
1760
0d3f9296 1761 return xas.xa_index;
e7b563bb 1762}
0d3f9296 1763EXPORT_SYMBOL(page_cache_prev_miss);
e7b563bb 1764
44835d20 1765/*
bc5a3011 1766 * mapping_get_entry - Get a page cache entry.
485bb99b 1767 * @mapping: the address_space to search
a6de4b48 1768 * @index: The page cache index.
0cd6144a
JW
1769 *
1770 * Looks up the page cache slot at @mapping & @offset. If there is a
a6de4b48 1771 * page cache page, the head page is returned with an increased refcount.
485bb99b 1772 *
139b6a6f
JW
1773 * If the slot holds a shadow entry of a previously evicted page, or a
1774 * swap entry from shmem/tmpfs, it is returned.
0cd6144a 1775 *
a6de4b48 1776 * Return: The head page or shadow entry, %NULL if nothing is found.
1da177e4 1777 */
bc5a3011
MWO
1778static struct page *mapping_get_entry(struct address_space *mapping,
1779 pgoff_t index)
1da177e4 1780{
a6de4b48 1781 XA_STATE(xas, &mapping->i_pages, index);
4101196b 1782 struct page *page;
1da177e4 1783
a60637c8
NP
1784 rcu_read_lock();
1785repeat:
4c7472c0
MW
1786 xas_reset(&xas);
1787 page = xas_load(&xas);
1788 if (xas_retry(&xas, page))
1789 goto repeat;
1790 /*
1791 * A shadow entry of a recently evicted page, or a swap entry from
1792 * shmem/tmpfs. Return it without attempting to raise page count.
1793 */
1794 if (!page || xa_is_value(page))
1795 goto out;
83929372 1796
4101196b 1797 if (!page_cache_get_speculative(page))
4c7472c0 1798 goto repeat;
83929372 1799
4c7472c0 1800 /*
4101196b 1801 * Has the page moved or been split?
4c7472c0
MW
1802 * This is part of the lockless pagecache protocol. See
1803 * include/linux/pagemap.h for details.
1804 */
1805 if (unlikely(page != xas_reload(&xas))) {
4101196b 1806 put_page(page);
4c7472c0 1807 goto repeat;
a60637c8 1808 }
27d20fdd 1809out:
a60637c8
NP
1810 rcu_read_unlock();
1811
1da177e4
LT
1812 return page;
1813}
1da177e4 1814
0cd6144a 1815/**
2294b32e
MWO
1816 * pagecache_get_page - Find and get a reference to a page.
1817 * @mapping: The address_space to search.
1818 * @index: The page index.
1819 * @fgp_flags: %FGP flags modify how the page is returned.
1820 * @gfp_mask: Memory allocation flags to use if %FGP_CREAT is specified.
1da177e4 1821 *
2294b32e 1822 * Looks up the page cache entry at @mapping & @index.
0cd6144a 1823 *
2294b32e 1824 * @fgp_flags can be zero or more of these flags:
0e056eb5 1825 *
2294b32e
MWO
1826 * * %FGP_ACCESSED - The page will be marked accessed.
1827 * * %FGP_LOCK - The page is returned locked.
a8cf7f27
MWO
1828 * * %FGP_HEAD - If the page is present and a THP, return the head page
1829 * rather than the exact page specified by the index.
44835d20
MWO
1830 * * %FGP_ENTRY - If there is a shadow / swap / DAX entry, return it
1831 * instead of allocating a new page to replace it.
2294b32e
MWO
1832 * * %FGP_CREAT - If no page is present then a new page is allocated using
1833 * @gfp_mask and added to the page cache and the VM's LRU list.
1834 * The page is returned locked and with an increased refcount.
1835 * * %FGP_FOR_MMAP - The caller wants to do its own locking dance if the
1836 * page is already in cache. If the page was allocated, unlock it before
1837 * returning so the caller can do the same dance.
605cad83
YS
1838 * * %FGP_WRITE - The page will be written
1839 * * %FGP_NOFS - __GFP_FS will get cleared in gfp mask
1840 * * %FGP_NOWAIT - Don't get blocked by page lock
1da177e4 1841 *
2294b32e
MWO
1842 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
1843 * if the %GFP flags specified for %FGP_CREAT are atomic.
1da177e4 1844 *
2457aec6 1845 * If there is a page cache page, it is returned with an increased refcount.
a862f68a 1846 *
2294b32e 1847 * Return: The found page or %NULL otherwise.
1da177e4 1848 */
2294b32e
MWO
1849struct page *pagecache_get_page(struct address_space *mapping, pgoff_t index,
1850 int fgp_flags, gfp_t gfp_mask)
1da177e4 1851{
eb2be189 1852 struct page *page;
2457aec6 1853
1da177e4 1854repeat:
bc5a3011 1855 page = mapping_get_entry(mapping, index);
44835d20
MWO
1856 if (xa_is_value(page)) {
1857 if (fgp_flags & FGP_ENTRY)
1858 return page;
2457aec6 1859 page = NULL;
44835d20 1860 }
2457aec6
MG
1861 if (!page)
1862 goto no_page;
1863
1864 if (fgp_flags & FGP_LOCK) {
1865 if (fgp_flags & FGP_NOWAIT) {
1866 if (!trylock_page(page)) {
09cbfeaf 1867 put_page(page);
2457aec6
MG
1868 return NULL;
1869 }
1870 } else {
1871 lock_page(page);
1872 }
1873
1874 /* Has the page been truncated? */
a8cf7f27 1875 if (unlikely(page->mapping != mapping)) {
2457aec6 1876 unlock_page(page);
09cbfeaf 1877 put_page(page);
2457aec6
MG
1878 goto repeat;
1879 }
a8cf7f27 1880 VM_BUG_ON_PAGE(!thp_contains(page, index), page);
2457aec6
MG
1881 }
1882
c16eb000 1883 if (fgp_flags & FGP_ACCESSED)
2457aec6 1884 mark_page_accessed(page);
b9306a79
YS
1885 else if (fgp_flags & FGP_WRITE) {
1886 /* Clear idle flag for buffer write */
1887 if (page_is_idle(page))
1888 clear_page_idle(page);
1889 }
a8cf7f27
MWO
1890 if (!(fgp_flags & FGP_HEAD))
1891 page = find_subpage(page, index);
2457aec6
MG
1892
1893no_page:
1894 if (!page && (fgp_flags & FGP_CREAT)) {
1895 int err;
f56753ac 1896 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
45f87de5
MH
1897 gfp_mask |= __GFP_WRITE;
1898 if (fgp_flags & FGP_NOFS)
1899 gfp_mask &= ~__GFP_FS;
2457aec6 1900
45f87de5 1901 page = __page_cache_alloc(gfp_mask);
eb2be189
NP
1902 if (!page)
1903 return NULL;
2457aec6 1904
a75d4c33 1905 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
2457aec6
MG
1906 fgp_flags |= FGP_LOCK;
1907
eb39d618 1908 /* Init accessed so avoid atomic mark_page_accessed later */
2457aec6 1909 if (fgp_flags & FGP_ACCESSED)
eb39d618 1910 __SetPageReferenced(page);
2457aec6 1911
2294b32e 1912 err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
eb2be189 1913 if (unlikely(err)) {
09cbfeaf 1914 put_page(page);
eb2be189
NP
1915 page = NULL;
1916 if (err == -EEXIST)
1917 goto repeat;
1da177e4 1918 }
a75d4c33
JB
1919
1920 /*
1921 * add_to_page_cache_lru locks the page, and for mmap we expect
1922 * an unlocked page.
1923 */
1924 if (page && (fgp_flags & FGP_FOR_MMAP))
1925 unlock_page(page);
1da177e4 1926 }
2457aec6 1927
1da177e4
LT
1928 return page;
1929}
2457aec6 1930EXPORT_SYMBOL(pagecache_get_page);
1da177e4 1931
c7bad633
MWO
1932static inline struct page *find_get_entry(struct xa_state *xas, pgoff_t max,
1933 xa_mark_t mark)
1934{
1935 struct page *page;
1936
1937retry:
1938 if (mark == XA_PRESENT)
1939 page = xas_find(xas, max);
1940 else
1941 page = xas_find_marked(xas, max, mark);
1942
1943 if (xas_retry(xas, page))
1944 goto retry;
1945 /*
1946 * A shadow entry of a recently evicted page, a swap
1947 * entry from shmem/tmpfs or a DAX entry. Return it
1948 * without attempting to raise page count.
1949 */
1950 if (!page || xa_is_value(page))
1951 return page;
1952
1953 if (!page_cache_get_speculative(page))
1954 goto reset;
1955
1956 /* Has the page moved or been split? */
1957 if (unlikely(page != xas_reload(xas))) {
1958 put_page(page);
1959 goto reset;
1960 }
1961
1962 return page;
1963reset:
1964 xas_reset(xas);
1965 goto retry;
1966}
1967
0cd6144a
JW
1968/**
1969 * find_get_entries - gang pagecache lookup
1970 * @mapping: The address_space to search
1971 * @start: The starting page cache index
ca122fe4 1972 * @end: The final page index (inclusive).
cf2039af 1973 * @pvec: Where the resulting entries are placed.
0cd6144a
JW
1974 * @indices: The cache indices corresponding to the entries in @entries
1975 *
cf2039af
MWO
1976 * find_get_entries() will search for and return a batch of entries in
1977 * the mapping. The entries are placed in @pvec. find_get_entries()
1978 * takes a reference on any actual pages it returns.
0cd6144a
JW
1979 *
1980 * The search returns a group of mapping-contiguous page cache entries
1981 * with ascending indexes. There may be holes in the indices due to
1982 * not-present pages.
1983 *
139b6a6f
JW
1984 * Any shadow entries of evicted pages, or swap entries from
1985 * shmem/tmpfs, are included in the returned array.
0cd6144a 1986 *
71725ed1
HD
1987 * If it finds a Transparent Huge Page, head or tail, find_get_entries()
1988 * stops at that page: the caller is likely to have a better way to handle
1989 * the compound page as a whole, and then skip its extent, than repeatedly
1990 * calling find_get_entries() to return all its tails.
1991 *
a862f68a 1992 * Return: the number of pages and shadow entries which were found.
0cd6144a 1993 */
ca122fe4 1994unsigned find_get_entries(struct address_space *mapping, pgoff_t start,
cf2039af 1995 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
0cd6144a 1996{
f280bf09
MW
1997 XA_STATE(xas, &mapping->i_pages, start);
1998 struct page *page;
0cd6144a 1999 unsigned int ret = 0;
cf2039af 2000 unsigned nr_entries = PAGEVEC_SIZE;
0cd6144a
JW
2001
2002 rcu_read_lock();
ca122fe4 2003 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
71725ed1
HD
2004 /*
2005 * Terminate early on finding a THP, to allow the caller to
2006 * handle it all at once; but continue if this is hugetlbfs.
2007 */
c7bad633
MWO
2008 if (!xa_is_value(page) && PageTransHuge(page) &&
2009 !PageHuge(page)) {
71725ed1
HD
2010 page = find_subpage(page, xas.xa_index);
2011 nr_entries = ret + 1;
2012 }
c7bad633 2013
f280bf09 2014 indices[ret] = xas.xa_index;
cf2039af 2015 pvec->pages[ret] = page;
0cd6144a
JW
2016 if (++ret == nr_entries)
2017 break;
2018 }
2019 rcu_read_unlock();
cf2039af
MWO
2020
2021 pvec->nr = ret;
0cd6144a
JW
2022 return ret;
2023}
2024
5c211ba2
MWO
2025/**
2026 * find_lock_entries - Find a batch of pagecache entries.
2027 * @mapping: The address_space to search.
2028 * @start: The starting page cache index.
2029 * @end: The final page index (inclusive).
2030 * @pvec: Where the resulting entries are placed.
2031 * @indices: The cache indices of the entries in @pvec.
2032 *
2033 * find_lock_entries() will return a batch of entries from @mapping.
2034 * Swap, shadow and DAX entries are included. Pages are returned
2035 * locked and with an incremented refcount. Pages which are locked by
2036 * somebody else or under writeback are skipped. Only the head page of
2037 * a THP is returned. Pages which are partially outside the range are
2038 * not returned.
2039 *
2040 * The entries have ascending indexes. The indices may not be consecutive
2041 * due to not-present entries, THP pages, pages which could not be locked
2042 * or pages under writeback.
2043 *
2044 * Return: The number of entries which were found.
2045 */
2046unsigned find_lock_entries(struct address_space *mapping, pgoff_t start,
2047 pgoff_t end, struct pagevec *pvec, pgoff_t *indices)
2048{
2049 XA_STATE(xas, &mapping->i_pages, start);
2050 struct page *page;
2051
2052 rcu_read_lock();
2053 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
2054 if (!xa_is_value(page)) {
2055 if (page->index < start)
2056 goto put;
2057 VM_BUG_ON_PAGE(page->index != xas.xa_index, page);
2058 if (page->index + thp_nr_pages(page) - 1 > end)
2059 goto put;
2060 if (!trylock_page(page))
2061 goto put;
2062 if (page->mapping != mapping || PageWriteback(page))
2063 goto unlock;
2064 VM_BUG_ON_PAGE(!thp_contains(page, xas.xa_index),
2065 page);
2066 }
2067 indices[pvec->nr] = xas.xa_index;
2068 if (!pagevec_add(pvec, page))
2069 break;
2070 goto next;
2071unlock:
2072 unlock_page(page);
2073put:
2074 put_page(page);
2075next:
2d11e738
HD
2076 if (!xa_is_value(page) && PageTransHuge(page)) {
2077 unsigned int nr_pages = thp_nr_pages(page);
2078
2079 /* Final THP may cross MAX_LFS_FILESIZE on 32-bit */
2080 xas_set(&xas, page->index + nr_pages);
2081 if (xas.xa_index < nr_pages)
2082 break;
2083 }
5c211ba2
MWO
2084 }
2085 rcu_read_unlock();
2086
2087 return pagevec_count(pvec);
2088}
2089
1da177e4 2090/**
b947cee4 2091 * find_get_pages_range - gang pagecache lookup
1da177e4
LT
2092 * @mapping: The address_space to search
2093 * @start: The starting page index
b947cee4 2094 * @end: The final page index (inclusive)
1da177e4
LT
2095 * @nr_pages: The maximum number of pages
2096 * @pages: Where the resulting pages are placed
2097 *
b947cee4
JK
2098 * find_get_pages_range() will search for and return a group of up to @nr_pages
2099 * pages in the mapping starting at index @start and up to index @end
2100 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
2101 * a reference against the returned pages.
1da177e4
LT
2102 *
2103 * The search returns a group of mapping-contiguous pages with ascending
2104 * indexes. There may be holes in the indices due to not-present pages.
d72dc8a2 2105 * We also update @start to index the next page for the traversal.
1da177e4 2106 *
a862f68a
MR
2107 * Return: the number of pages which were found. If this number is
2108 * smaller than @nr_pages, the end of specified range has been
b947cee4 2109 * reached.
1da177e4 2110 */
b947cee4
JK
2111unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
2112 pgoff_t end, unsigned int nr_pages,
2113 struct page **pages)
1da177e4 2114{
fd1b3cee
MW
2115 XA_STATE(xas, &mapping->i_pages, *start);
2116 struct page *page;
0fc9d104
KK
2117 unsigned ret = 0;
2118
2119 if (unlikely(!nr_pages))
2120 return 0;
a60637c8
NP
2121
2122 rcu_read_lock();
c7bad633 2123 while ((page = find_get_entry(&xas, end, XA_PRESENT))) {
fd1b3cee
MW
2124 /* Skip over shadow, swap and DAX entries */
2125 if (xa_is_value(page))
8079b1c8 2126 continue;
a60637c8 2127
4101196b 2128 pages[ret] = find_subpage(page, xas.xa_index);
b947cee4 2129 if (++ret == nr_pages) {
5d3ee42f 2130 *start = xas.xa_index + 1;
b947cee4
JK
2131 goto out;
2132 }
a60637c8 2133 }
5b280c0c 2134
b947cee4
JK
2135 /*
2136 * We come here when there is no page beyond @end. We take care to not
2137 * overflow the index @start as it confuses some of the callers. This
fd1b3cee 2138 * breaks the iteration when there is a page at index -1 but that is
b947cee4
JK
2139 * already broken anyway.
2140 */
2141 if (end == (pgoff_t)-1)
2142 *start = (pgoff_t)-1;
2143 else
2144 *start = end + 1;
2145out:
a60637c8 2146 rcu_read_unlock();
d72dc8a2 2147
1da177e4
LT
2148 return ret;
2149}
2150
ebf43500
JA
2151/**
2152 * find_get_pages_contig - gang contiguous pagecache lookup
2153 * @mapping: The address_space to search
2154 * @index: The starting page index
2155 * @nr_pages: The maximum number of pages
2156 * @pages: Where the resulting pages are placed
2157 *
2158 * find_get_pages_contig() works exactly like find_get_pages(), except
2159 * that the returned number of pages are guaranteed to be contiguous.
2160 *
a862f68a 2161 * Return: the number of pages which were found.
ebf43500
JA
2162 */
2163unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
2164 unsigned int nr_pages, struct page **pages)
2165{
3ece58a2
MW
2166 XA_STATE(xas, &mapping->i_pages, index);
2167 struct page *page;
0fc9d104
KK
2168 unsigned int ret = 0;
2169
2170 if (unlikely(!nr_pages))
2171 return 0;
a60637c8
NP
2172
2173 rcu_read_lock();
3ece58a2 2174 for (page = xas_load(&xas); page; page = xas_next(&xas)) {
3ece58a2
MW
2175 if (xas_retry(&xas, page))
2176 continue;
2177 /*
2178 * If the entry has been swapped out, we can stop looking.
2179 * No current caller is looking for DAX entries.
2180 */
2181 if (xa_is_value(page))
8079b1c8 2182 break;
ebf43500 2183
4101196b 2184 if (!page_cache_get_speculative(page))
3ece58a2 2185 goto retry;
83929372 2186
4101196b 2187 /* Has the page moved or been split? */
3ece58a2
MW
2188 if (unlikely(page != xas_reload(&xas)))
2189 goto put_page;
a60637c8 2190
4101196b 2191 pages[ret] = find_subpage(page, xas.xa_index);
0fc9d104
KK
2192 if (++ret == nr_pages)
2193 break;
3ece58a2
MW
2194 continue;
2195put_page:
4101196b 2196 put_page(page);
3ece58a2
MW
2197retry:
2198 xas_reset(&xas);
ebf43500 2199 }
a60637c8
NP
2200 rcu_read_unlock();
2201 return ret;
ebf43500 2202}
ef71c15c 2203EXPORT_SYMBOL(find_get_pages_contig);
ebf43500 2204
485bb99b 2205/**
c49f50d1 2206 * find_get_pages_range_tag - Find and return head pages matching @tag.
485bb99b
RD
2207 * @mapping: the address_space to search
2208 * @index: the starting page index
72b045ae 2209 * @end: The final page index (inclusive)
485bb99b
RD
2210 * @tag: the tag index
2211 * @nr_pages: the maximum number of pages
2212 * @pages: where the resulting pages are placed
2213 *
c49f50d1
MWO
2214 * Like find_get_pages(), except we only return head pages which are tagged
2215 * with @tag. @index is updated to the index immediately after the last
2216 * page we return, ready for the next iteration.
a862f68a
MR
2217 *
2218 * Return: the number of pages which were found.
1da177e4 2219 */
72b045ae 2220unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
a6906972 2221 pgoff_t end, xa_mark_t tag, unsigned int nr_pages,
72b045ae 2222 struct page **pages)
1da177e4 2223{
a6906972
MW
2224 XA_STATE(xas, &mapping->i_pages, *index);
2225 struct page *page;
0fc9d104
KK
2226 unsigned ret = 0;
2227
2228 if (unlikely(!nr_pages))
2229 return 0;
a60637c8
NP
2230
2231 rcu_read_lock();
c7bad633 2232 while ((page = find_get_entry(&xas, end, tag))) {
a6906972
MW
2233 /*
2234 * Shadow entries should never be tagged, but this iteration
2235 * is lockless so there is a window for page reclaim to evict
2236 * a page we saw tagged. Skip over it.
2237 */
2238 if (xa_is_value(page))
139b6a6f 2239 continue;
a60637c8 2240
c49f50d1 2241 pages[ret] = page;
72b045ae 2242 if (++ret == nr_pages) {
c49f50d1 2243 *index = page->index + thp_nr_pages(page);
72b045ae
JK
2244 goto out;
2245 }
a60637c8 2246 }
5b280c0c 2247
72b045ae 2248 /*
a6906972 2249 * We come here when we got to @end. We take care to not overflow the
72b045ae 2250 * index @index as it confuses some of the callers. This breaks the
a6906972
MW
2251 * iteration when there is a page at index -1 but that is already
2252 * broken anyway.
72b045ae
JK
2253 */
2254 if (end == (pgoff_t)-1)
2255 *index = (pgoff_t)-1;
2256 else
2257 *index = end + 1;
2258out:
a60637c8 2259 rcu_read_unlock();
1da177e4 2260
1da177e4
LT
2261 return ret;
2262}
72b045ae 2263EXPORT_SYMBOL(find_get_pages_range_tag);
1da177e4 2264
76d42bd9
WF
2265/*
2266 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2267 * a _large_ part of the i/o request. Imagine the worst scenario:
2268 *
2269 * ---R__________________________________________B__________
2270 * ^ reading here ^ bad block(assume 4k)
2271 *
2272 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2273 * => failing the whole request => read(R) => read(R+1) =>
2274 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2275 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2276 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2277 *
2278 * It is going insane. Fix it by quickly scaling down the readahead size.
2279 */
0f8e2db4 2280static void shrink_readahead_size_eio(struct file_ra_state *ra)
76d42bd9 2281{
76d42bd9 2282 ra->ra_pages /= 4;
76d42bd9
WF
2283}
2284
cbd59c48
MWO
2285/*
2286 * filemap_get_read_batch - Get a batch of pages for read
2287 *
2288 * Get a batch of pages which represent a contiguous range of bytes
2289 * in the file. No tail pages will be returned. If @index is in the
2290 * middle of a THP, the entire THP will be returned. The last page in
2291 * the batch may have Readahead set or be not Uptodate so that the
2292 * caller can take the appropriate action.
2293 */
2294static void filemap_get_read_batch(struct address_space *mapping,
2295 pgoff_t index, pgoff_t max, struct pagevec *pvec)
2296{
2297 XA_STATE(xas, &mapping->i_pages, index);
2298 struct page *head;
2299
2300 rcu_read_lock();
2301 for (head = xas_load(&xas); head; head = xas_next(&xas)) {
2302 if (xas_retry(&xas, head))
2303 continue;
2304 if (xas.xa_index > max || xa_is_value(head))
2305 break;
2306 if (!page_cache_get_speculative(head))
2307 goto retry;
2308
2309 /* Has the page moved or been split? */
2310 if (unlikely(head != xas_reload(&xas)))
2311 goto put_page;
2312
2313 if (!pagevec_add(pvec, head))
2314 break;
2315 if (!PageUptodate(head))
2316 break;
2317 if (PageReadahead(head))
2318 break;
2319 xas.xa_index = head->index + thp_nr_pages(head) - 1;
2320 xas.xa_offset = (xas.xa_index >> xas.xa_shift) & XA_CHUNK_MASK;
2321 continue;
2322put_page:
2323 put_page(head);
2324retry:
2325 xas_reset(&xas);
2326 }
2327 rcu_read_unlock();
2328}
2329
68430303
MWO
2330static int filemap_read_page(struct file *file, struct address_space *mapping,
2331 struct page *page)
723ef24b 2332{
723ef24b
KO
2333 int error;
2334
723ef24b 2335 /*
68430303
MWO
2336 * A previous I/O error may have been due to temporary failures,
2337 * eg. multipath errors. PG_error will be set again if readpage
2338 * fails.
723ef24b
KO
2339 */
2340 ClearPageError(page);
2341 /* Start the actual read. The read will unlock the page. */
68430303
MWO
2342 error = mapping->a_ops->readpage(file, page);
2343 if (error)
2344 return error;
723ef24b 2345
aa1ec2f6 2346 error = wait_on_page_locked_killable(page);
68430303
MWO
2347 if (error)
2348 return error;
aa1ec2f6
MWO
2349 if (PageUptodate(page))
2350 return 0;
2351 if (!page->mapping) /* page truncated */
2352 return AOP_TRUNCATED_PAGE;
2353 shrink_readahead_size_eio(&file->f_ra);
2354 return -EIO;
723ef24b
KO
2355}
2356
fce70da3
MWO
2357static bool filemap_range_uptodate(struct address_space *mapping,
2358 loff_t pos, struct iov_iter *iter, struct page *page)
2359{
2360 int count;
2361
2362 if (PageUptodate(page))
2363 return true;
2364 /* pipes can't handle partially uptodate pages */
2365 if (iov_iter_is_pipe(iter))
2366 return false;
2367 if (!mapping->a_ops->is_partially_uptodate)
2368 return false;
2369 if (mapping->host->i_blkbits >= (PAGE_SHIFT + thp_order(page)))
2370 return false;
2371
2372 count = iter->count;
2373 if (page_offset(page) > pos) {
2374 count -= page_offset(page) - pos;
2375 pos = 0;
2376 } else {
2377 pos -= page_offset(page);
2378 }
2379
2380 return mapping->a_ops->is_partially_uptodate(page, pos, count);
2381}
2382
4612aeef
MWO
2383static int filemap_update_page(struct kiocb *iocb,
2384 struct address_space *mapping, struct iov_iter *iter,
fce70da3 2385 struct page *page)
723ef24b 2386{
723ef24b
KO
2387 int error;
2388
87d1d7b6
MWO
2389 if (!trylock_page(page)) {
2390 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2391 return -EAGAIN;
2392 if (!(iocb->ki_flags & IOCB_WAITQ)) {
bd8a1f36 2393 put_and_wait_on_page_locked(page, TASK_KILLABLE);
4612aeef 2394 return AOP_TRUNCATED_PAGE;
bd8a1f36 2395 }
87d1d7b6
MWO
2396 error = __lock_page_async(page, iocb->ki_waitq);
2397 if (error)
2398 return error;
723ef24b 2399 }
723ef24b 2400
bd8a1f36
MWO
2401 if (!page->mapping)
2402 goto truncated;
723ef24b 2403
fce70da3
MWO
2404 error = 0;
2405 if (filemap_range_uptodate(mapping, iocb->ki_pos, iter, page))
2406 goto unlock;
2407
2408 error = -EAGAIN;
2409 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2410 goto unlock;
2411
68430303 2412 error = filemap_read_page(iocb->ki_filp, mapping, page);
68430303 2413 if (error == AOP_TRUNCATED_PAGE)
4612aeef
MWO
2414 put_page(page);
2415 return error;
bd8a1f36
MWO
2416truncated:
2417 unlock_page(page);
2418 put_page(page);
4612aeef 2419 return AOP_TRUNCATED_PAGE;
fce70da3
MWO
2420unlock:
2421 unlock_page(page);
2422 return error;
723ef24b
KO
2423}
2424
f253e185
MWO
2425static int filemap_create_page(struct file *file,
2426 struct address_space *mapping, pgoff_t index,
2427 struct pagevec *pvec)
723ef24b 2428{
723ef24b
KO
2429 struct page *page;
2430 int error;
2431
723ef24b
KO
2432 page = page_cache_alloc(mapping);
2433 if (!page)
f253e185 2434 return -ENOMEM;
723ef24b
KO
2435
2436 error = add_to_page_cache_lru(page, mapping, index,
f253e185
MWO
2437 mapping_gfp_constraint(mapping, GFP_KERNEL));
2438 if (error == -EEXIST)
2439 error = AOP_TRUNCATED_PAGE;
2440 if (error)
2441 goto error;
2442
2443 error = filemap_read_page(file, mapping, page);
2444 if (error)
2445 goto error;
2446
2447 pagevec_add(pvec, page);
2448 return 0;
2449error:
68430303 2450 put_page(page);
f253e185 2451 return error;
723ef24b
KO
2452}
2453
5963fe03
MWO
2454static int filemap_readahead(struct kiocb *iocb, struct file *file,
2455 struct address_space *mapping, struct page *page,
2456 pgoff_t last_index)
2457{
2458 if (iocb->ki_flags & IOCB_NOIO)
2459 return -EAGAIN;
2460 page_cache_async_readahead(mapping, &file->f_ra, file, page,
2461 page->index, last_index - page->index);
2462 return 0;
2463}
2464
3a6bae48 2465static int filemap_get_pages(struct kiocb *iocb, struct iov_iter *iter,
ff993ba1 2466 struct pagevec *pvec)
06c04442
KO
2467{
2468 struct file *filp = iocb->ki_filp;
2469 struct address_space *mapping = filp->f_mapping;
2470 struct file_ra_state *ra = &filp->f_ra;
2471 pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
cbd59c48 2472 pgoff_t last_index;
2642fca6 2473 struct page *page;
cbd59c48 2474 int err = 0;
06c04442 2475
cbd59c48 2476 last_index = DIV_ROUND_UP(iocb->ki_pos + iter->count, PAGE_SIZE);
2642fca6 2477retry:
06c04442
KO
2478 if (fatal_signal_pending(current))
2479 return -EINTR;
2480
cbd59c48 2481 filemap_get_read_batch(mapping, index, last_index, pvec);
2642fca6
MWO
2482 if (!pagevec_count(pvec)) {
2483 if (iocb->ki_flags & IOCB_NOIO)
2484 return -EAGAIN;
2485 page_cache_sync_readahead(mapping, ra, filp, index,
2486 last_index - index);
2487 filemap_get_read_batch(mapping, index, last_index, pvec);
2488 }
f253e185
MWO
2489 if (!pagevec_count(pvec)) {
2490 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2491 return -EAGAIN;
2492 err = filemap_create_page(filp, mapping,
2493 iocb->ki_pos >> PAGE_SHIFT, pvec);
2494 if (err == AOP_TRUNCATED_PAGE)
2642fca6 2495 goto retry;
f253e185
MWO
2496 return err;
2497 }
06c04442 2498
2642fca6
MWO
2499 page = pvec->pages[pagevec_count(pvec) - 1];
2500 if (PageReadahead(page)) {
2501 err = filemap_readahead(iocb, filp, mapping, page, last_index);
2502 if (err)
2503 goto err;
2504 }
2505 if (!PageUptodate(page)) {
2506 if ((iocb->ki_flags & IOCB_WAITQ) && pagevec_count(pvec) > 1)
2507 iocb->ki_flags |= IOCB_NOWAIT;
2508 err = filemap_update_page(iocb, mapping, iter, page);
2509 if (err)
2510 goto err;
06c04442
KO
2511 }
2512
2642fca6 2513 return 0;
cbd59c48 2514err:
2642fca6
MWO
2515 if (err < 0)
2516 put_page(page);
2517 if (likely(--pvec->nr))
ff993ba1 2518 return 0;
4612aeef 2519 if (err == AOP_TRUNCATED_PAGE)
2642fca6
MWO
2520 goto retry;
2521 return err;
06c04442
KO
2522}
2523
485bb99b 2524/**
87fa0f3e
CH
2525 * filemap_read - Read data from the page cache.
2526 * @iocb: The iocb to read.
2527 * @iter: Destination for the data.
2528 * @already_read: Number of bytes already read by the caller.
485bb99b 2529 *
87fa0f3e
CH
2530 * Copies data from the page cache. If the data is not currently present,
2531 * uses the readahead and readpage address_space operations to fetch it.
1da177e4 2532 *
87fa0f3e
CH
2533 * Return: Total number of bytes copied, including those already read by
2534 * the caller. If an error happens before any bytes are copied, returns
2535 * a negative error number.
1da177e4 2536 */
87fa0f3e
CH
2537ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
2538 ssize_t already_read)
1da177e4 2539{
47c27bc4 2540 struct file *filp = iocb->ki_filp;
06c04442 2541 struct file_ra_state *ra = &filp->f_ra;
36e78914 2542 struct address_space *mapping = filp->f_mapping;
1da177e4 2543 struct inode *inode = mapping->host;
ff993ba1
MWO
2544 struct pagevec pvec;
2545 int i, error = 0;
06c04442
KO
2546 bool writably_mapped;
2547 loff_t isize, end_offset;
1da177e4 2548
723ef24b 2549 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
d05c5f7b 2550 return 0;
3644e2d2
KO
2551 if (unlikely(!iov_iter_count(iter)))
2552 return 0;
2553
c2a9737f 2554 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
cbd59c48 2555 pagevec_init(&pvec);
c2a9737f 2556
06c04442 2557 do {
1da177e4 2558 cond_resched();
5abf186a 2559
723ef24b 2560 /*
06c04442
KO
2561 * If we've already successfully copied some data, then we
2562 * can no longer safely return -EIOCBQUEUED. Hence mark
2563 * an async read NOWAIT at that point.
723ef24b 2564 */
87fa0f3e 2565 if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
723ef24b
KO
2566 iocb->ki_flags |= IOCB_NOWAIT;
2567
ff993ba1
MWO
2568 error = filemap_get_pages(iocb, iter, &pvec);
2569 if (error < 0)
06c04442 2570 break;
1da177e4 2571
06c04442
KO
2572 /*
2573 * i_size must be checked after we know the pages are Uptodate.
2574 *
2575 * Checking i_size after the check allows us to calculate
2576 * the correct value for "nr", which means the zero-filled
2577 * part of the page is not copied back to userspace (unless
2578 * another truncate extends the file - this is desired though).
2579 */
2580 isize = i_size_read(inode);
2581 if (unlikely(iocb->ki_pos >= isize))
2582 goto put_pages;
06c04442
KO
2583 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2584
06c04442
KO
2585 /*
2586 * Once we start copying data, we don't want to be touching any
2587 * cachelines that might be contended:
2588 */
2589 writably_mapped = mapping_writably_mapped(mapping);
2590
2591 /*
2592 * When a sequential read accesses a page several times, only
2593 * mark it as accessed the first time.
2594 */
2595 if (iocb->ki_pos >> PAGE_SHIFT !=
2596 ra->prev_pos >> PAGE_SHIFT)
ff993ba1 2597 mark_page_accessed(pvec.pages[0]);
06c04442 2598
ff993ba1 2599 for (i = 0; i < pagevec_count(&pvec); i++) {
cbd59c48
MWO
2600 struct page *page = pvec.pages[i];
2601 size_t page_size = thp_size(page);
2602 size_t offset = iocb->ki_pos & (page_size - 1);
2603 size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2604 page_size - offset);
2605 size_t copied;
06c04442 2606
cbd59c48
MWO
2607 if (end_offset < page_offset(page))
2608 break;
2609 if (i > 0)
2610 mark_page_accessed(page);
06c04442
KO
2611 /*
2612 * If users can be writing to this page using arbitrary
2613 * virtual addresses, take care about potential aliasing
2614 * before reading the page on the kernel side.
2615 */
cbd59c48
MWO
2616 if (writably_mapped) {
2617 int j;
2618
2619 for (j = 0; j < thp_nr_pages(page); j++)
2620 flush_dcache_page(page + j);
2621 }
06c04442 2622
cbd59c48 2623 copied = copy_page_to_iter(page, offset, bytes, iter);
06c04442 2624
87fa0f3e 2625 already_read += copied;
06c04442
KO
2626 iocb->ki_pos += copied;
2627 ra->prev_pos = iocb->ki_pos;
2628
2629 if (copied < bytes) {
2630 error = -EFAULT;
2631 break;
2632 }
1da177e4 2633 }
06c04442 2634put_pages:
ff993ba1
MWO
2635 for (i = 0; i < pagevec_count(&pvec); i++)
2636 put_page(pvec.pages[i]);
cbd59c48 2637 pagevec_reinit(&pvec);
06c04442 2638 } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
1da177e4 2639
0c6aa263 2640 file_accessed(filp);
06c04442 2641
87fa0f3e 2642 return already_read ? already_read : error;
1da177e4 2643}
87fa0f3e 2644EXPORT_SYMBOL_GPL(filemap_read);
1da177e4 2645
485bb99b 2646/**
6abd2322 2647 * generic_file_read_iter - generic filesystem read routine
485bb99b 2648 * @iocb: kernel I/O control block
6abd2322 2649 * @iter: destination for the data read
485bb99b 2650 *
6abd2322 2651 * This is the "read_iter()" routine for all filesystems
1da177e4 2652 * that can use the page cache directly.
41da51bc
AG
2653 *
2654 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
2655 * be returned when no data can be read without waiting for I/O requests
2656 * to complete; it doesn't prevent readahead.
2657 *
2658 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
2659 * requests shall be made for the read or for readahead. When no data
2660 * can be read, -EAGAIN shall be returned. When readahead would be
2661 * triggered, a partial, possibly empty read shall be returned.
2662 *
a862f68a
MR
2663 * Return:
2664 * * number of bytes copied, even for partial reads
41da51bc 2665 * * negative error code (or 0 if IOCB_NOIO) if nothing was read
1da177e4
LT
2666 */
2667ssize_t
ed978a81 2668generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
1da177e4 2669{
e7080a43 2670 size_t count = iov_iter_count(iter);
47c27bc4 2671 ssize_t retval = 0;
e7080a43
NS
2672
2673 if (!count)
826ea860 2674 return 0; /* skip atime */
1da177e4 2675
2ba48ce5 2676 if (iocb->ki_flags & IOCB_DIRECT) {
47c27bc4 2677 struct file *file = iocb->ki_filp;
ed978a81
AV
2678 struct address_space *mapping = file->f_mapping;
2679 struct inode *inode = mapping->host;
543ade1f 2680 loff_t size;
1da177e4 2681
1da177e4 2682 size = i_size_read(inode);
6be96d3a 2683 if (iocb->ki_flags & IOCB_NOWAIT) {
7a60d6d7
JA
2684 if (filemap_range_needs_writeback(mapping, iocb->ki_pos,
2685 iocb->ki_pos + count - 1))
6be96d3a
GR
2686 return -EAGAIN;
2687 } else {
2688 retval = filemap_write_and_wait_range(mapping,
2689 iocb->ki_pos,
2690 iocb->ki_pos + count - 1);
2691 if (retval < 0)
826ea860 2692 return retval;
6be96d3a 2693 }
d8d3d94b 2694
0d5b0cf2
CH
2695 file_accessed(file);
2696
5ecda137 2697 retval = mapping->a_ops->direct_IO(iocb, iter);
c3a69024 2698 if (retval >= 0) {
c64fb5c7 2699 iocb->ki_pos += retval;
5ecda137 2700 count -= retval;
9fe55eea 2701 }
ab2125df
PB
2702 if (retval != -EIOCBQUEUED)
2703 iov_iter_revert(iter, count - iov_iter_count(iter));
66f998f6 2704
9fe55eea
SW
2705 /*
2706 * Btrfs can have a short DIO read if we encounter
2707 * compressed extents, so if there was an error, or if
2708 * we've already read everything we wanted to, or if
2709 * there was a short read because we hit EOF, go ahead
2710 * and return. Otherwise fallthrough to buffered io for
fbbbad4b
MW
2711 * the rest of the read. Buffered reads will not work for
2712 * DAX files, so don't bother trying.
9fe55eea 2713 */
5ecda137 2714 if (retval < 0 || !count || iocb->ki_pos >= size ||
0d5b0cf2 2715 IS_DAX(inode))
826ea860 2716 return retval;
1da177e4
LT
2717 }
2718
826ea860 2719 return filemap_read(iocb, iter, retval);
1da177e4 2720}
ed978a81 2721EXPORT_SYMBOL(generic_file_read_iter);
1da177e4 2722
54fa39ac
MWO
2723static inline loff_t page_seek_hole_data(struct xa_state *xas,
2724 struct address_space *mapping, struct page *page,
2725 loff_t start, loff_t end, bool seek_data)
41139aa4 2726{
54fa39ac
MWO
2727 const struct address_space_operations *ops = mapping->a_ops;
2728 size_t offset, bsz = i_blocksize(mapping->host);
2729
41139aa4 2730 if (xa_is_value(page) || PageUptodate(page))
54fa39ac
MWO
2731 return seek_data ? start : end;
2732 if (!ops->is_partially_uptodate)
2733 return seek_data ? end : start;
2734
2735 xas_pause(xas);
2736 rcu_read_unlock();
2737 lock_page(page);
2738 if (unlikely(page->mapping != mapping))
2739 goto unlock;
2740
2741 offset = offset_in_thp(page, start) & ~(bsz - 1);
2742
2743 do {
2744 if (ops->is_partially_uptodate(page, offset, bsz) == seek_data)
2745 break;
2746 start = (start + bsz) & ~(bsz - 1);
2747 offset += bsz;
2748 } while (offset < thp_size(page));
2749unlock:
2750 unlock_page(page);
2751 rcu_read_lock();
2752 return start;
41139aa4
MWO
2753}
2754
2755static inline
2756unsigned int seek_page_size(struct xa_state *xas, struct page *page)
2757{
2758 if (xa_is_value(page))
2759 return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
2760 return thp_size(page);
2761}
2762
2763/**
2764 * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
2765 * @mapping: Address space to search.
2766 * @start: First byte to consider.
2767 * @end: Limit of search (exclusive).
2768 * @whence: Either SEEK_HOLE or SEEK_DATA.
2769 *
2770 * If the page cache knows which blocks contain holes and which blocks
2771 * contain data, your filesystem can use this function to implement
2772 * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are
2773 * entirely memory-based such as tmpfs, and filesystems which support
2774 * unwritten extents.
2775 *
2776 * Return: The requested offset on successs, or -ENXIO if @whence specifies
2777 * SEEK_DATA and there is no data after @start. There is an implicit hole
2778 * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
2779 * and @end contain data.
2780 */
2781loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
2782 loff_t end, int whence)
2783{
2784 XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
ed98b015 2785 pgoff_t max = (end - 1) >> PAGE_SHIFT;
41139aa4
MWO
2786 bool seek_data = (whence == SEEK_DATA);
2787 struct page *page;
2788
2789 if (end <= start)
2790 return -ENXIO;
2791
2792 rcu_read_lock();
2793 while ((page = find_get_entry(&xas, max, XA_PRESENT))) {
ed98b015
HD
2794 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
2795 unsigned int seek_size;
41139aa4
MWO
2796
2797 if (start < pos) {
2798 if (!seek_data)
2799 goto unlock;
2800 start = pos;
2801 }
2802
ed98b015
HD
2803 seek_size = seek_page_size(&xas, page);
2804 pos = round_up(pos + 1, seek_size);
54fa39ac
MWO
2805 start = page_seek_hole_data(&xas, mapping, page, start, pos,
2806 seek_data);
2807 if (start < pos)
41139aa4 2808 goto unlock;
ed98b015
HD
2809 if (start >= end)
2810 break;
2811 if (seek_size > PAGE_SIZE)
2812 xas_set(&xas, pos >> PAGE_SHIFT);
41139aa4
MWO
2813 if (!xa_is_value(page))
2814 put_page(page);
2815 }
41139aa4 2816 if (seek_data)
ed98b015 2817 start = -ENXIO;
41139aa4
MWO
2818unlock:
2819 rcu_read_unlock();
ed98b015 2820 if (page && !xa_is_value(page))
41139aa4 2821 put_page(page);
41139aa4
MWO
2822 if (start > end)
2823 return end;
2824 return start;
2825}
2826
1da177e4 2827#ifdef CONFIG_MMU
1da177e4 2828#define MMAP_LOTSAMISS (100)
6b4c9f44 2829/*
c1e8d7c6 2830 * lock_page_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
6b4c9f44
JB
2831 * @vmf - the vm_fault for this fault.
2832 * @page - the page to lock.
2833 * @fpin - the pointer to the file we may pin (or is already pinned).
2834 *
c1e8d7c6 2835 * This works similar to lock_page_or_retry in that it can drop the mmap_lock.
6b4c9f44 2836 * It differs in that it actually returns the page locked if it returns 1 and 0
c1e8d7c6 2837 * if it couldn't lock the page. If we did have to drop the mmap_lock then fpin
6b4c9f44
JB
2838 * will point to the pinned file and needs to be fput()'ed at a later point.
2839 */
2840static int lock_page_maybe_drop_mmap(struct vm_fault *vmf, struct page *page,
2841 struct file **fpin)
2842{
2843 if (trylock_page(page))
2844 return 1;
2845
8b0f9fa2
LT
2846 /*
2847 * NOTE! This will make us return with VM_FAULT_RETRY, but with
c1e8d7c6 2848 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
8b0f9fa2
LT
2849 * is supposed to work. We have way too many special cases..
2850 */
6b4c9f44
JB
2851 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
2852 return 0;
2853
2854 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
2855 if (vmf->flags & FAULT_FLAG_KILLABLE) {
2856 if (__lock_page_killable(page)) {
2857 /*
c1e8d7c6 2858 * We didn't have the right flags to drop the mmap_lock,
6b4c9f44
JB
2859 * but all fault_handlers only check for fatal signals
2860 * if we return VM_FAULT_RETRY, so we need to drop the
c1e8d7c6 2861 * mmap_lock here and return 0 if we don't have a fpin.
6b4c9f44
JB
2862 */
2863 if (*fpin == NULL)
d8ed45c5 2864 mmap_read_unlock(vmf->vma->vm_mm);
6b4c9f44
JB
2865 return 0;
2866 }
2867 } else
2868 __lock_page(page);
2869 return 1;
2870}
2871
1da177e4 2872
ef00e08e 2873/*
6b4c9f44
JB
2874 * Synchronous readahead happens when we don't even find a page in the page
2875 * cache at all. We don't want to perform IO under the mmap sem, so if we have
2876 * to drop the mmap sem we return the file that was pinned in order for us to do
2877 * that. If we didn't pin a file then we return NULL. The file that is
2878 * returned needs to be fput()'ed when we're done with it.
ef00e08e 2879 */
6b4c9f44 2880static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
ef00e08e 2881{
2a1180f1
JB
2882 struct file *file = vmf->vma->vm_file;
2883 struct file_ra_state *ra = &file->f_ra;
ef00e08e 2884 struct address_space *mapping = file->f_mapping;
fcd9ae4f 2885 DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
6b4c9f44 2886 struct file *fpin = NULL;
e630bfac 2887 unsigned int mmap_miss;
ef00e08e
LT
2888
2889 /* If we don't want any read-ahead, don't bother */
2a1180f1 2890 if (vmf->vma->vm_flags & VM_RAND_READ)
6b4c9f44 2891 return fpin;
275b12bf 2892 if (!ra->ra_pages)
6b4c9f44 2893 return fpin;
ef00e08e 2894
2a1180f1 2895 if (vmf->vma->vm_flags & VM_SEQ_READ) {
6b4c9f44 2896 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
fcd9ae4f 2897 page_cache_sync_ra(&ractl, ra->ra_pages);
6b4c9f44 2898 return fpin;
ef00e08e
LT
2899 }
2900
207d04ba 2901 /* Avoid banging the cache line if not needed */
e630bfac
KS
2902 mmap_miss = READ_ONCE(ra->mmap_miss);
2903 if (mmap_miss < MMAP_LOTSAMISS * 10)
2904 WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
ef00e08e
LT
2905
2906 /*
2907 * Do we miss much more than hit in this file? If so,
2908 * stop bothering with read-ahead. It will only hurt.
2909 */
e630bfac 2910 if (mmap_miss > MMAP_LOTSAMISS)
6b4c9f44 2911 return fpin;
ef00e08e 2912
d30a1100
WF
2913 /*
2914 * mmap read-around
2915 */
6b4c9f44 2916 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
db660d46 2917 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
600e19af
RG
2918 ra->size = ra->ra_pages;
2919 ra->async_size = ra->ra_pages / 4;
db660d46
DH
2920 ractl._index = ra->start;
2921 do_page_cache_ra(&ractl, ra->size, ra->async_size);
6b4c9f44 2922 return fpin;
ef00e08e
LT
2923}
2924
2925/*
2926 * Asynchronous readahead happens when we find the page and PG_readahead,
6b4c9f44 2927 * so we want to possibly extend the readahead further. We return the file that
c1e8d7c6 2928 * was pinned if we have to drop the mmap_lock in order to do IO.
ef00e08e 2929 */
6b4c9f44
JB
2930static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
2931 struct page *page)
ef00e08e 2932{
2a1180f1
JB
2933 struct file *file = vmf->vma->vm_file;
2934 struct file_ra_state *ra = &file->f_ra;
ef00e08e 2935 struct address_space *mapping = file->f_mapping;
6b4c9f44 2936 struct file *fpin = NULL;
e630bfac 2937 unsigned int mmap_miss;
2a1180f1 2938 pgoff_t offset = vmf->pgoff;
ef00e08e
LT
2939
2940 /* If we don't want any read-ahead, don't bother */
5c72feee 2941 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
6b4c9f44 2942 return fpin;
e630bfac
KS
2943 mmap_miss = READ_ONCE(ra->mmap_miss);
2944 if (mmap_miss)
2945 WRITE_ONCE(ra->mmap_miss, --mmap_miss);
6b4c9f44
JB
2946 if (PageReadahead(page)) {
2947 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
2fad6f5d
WF
2948 page_cache_async_readahead(mapping, ra, file,
2949 page, offset, ra->ra_pages);
6b4c9f44
JB
2950 }
2951 return fpin;
ef00e08e
LT
2952}
2953
485bb99b 2954/**
54cb8821 2955 * filemap_fault - read in file data for page fault handling
d0217ac0 2956 * @vmf: struct vm_fault containing details of the fault
485bb99b 2957 *
54cb8821 2958 * filemap_fault() is invoked via the vma operations vector for a
1da177e4
LT
2959 * mapped memory region to read in file data during a page fault.
2960 *
2961 * The goto's are kind of ugly, but this streamlines the normal case of having
2962 * it in the page cache, and handles the special cases reasonably without
2963 * having a lot of duplicated code.
9a95f3cf 2964 *
c1e8d7c6 2965 * vma->vm_mm->mmap_lock must be held on entry.
9a95f3cf 2966 *
c1e8d7c6 2967 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
a4985833 2968 * may be dropped before doing I/O or by lock_page_maybe_drop_mmap().
9a95f3cf 2969 *
c1e8d7c6 2970 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
9a95f3cf
PC
2971 * has not been released.
2972 *
2973 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
a862f68a
MR
2974 *
2975 * Return: bitwise-OR of %VM_FAULT_ codes.
1da177e4 2976 */
2bcd6454 2977vm_fault_t filemap_fault(struct vm_fault *vmf)
1da177e4
LT
2978{
2979 int error;
11bac800 2980 struct file *file = vmf->vma->vm_file;
6b4c9f44 2981 struct file *fpin = NULL;
1da177e4
LT
2982 struct address_space *mapping = file->f_mapping;
2983 struct file_ra_state *ra = &file->f_ra;
2984 struct inode *inode = mapping->host;
ef00e08e 2985 pgoff_t offset = vmf->pgoff;
9ab2594f 2986 pgoff_t max_off;
1da177e4 2987 struct page *page;
2bcd6454 2988 vm_fault_t ret = 0;
1da177e4 2989
9ab2594f
MW
2990 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2991 if (unlikely(offset >= max_off))
5307cc1a 2992 return VM_FAULT_SIGBUS;
1da177e4 2993
1da177e4 2994 /*
49426420 2995 * Do we have something in the page cache already?
1da177e4 2996 */
ef00e08e 2997 page = find_get_page(mapping, offset);
45cac65b 2998 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
1da177e4 2999 /*
ef00e08e
LT
3000 * We found the page, so try async readahead before
3001 * waiting for the lock.
1da177e4 3002 */
6b4c9f44 3003 fpin = do_async_mmap_readahead(vmf, page);
45cac65b 3004 } else if (!page) {
ef00e08e 3005 /* No page in the page cache at all */
ef00e08e 3006 count_vm_event(PGMAJFAULT);
2262185c 3007 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
ef00e08e 3008 ret = VM_FAULT_MAJOR;
6b4c9f44 3009 fpin = do_sync_mmap_readahead(vmf);
ef00e08e 3010retry_find:
a75d4c33
JB
3011 page = pagecache_get_page(mapping, offset,
3012 FGP_CREAT|FGP_FOR_MMAP,
3013 vmf->gfp_mask);
6b4c9f44
JB
3014 if (!page) {
3015 if (fpin)
3016 goto out_retry;
e520e932 3017 return VM_FAULT_OOM;
6b4c9f44 3018 }
1da177e4
LT
3019 }
3020
6b4c9f44
JB
3021 if (!lock_page_maybe_drop_mmap(vmf, page, &fpin))
3022 goto out_retry;
b522c94d
ML
3023
3024 /* Did it get truncated? */
585e5a7b 3025 if (unlikely(compound_head(page)->mapping != mapping)) {
b522c94d
ML
3026 unlock_page(page);
3027 put_page(page);
3028 goto retry_find;
3029 }
520e5ba4 3030 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
b522c94d 3031
1da177e4 3032 /*
d00806b1
NP
3033 * We have a locked page in the page cache, now we need to check
3034 * that it's up-to-date. If not, it is going to be due to an error.
1da177e4 3035 */
d00806b1 3036 if (unlikely(!PageUptodate(page)))
1da177e4
LT
3037 goto page_not_uptodate;
3038
6b4c9f44 3039 /*
c1e8d7c6 3040 * We've made it this far and we had to drop our mmap_lock, now is the
6b4c9f44
JB
3041 * time to return to the upper layer and have it re-find the vma and
3042 * redo the fault.
3043 */
3044 if (fpin) {
3045 unlock_page(page);
3046 goto out_retry;
3047 }
3048
ef00e08e
LT
3049 /*
3050 * Found the page and have a reference on it.
3051 * We must recheck i_size under page lock.
3052 */
9ab2594f
MW
3053 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3054 if (unlikely(offset >= max_off)) {
d00806b1 3055 unlock_page(page);
09cbfeaf 3056 put_page(page);
5307cc1a 3057 return VM_FAULT_SIGBUS;
d00806b1
NP
3058 }
3059
d0217ac0 3060 vmf->page = page;
83c54070 3061 return ret | VM_FAULT_LOCKED;
1da177e4 3062
1da177e4 3063page_not_uptodate:
1da177e4
LT
3064 /*
3065 * Umm, take care of errors if the page isn't up-to-date.
3066 * Try to re-read it _once_. We do this synchronously,
3067 * because there really aren't any performance issues here
3068 * and we need to check for errors.
3069 */
1da177e4 3070 ClearPageError(page);
6b4c9f44 3071 fpin = maybe_unlock_mmap_for_io(vmf, fpin);
994fc28c 3072 error = mapping->a_ops->readpage(file, page);
3ef0f720
MS
3073 if (!error) {
3074 wait_on_page_locked(page);
3075 if (!PageUptodate(page))
3076 error = -EIO;
3077 }
6b4c9f44
JB
3078 if (fpin)
3079 goto out_retry;
09cbfeaf 3080 put_page(page);
d00806b1
NP
3081
3082 if (!error || error == AOP_TRUNCATED_PAGE)
994fc28c 3083 goto retry_find;
1da177e4 3084
0f8e2db4 3085 shrink_readahead_size_eio(ra);
d0217ac0 3086 return VM_FAULT_SIGBUS;
6b4c9f44
JB
3087
3088out_retry:
3089 /*
c1e8d7c6 3090 * We dropped the mmap_lock, we need to return to the fault handler to
6b4c9f44
JB
3091 * re-find the vma and come back and find our hopefully still populated
3092 * page.
3093 */
3094 if (page)
3095 put_page(page);
3096 if (fpin)
3097 fput(fpin);
3098 return ret | VM_FAULT_RETRY;
54cb8821
NP
3099}
3100EXPORT_SYMBOL(filemap_fault);
3101
f9ce0be7 3102static bool filemap_map_pmd(struct vm_fault *vmf, struct page *page)
f1820361 3103{
f9ce0be7
KS
3104 struct mm_struct *mm = vmf->vma->vm_mm;
3105
3106 /* Huge page is mapped? No need to proceed. */
3107 if (pmd_trans_huge(*vmf->pmd)) {
3108 unlock_page(page);
3109 put_page(page);
3110 return true;
3111 }
3112
3113 if (pmd_none(*vmf->pmd) && PageTransHuge(page)) {
3114 vm_fault_t ret = do_set_pmd(vmf, page);
3115 if (!ret) {
3116 /* The page is mapped successfully, reference consumed. */
3117 unlock_page(page);
3118 return true;
3119 }
3120 }
3121
3122 if (pmd_none(*vmf->pmd)) {
3123 vmf->ptl = pmd_lock(mm, vmf->pmd);
3124 if (likely(pmd_none(*vmf->pmd))) {
3125 mm_inc_nr_ptes(mm);
3126 pmd_populate(mm, vmf->pmd, vmf->prealloc_pte);
3127 vmf->prealloc_pte = NULL;
3128 }
3129 spin_unlock(vmf->ptl);
3130 }
3131
3132 /* See comment in handle_pte_fault() */
3133 if (pmd_devmap_trans_unstable(vmf->pmd)) {
3134 unlock_page(page);
3135 put_page(page);
3136 return true;
3137 }
3138
3139 return false;
3140}
3141
3142static struct page *next_uptodate_page(struct page *page,
3143 struct address_space *mapping,
3144 struct xa_state *xas, pgoff_t end_pgoff)
3145{
3146 unsigned long max_idx;
3147
3148 do {
3149 if (!page)
3150 return NULL;
3151 if (xas_retry(xas, page))
3152 continue;
3153 if (xa_is_value(page))
3154 continue;
3155 if (PageLocked(page))
3156 continue;
3157 if (!page_cache_get_speculative(page))
3158 continue;
3159 /* Has the page moved or been split? */
3160 if (unlikely(page != xas_reload(xas)))
3161 goto skip;
3162 if (!PageUptodate(page) || PageReadahead(page))
3163 goto skip;
3164 if (PageHWPoison(page))
3165 goto skip;
3166 if (!trylock_page(page))
3167 goto skip;
3168 if (page->mapping != mapping)
3169 goto unlock;
3170 if (!PageUptodate(page))
3171 goto unlock;
3172 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3173 if (xas->xa_index >= max_idx)
3174 goto unlock;
3175 return page;
3176unlock:
3177 unlock_page(page);
3178skip:
3179 put_page(page);
3180 } while ((page = xas_next_entry(xas, end_pgoff)) != NULL);
3181
3182 return NULL;
3183}
3184
3185static inline struct page *first_map_page(struct address_space *mapping,
3186 struct xa_state *xas,
3187 pgoff_t end_pgoff)
3188{
3189 return next_uptodate_page(xas_find(xas, end_pgoff),
3190 mapping, xas, end_pgoff);
3191}
3192
3193static inline struct page *next_map_page(struct address_space *mapping,
3194 struct xa_state *xas,
3195 pgoff_t end_pgoff)
3196{
3197 return next_uptodate_page(xas_next_entry(xas, end_pgoff),
3198 mapping, xas, end_pgoff);
3199}
3200
3201vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3202 pgoff_t start_pgoff, pgoff_t end_pgoff)
3203{
3204 struct vm_area_struct *vma = vmf->vma;
3205 struct file *file = vma->vm_file;
f1820361 3206 struct address_space *mapping = file->f_mapping;
bae473a4 3207 pgoff_t last_pgoff = start_pgoff;
9d3af4b4 3208 unsigned long addr;
070e807c 3209 XA_STATE(xas, &mapping->i_pages, start_pgoff);
27a83a60 3210 struct page *head, *page;
e630bfac 3211 unsigned int mmap_miss = READ_ONCE(file->f_ra.mmap_miss);
f9ce0be7 3212 vm_fault_t ret = 0;
f1820361
KS
3213
3214 rcu_read_lock();
f9ce0be7
KS
3215 head = first_map_page(mapping, &xas, end_pgoff);
3216 if (!head)
3217 goto out;
f1820361 3218
f9ce0be7
KS
3219 if (filemap_map_pmd(vmf, head)) {
3220 ret = VM_FAULT_NOPAGE;
3221 goto out;
3222 }
f1820361 3223
9d3af4b4
WD
3224 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
3225 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
f9ce0be7 3226 do {
27a83a60 3227 page = find_subpage(head, xas.xa_index);
f9ce0be7 3228 if (PageHWPoison(page))
f1820361
KS
3229 goto unlock;
3230
e630bfac
KS
3231 if (mmap_miss > 0)
3232 mmap_miss--;
7267ec00 3233
9d3af4b4 3234 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
f9ce0be7 3235 vmf->pte += xas.xa_index - last_pgoff;
070e807c 3236 last_pgoff = xas.xa_index;
f9ce0be7
KS
3237
3238 if (!pte_none(*vmf->pte))
7267ec00 3239 goto unlock;
f9ce0be7 3240
46bdb427 3241 /* We're about to handle the fault */
9d3af4b4 3242 if (vmf->address == addr)
46bdb427 3243 ret = VM_FAULT_NOPAGE;
46bdb427 3244
9d3af4b4 3245 do_set_pte(vmf, page, addr);
f9ce0be7 3246 /* no need to invalidate: a not-present page won't be cached */
9d3af4b4 3247 update_mmu_cache(vma, addr, vmf->pte);
27a83a60 3248 unlock_page(head);
f9ce0be7 3249 continue;
f1820361 3250unlock:
27a83a60 3251 unlock_page(head);
27a83a60 3252 put_page(head);
f9ce0be7
KS
3253 } while ((head = next_map_page(mapping, &xas, end_pgoff)) != NULL);
3254 pte_unmap_unlock(vmf->pte, vmf->ptl);
3255out:
f1820361 3256 rcu_read_unlock();
e630bfac 3257 WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss);
f9ce0be7 3258 return ret;
f1820361
KS
3259}
3260EXPORT_SYMBOL(filemap_map_pages);
3261
2bcd6454 3262vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
4fcf1c62 3263{
5df1a672 3264 struct address_space *mapping = vmf->vma->vm_file->f_mapping;
4fcf1c62 3265 struct page *page = vmf->page;
2bcd6454 3266 vm_fault_t ret = VM_FAULT_LOCKED;
4fcf1c62 3267
5df1a672 3268 sb_start_pagefault(mapping->host->i_sb);
11bac800 3269 file_update_time(vmf->vma->vm_file);
4fcf1c62 3270 lock_page(page);
5df1a672 3271 if (page->mapping != mapping) {
4fcf1c62
JK
3272 unlock_page(page);
3273 ret = VM_FAULT_NOPAGE;
3274 goto out;
3275 }
14da9200
JK
3276 /*
3277 * We mark the page dirty already here so that when freeze is in
3278 * progress, we are guaranteed that writeback during freezing will
3279 * see the dirty page and writeprotect it again.
3280 */
3281 set_page_dirty(page);
1d1d1a76 3282 wait_for_stable_page(page);
4fcf1c62 3283out:
5df1a672 3284 sb_end_pagefault(mapping->host->i_sb);
4fcf1c62
JK
3285 return ret;
3286}
4fcf1c62 3287
f0f37e2f 3288const struct vm_operations_struct generic_file_vm_ops = {
54cb8821 3289 .fault = filemap_fault,
f1820361 3290 .map_pages = filemap_map_pages,
4fcf1c62 3291 .page_mkwrite = filemap_page_mkwrite,
1da177e4
LT
3292};
3293
3294/* This is used for a general mmap of a disk file */
3295
3296int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
3297{
3298 struct address_space *mapping = file->f_mapping;
3299
3300 if (!mapping->a_ops->readpage)
3301 return -ENOEXEC;
3302 file_accessed(file);
3303 vma->vm_ops = &generic_file_vm_ops;
3304 return 0;
3305}
1da177e4
LT
3306
3307/*
3308 * This is for filesystems which do not implement ->writepage.
3309 */
3310int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
3311{
3312 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
3313 return -EINVAL;
3314 return generic_file_mmap(file, vma);
3315}
3316#else
4b96a37d 3317vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
45397228 3318{
4b96a37d 3319 return VM_FAULT_SIGBUS;
45397228 3320}
1da177e4
LT
3321int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
3322{
3323 return -ENOSYS;
3324}
3325int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
3326{
3327 return -ENOSYS;
3328}
3329#endif /* CONFIG_MMU */
3330
45397228 3331EXPORT_SYMBOL(filemap_page_mkwrite);
1da177e4
LT
3332EXPORT_SYMBOL(generic_file_mmap);
3333EXPORT_SYMBOL(generic_file_readonly_mmap);
3334
67f9fd91
SL
3335static struct page *wait_on_page_read(struct page *page)
3336{
3337 if (!IS_ERR(page)) {
3338 wait_on_page_locked(page);
3339 if (!PageUptodate(page)) {
09cbfeaf 3340 put_page(page);
67f9fd91
SL
3341 page = ERR_PTR(-EIO);
3342 }
3343 }
3344 return page;
3345}
3346
32b63529 3347static struct page *do_read_cache_page(struct address_space *mapping,
57f6b96c 3348 pgoff_t index,
5e5358e7 3349 int (*filler)(void *, struct page *),
0531b2aa
LT
3350 void *data,
3351 gfp_t gfp)
1da177e4 3352{
eb2be189 3353 struct page *page;
1da177e4
LT
3354 int err;
3355repeat:
3356 page = find_get_page(mapping, index);
3357 if (!page) {
453f85d4 3358 page = __page_cache_alloc(gfp);
eb2be189
NP
3359 if (!page)
3360 return ERR_PTR(-ENOMEM);
e6f67b8c 3361 err = add_to_page_cache_lru(page, mapping, index, gfp);
eb2be189 3362 if (unlikely(err)) {
09cbfeaf 3363 put_page(page);
eb2be189
NP
3364 if (err == -EEXIST)
3365 goto repeat;
22ecdb4f 3366 /* Presumably ENOMEM for xarray node */
1da177e4
LT
3367 return ERR_PTR(err);
3368 }
32b63529
MG
3369
3370filler:
6c45b454
CH
3371 if (filler)
3372 err = filler(data, page);
3373 else
3374 err = mapping->a_ops->readpage(data, page);
3375
1da177e4 3376 if (err < 0) {
09cbfeaf 3377 put_page(page);
32b63529 3378 return ERR_PTR(err);
1da177e4 3379 }
1da177e4 3380
32b63529
MG
3381 page = wait_on_page_read(page);
3382 if (IS_ERR(page))
3383 return page;
3384 goto out;
3385 }
1da177e4
LT
3386 if (PageUptodate(page))
3387 goto out;
3388
ebded027 3389 /*
0e9aa675 3390 * Page is not up to date and may be locked due to one of the following
ebded027
MG
3391 * case a: Page is being filled and the page lock is held
3392 * case b: Read/write error clearing the page uptodate status
3393 * case c: Truncation in progress (page locked)
3394 * case d: Reclaim in progress
3395 *
3396 * Case a, the page will be up to date when the page is unlocked.
3397 * There is no need to serialise on the page lock here as the page
3398 * is pinned so the lock gives no additional protection. Even if the
ce89fddf 3399 * page is truncated, the data is still valid if PageUptodate as
ebded027
MG
3400 * it's a race vs truncate race.
3401 * Case b, the page will not be up to date
3402 * Case c, the page may be truncated but in itself, the data may still
3403 * be valid after IO completes as it's a read vs truncate race. The
3404 * operation must restart if the page is not uptodate on unlock but
3405 * otherwise serialising on page lock to stabilise the mapping gives
3406 * no additional guarantees to the caller as the page lock is
3407 * released before return.
3408 * Case d, similar to truncation. If reclaim holds the page lock, it
3409 * will be a race with remove_mapping that determines if the mapping
3410 * is valid on unlock but otherwise the data is valid and there is
3411 * no need to serialise with page lock.
3412 *
3413 * As the page lock gives no additional guarantee, we optimistically
3414 * wait on the page to be unlocked and check if it's up to date and
3415 * use the page if it is. Otherwise, the page lock is required to
3416 * distinguish between the different cases. The motivation is that we
3417 * avoid spurious serialisations and wakeups when multiple processes
3418 * wait on the same page for IO to complete.
3419 */
3420 wait_on_page_locked(page);
3421 if (PageUptodate(page))
3422 goto out;
3423
3424 /* Distinguish between all the cases under the safety of the lock */
1da177e4 3425 lock_page(page);
ebded027
MG
3426
3427 /* Case c or d, restart the operation */
1da177e4
LT
3428 if (!page->mapping) {
3429 unlock_page(page);
09cbfeaf 3430 put_page(page);
32b63529 3431 goto repeat;
1da177e4 3432 }
ebded027
MG
3433
3434 /* Someone else locked and filled the page in a very small window */
1da177e4
LT
3435 if (PageUptodate(page)) {
3436 unlock_page(page);
3437 goto out;
3438 }
faffdfa0
XT
3439
3440 /*
3441 * A previous I/O error may have been due to temporary
3442 * failures.
3443 * Clear page error before actual read, PG_error will be
3444 * set again if read page fails.
3445 */
3446 ClearPageError(page);
32b63529
MG
3447 goto filler;
3448
c855ff37 3449out:
6fe6900e
NP
3450 mark_page_accessed(page);
3451 return page;
3452}
0531b2aa
LT
3453
3454/**
67f9fd91 3455 * read_cache_page - read into page cache, fill it if needed
0531b2aa
LT
3456 * @mapping: the page's address_space
3457 * @index: the page index
3458 * @filler: function to perform the read
5e5358e7 3459 * @data: first arg to filler(data, page) function, often left as NULL
0531b2aa 3460 *
0531b2aa 3461 * Read into the page cache. If a page already exists, and PageUptodate() is
67f9fd91 3462 * not set, try to fill the page and wait for it to become unlocked.
0531b2aa
LT
3463 *
3464 * If the page does not get brought uptodate, return -EIO.
a862f68a
MR
3465 *
3466 * Return: up to date page on success, ERR_PTR() on failure.
0531b2aa 3467 */
67f9fd91 3468struct page *read_cache_page(struct address_space *mapping,
0531b2aa 3469 pgoff_t index,
5e5358e7 3470 int (*filler)(void *, struct page *),
0531b2aa
LT
3471 void *data)
3472{
d322a8e5
CH
3473 return do_read_cache_page(mapping, index, filler, data,
3474 mapping_gfp_mask(mapping));
0531b2aa 3475}
67f9fd91 3476EXPORT_SYMBOL(read_cache_page);
0531b2aa
LT
3477
3478/**
3479 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
3480 * @mapping: the page's address_space
3481 * @index: the page index
3482 * @gfp: the page allocator flags to use if allocating
3483 *
3484 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
e6f67b8c 3485 * any new page allocations done using the specified allocation flags.
0531b2aa
LT
3486 *
3487 * If the page does not get brought uptodate, return -EIO.
a862f68a
MR
3488 *
3489 * Return: up to date page on success, ERR_PTR() on failure.
0531b2aa
LT
3490 */
3491struct page *read_cache_page_gfp(struct address_space *mapping,
3492 pgoff_t index,
3493 gfp_t gfp)
3494{
6c45b454 3495 return do_read_cache_page(mapping, index, NULL, NULL, gfp);
0531b2aa
LT
3496}
3497EXPORT_SYMBOL(read_cache_page_gfp);
3498
afddba49
NP
3499int pagecache_write_begin(struct file *file, struct address_space *mapping,
3500 loff_t pos, unsigned len, unsigned flags,
3501 struct page **pagep, void **fsdata)
3502{
3503 const struct address_space_operations *aops = mapping->a_ops;
3504
4e02ed4b 3505 return aops->write_begin(file, mapping, pos, len, flags,
afddba49 3506 pagep, fsdata);
afddba49
NP
3507}
3508EXPORT_SYMBOL(pagecache_write_begin);
3509
3510int pagecache_write_end(struct file *file, struct address_space *mapping,
3511 loff_t pos, unsigned len, unsigned copied,
3512 struct page *page, void *fsdata)
3513{
3514 const struct address_space_operations *aops = mapping->a_ops;
afddba49 3515
4e02ed4b 3516 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
afddba49
NP
3517}
3518EXPORT_SYMBOL(pagecache_write_end);
3519
a92853b6
KK
3520/*
3521 * Warn about a page cache invalidation failure during a direct I/O write.
3522 */
3523void dio_warn_stale_pagecache(struct file *filp)
3524{
3525 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3526 char pathname[128];
a92853b6
KK
3527 char *path;
3528
5df1a672 3529 errseq_set(&filp->f_mapping->wb_err, -EIO);
a92853b6
KK
3530 if (__ratelimit(&_rs)) {
3531 path = file_path(filp, pathname, sizeof(pathname));
3532 if (IS_ERR(path))
3533 path = "(unknown)";
3534 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n");
3535 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3536 current->comm);
3537 }
3538}
3539
1da177e4 3540ssize_t
1af5bb49 3541generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
1da177e4
LT
3542{
3543 struct file *file = iocb->ki_filp;
3544 struct address_space *mapping = file->f_mapping;
3545 struct inode *inode = mapping->host;
1af5bb49 3546 loff_t pos = iocb->ki_pos;
1da177e4 3547 ssize_t written;
a969e903
CH
3548 size_t write_len;
3549 pgoff_t end;
1da177e4 3550
0c949334 3551 write_len = iov_iter_count(from);
09cbfeaf 3552 end = (pos + write_len - 1) >> PAGE_SHIFT;
a969e903 3553
6be96d3a
GR
3554 if (iocb->ki_flags & IOCB_NOWAIT) {
3555 /* If there are pages to writeback, return */
5df1a672 3556 if (filemap_range_has_page(file->f_mapping, pos,
35f12f0f 3557 pos + write_len - 1))
6be96d3a
GR
3558 return -EAGAIN;
3559 } else {
3560 written = filemap_write_and_wait_range(mapping, pos,
3561 pos + write_len - 1);
3562 if (written)
3563 goto out;
3564 }
a969e903
CH
3565
3566 /*
3567 * After a write we want buffered reads to be sure to go to disk to get
3568 * the new data. We invalidate clean cached page from the region we're
3569 * about to write. We do this *before* the write so that we can return
6ccfa806 3570 * without clobbering -EIOCBQUEUED from ->direct_IO().
a969e903 3571 */
55635ba7 3572 written = invalidate_inode_pages2_range(mapping,
09cbfeaf 3573 pos >> PAGE_SHIFT, end);
55635ba7
AR
3574 /*
3575 * If a page can not be invalidated, return 0 to fall back
3576 * to buffered write.
3577 */
3578 if (written) {
3579 if (written == -EBUSY)
3580 return 0;
3581 goto out;
a969e903
CH
3582 }
3583
639a93a5 3584 written = mapping->a_ops->direct_IO(iocb, from);
a969e903
CH
3585
3586 /*
3587 * Finally, try again to invalidate clean pages which might have been
3588 * cached by non-direct readahead, or faulted in by get_user_pages()
3589 * if the source of the write was an mmap'ed region of the file
3590 * we're writing. Either one is a pretty crazy thing to do,
3591 * so we don't support it 100%. If this invalidation
3592 * fails, tough, the write still worked...
332391a9
LC
3593 *
3594 * Most of the time we do not need this since dio_complete() will do
3595 * the invalidation for us. However there are some file systems that
3596 * do not end up with dio_complete() being called, so let's not break
80c1fe90
KK
3597 * them by removing it completely.
3598 *
9266a140
KK
3599 * Noticeable example is a blkdev_direct_IO().
3600 *
80c1fe90 3601 * Skip invalidation for async writes or if mapping has no pages.
a969e903 3602 */
9266a140
KK
3603 if (written > 0 && mapping->nrpages &&
3604 invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, end))
3605 dio_warn_stale_pagecache(file);
a969e903 3606
1da177e4 3607 if (written > 0) {
0116651c 3608 pos += written;
639a93a5 3609 write_len -= written;
0116651c
NK
3610 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3611 i_size_write(inode, pos);
1da177e4
LT
3612 mark_inode_dirty(inode);
3613 }
5cb6c6c7 3614 iocb->ki_pos = pos;
1da177e4 3615 }
ab2125df
PB
3616 if (written != -EIOCBQUEUED)
3617 iov_iter_revert(from, write_len - iov_iter_count(from));
a969e903 3618out:
1da177e4
LT
3619 return written;
3620}
3621EXPORT_SYMBOL(generic_file_direct_write);
3622
eb2be189
NP
3623/*
3624 * Find or create a page at the given pagecache position. Return the locked
3625 * page. This function is specifically for buffered writes.
3626 */
54566b2c
NP
3627struct page *grab_cache_page_write_begin(struct address_space *mapping,
3628 pgoff_t index, unsigned flags)
eb2be189 3629{
eb2be189 3630 struct page *page;
bbddabe2 3631 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
0faa70cb 3632
54566b2c 3633 if (flags & AOP_FLAG_NOFS)
2457aec6
MG
3634 fgp_flags |= FGP_NOFS;
3635
3636 page = pagecache_get_page(mapping, index, fgp_flags,
45f87de5 3637 mapping_gfp_mask(mapping));
c585a267 3638 if (page)
2457aec6 3639 wait_for_stable_page(page);
eb2be189 3640
eb2be189
NP
3641 return page;
3642}
54566b2c 3643EXPORT_SYMBOL(grab_cache_page_write_begin);
eb2be189 3644
3b93f911 3645ssize_t generic_perform_write(struct file *file,
afddba49
NP
3646 struct iov_iter *i, loff_t pos)
3647{
3648 struct address_space *mapping = file->f_mapping;
3649 const struct address_space_operations *a_ops = mapping->a_ops;
3650 long status = 0;
3651 ssize_t written = 0;
674b892e
NP
3652 unsigned int flags = 0;
3653
afddba49
NP
3654 do {
3655 struct page *page;
afddba49
NP
3656 unsigned long offset; /* Offset into pagecache page */
3657 unsigned long bytes; /* Bytes to write to page */
3658 size_t copied; /* Bytes copied from user */
3659 void *fsdata;
3660
09cbfeaf
KS
3661 offset = (pos & (PAGE_SIZE - 1));
3662 bytes = min_t(unsigned long, PAGE_SIZE - offset,
afddba49
NP
3663 iov_iter_count(i));
3664
3665again:
00a3d660
LT
3666 /*
3667 * Bring in the user page that we will copy from _first_.
3668 * Otherwise there's a nasty deadlock on copying from the
3669 * same page as we're writing to, without it being marked
3670 * up-to-date.
3671 *
3672 * Not only is this an optimisation, but it is also required
3673 * to check that the address is actually valid, when atomic
3674 * usercopies are used, below.
3675 */
3676 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3677 status = -EFAULT;
3678 break;
3679 }
3680
296291cd
JK
3681 if (fatal_signal_pending(current)) {
3682 status = -EINTR;
3683 break;
3684 }
3685
674b892e 3686 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
afddba49 3687 &page, &fsdata);
2457aec6 3688 if (unlikely(status < 0))
afddba49
NP
3689 break;
3690
931e80e4 3691 if (mapping_writably_mapped(mapping))
3692 flush_dcache_page(page);
00a3d660 3693
afddba49 3694 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
afddba49
NP
3695 flush_dcache_page(page);
3696
3697 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3698 page, fsdata);
3699 if (unlikely(status < 0))
3700 break;
3701 copied = status;
3702
3703 cond_resched();
3704
124d3b70 3705 iov_iter_advance(i, copied);
afddba49
NP
3706 if (unlikely(copied == 0)) {
3707 /*
3708 * If we were unable to copy any data at all, we must
3709 * fall back to a single segment length write.
3710 *
3711 * If we didn't fallback here, we could livelock
3712 * because not all segments in the iov can be copied at
3713 * once without a pagefault.
3714 */
09cbfeaf 3715 bytes = min_t(unsigned long, PAGE_SIZE - offset,
afddba49
NP
3716 iov_iter_single_seg_count(i));
3717 goto again;
3718 }
afddba49
NP
3719 pos += copied;
3720 written += copied;
3721
3722 balance_dirty_pages_ratelimited(mapping);
afddba49
NP
3723 } while (iov_iter_count(i));
3724
3725 return written ? written : status;
3726}
3b93f911 3727EXPORT_SYMBOL(generic_perform_write);
1da177e4 3728
e4dd9de3 3729/**
8174202b 3730 * __generic_file_write_iter - write data to a file
e4dd9de3 3731 * @iocb: IO state structure (file, offset, etc.)
8174202b 3732 * @from: iov_iter with data to write
e4dd9de3
JK
3733 *
3734 * This function does all the work needed for actually writing data to a
3735 * file. It does all basic checks, removes SUID from the file, updates
3736 * modification times and calls proper subroutines depending on whether we
3737 * do direct IO or a standard buffered write.
3738 *
3739 * It expects i_mutex to be grabbed unless we work on a block device or similar
3740 * object which does not need locking at all.
3741 *
3742 * This function does *not* take care of syncing data in case of O_SYNC write.
3743 * A caller has to handle it. This is mainly due to the fact that we want to
3744 * avoid syncing under i_mutex.
a862f68a
MR
3745 *
3746 * Return:
3747 * * number of bytes written, even for truncated writes
3748 * * negative error code if no data has been written at all
e4dd9de3 3749 */
8174202b 3750ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1da177e4
LT
3751{
3752 struct file *file = iocb->ki_filp;
fb5527e6 3753 struct address_space * mapping = file->f_mapping;
1da177e4 3754 struct inode *inode = mapping->host;
3b93f911 3755 ssize_t written = 0;
1da177e4 3756 ssize_t err;
3b93f911 3757 ssize_t status;
1da177e4 3758
1da177e4 3759 /* We can write back this queue in page reclaim */
de1414a6 3760 current->backing_dev_info = inode_to_bdi(inode);
5fa8e0a1 3761 err = file_remove_privs(file);
1da177e4
LT
3762 if (err)
3763 goto out;
3764
c3b2da31
JB
3765 err = file_update_time(file);
3766 if (err)
3767 goto out;
1da177e4 3768
2ba48ce5 3769 if (iocb->ki_flags & IOCB_DIRECT) {
0b8def9d 3770 loff_t pos, endbyte;
fb5527e6 3771
1af5bb49 3772 written = generic_file_direct_write(iocb, from);
1da177e4 3773 /*
fbbbad4b
MW
3774 * If the write stopped short of completing, fall back to
3775 * buffered writes. Some filesystems do this for writes to
3776 * holes, for example. For DAX files, a buffered write will
3777 * not succeed (even if it did, DAX does not handle dirty
3778 * page-cache pages correctly).
1da177e4 3779 */
0b8def9d 3780 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
fbbbad4b
MW
3781 goto out;
3782
0b8def9d 3783 status = generic_perform_write(file, from, pos = iocb->ki_pos);
fb5527e6 3784 /*
3b93f911 3785 * If generic_perform_write() returned a synchronous error
fb5527e6
JM
3786 * then we want to return the number of bytes which were
3787 * direct-written, or the error code if that was zero. Note
3788 * that this differs from normal direct-io semantics, which
3789 * will return -EFOO even if some bytes were written.
3790 */
60bb4529 3791 if (unlikely(status < 0)) {
3b93f911 3792 err = status;
fb5527e6
JM
3793 goto out;
3794 }
fb5527e6
JM
3795 /*
3796 * We need to ensure that the page cache pages are written to
3797 * disk and invalidated to preserve the expected O_DIRECT
3798 * semantics.
3799 */
3b93f911 3800 endbyte = pos + status - 1;
0b8def9d 3801 err = filemap_write_and_wait_range(mapping, pos, endbyte);
fb5527e6 3802 if (err == 0) {
0b8def9d 3803 iocb->ki_pos = endbyte + 1;
3b93f911 3804 written += status;
fb5527e6 3805 invalidate_mapping_pages(mapping,
09cbfeaf
KS
3806 pos >> PAGE_SHIFT,
3807 endbyte >> PAGE_SHIFT);
fb5527e6
JM
3808 } else {
3809 /*
3810 * We don't know how much we wrote, so just return
3811 * the number of bytes which were direct-written
3812 */
3813 }
3814 } else {
0b8def9d
AV
3815 written = generic_perform_write(file, from, iocb->ki_pos);
3816 if (likely(written > 0))
3817 iocb->ki_pos += written;
fb5527e6 3818 }
1da177e4
LT
3819out:
3820 current->backing_dev_info = NULL;
3821 return written ? written : err;
3822}
8174202b 3823EXPORT_SYMBOL(__generic_file_write_iter);
e4dd9de3 3824
e4dd9de3 3825/**
8174202b 3826 * generic_file_write_iter - write data to a file
e4dd9de3 3827 * @iocb: IO state structure
8174202b 3828 * @from: iov_iter with data to write
e4dd9de3 3829 *
8174202b 3830 * This is a wrapper around __generic_file_write_iter() to be used by most
e4dd9de3
JK
3831 * filesystems. It takes care of syncing the file in case of O_SYNC file
3832 * and acquires i_mutex as needed.
a862f68a
MR
3833 * Return:
3834 * * negative error code if no data has been written at all of
3835 * vfs_fsync_range() failed for a synchronous write
3836 * * number of bytes written, even for truncated writes
e4dd9de3 3837 */
8174202b 3838ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1da177e4
LT
3839{
3840 struct file *file = iocb->ki_filp;
148f948b 3841 struct inode *inode = file->f_mapping->host;
1da177e4 3842 ssize_t ret;
1da177e4 3843
5955102c 3844 inode_lock(inode);
3309dd04
AV
3845 ret = generic_write_checks(iocb, from);
3846 if (ret > 0)
5f380c7f 3847 ret = __generic_file_write_iter(iocb, from);
5955102c 3848 inode_unlock(inode);
1da177e4 3849
e2592217
CH
3850 if (ret > 0)
3851 ret = generic_write_sync(iocb, ret);
1da177e4
LT
3852 return ret;
3853}
8174202b 3854EXPORT_SYMBOL(generic_file_write_iter);
1da177e4 3855
cf9a2ae8
DH
3856/**
3857 * try_to_release_page() - release old fs-specific metadata on a page
3858 *
3859 * @page: the page which the kernel is trying to free
3860 * @gfp_mask: memory allocation flags (and I/O mode)
3861 *
3862 * The address_space is to try to release any data against the page
a862f68a 3863 * (presumably at page->private).
cf9a2ae8 3864 *
266cf658
DH
3865 * This may also be called if PG_fscache is set on a page, indicating that the
3866 * page is known to the local caching routines.
3867 *
cf9a2ae8 3868 * The @gfp_mask argument specifies whether I/O may be performed to release
71baba4b 3869 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
cf9a2ae8 3870 *
a862f68a 3871 * Return: %1 if the release was successful, otherwise return zero.
cf9a2ae8
DH
3872 */
3873int try_to_release_page(struct page *page, gfp_t gfp_mask)
3874{
3875 struct address_space * const mapping = page->mapping;
3876
3877 BUG_ON(!PageLocked(page));
3878 if (PageWriteback(page))
3879 return 0;
3880
3881 if (mapping && mapping->a_ops->releasepage)
3882 return mapping->a_ops->releasepage(page, gfp_mask);
3883 return try_to_free_buffers(page);
3884}
3885
3886EXPORT_SYMBOL(try_to_release_page);