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