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