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