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