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