1 // SPDX-License-Identifier: GPL-2.0-only 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 */ 13 #include <linux/export.h> 14 #include <linux/compiler.h> 15 #include <linux/dax.h> 16 #include <linux/fs.h> 17 #include <linux/sched/signal.h> 18 #include <linux/uaccess.h> 19 #include <linux/capability.h> 20 #include <linux/kernel_stat.h> 21 #include <linux/gfp.h> 22 #include <linux/mm.h> 23 #include <linux/swap.h> 24 #include <linux/leafops.h> 25 #include <linux/syscalls.h> 26 #include <linux/mman.h> 27 #include <linux/pagemap.h> 28 #include <linux/file.h> 29 #include <linux/uio.h> 30 #include <linux/error-injection.h> 31 #include <linux/hash.h> 32 #include <linux/writeback.h> 33 #include <linux/backing-dev.h> 34 #include <linux/folio_batch.h> 35 #include <linux/security.h> 36 #include <linux/cpuset.h> 37 #include <linux/hugetlb.h> 38 #include <linux/memcontrol.h> 39 #include <linux/shmem_fs.h> 40 #include <linux/rmap.h> 41 #include <linux/delayacct.h> 42 #include <linux/psi.h> 43 #include <linux/ramfs.h> 44 #include <linux/page_idle.h> 45 #include <linux/migrate.h> 46 #include <linux/pipe_fs_i.h> 47 #include <linux/splice.h> 48 #include <linux/rcupdate_wait.h> 49 #include <linux/sched/mm.h> 50 #include <linux/sysctl.h> 51 #include <linux/pgalloc.h> 52 53 #include <asm/tlbflush.h> 54 #include "internal.h" 55 56 #define CREATE_TRACE_POINTS 57 #include <trace/events/filemap.h> 58 59 /* 60 * FIXME: remove all knowledge of the buffer layer from the core VM 61 */ 62 #include <linux/buffer_head.h> /* for try_to_free_buffers */ 63 64 #include <asm/mman.h> 65 66 #include "swap.h" 67 68 /* 69 * Shared mappings implemented 30.11.1994. It's not fully working yet, 70 * though. 71 * 72 * Shared mappings now work. 15.8.1995 Bruno. 73 * 74 * finished 'unifying' the page and buffer cache and SMP-threaded the 75 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com> 76 * 77 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de> 78 */ 79 80 /* 81 * Lock ordering: 82 * 83 * ->i_mmap_rwsem (truncate_pagecache) 84 * ->private_lock (__free_pte->block_dirty_folio) 85 * ->swap_lock (exclusive_swap_page, others) 86 * ->i_pages lock 87 * 88 * ->i_rwsem 89 * ->invalidate_lock (acquired by fs in truncate path) 90 * ->i_mmap_rwsem (truncate->unmap_mapping_range) 91 * 92 * ->mmap_lock 93 * ->i_mmap_rwsem 94 * ->page_table_lock or pte_lock (various, mainly in memory.c) 95 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock) 96 * 97 * ->mmap_lock 98 * ->invalidate_lock (filemap_fault) 99 * ->lock_page (filemap_fault, access_process_vm) 100 * 101 * ->i_rwsem (generic_perform_write) 102 * ->mmap_lock (fault_in_readable->do_page_fault) 103 * 104 * bdi->wb.list_lock 105 * sb_lock (fs/fs-writeback.c) 106 * ->i_pages lock (__sync_single_inode) 107 * 108 * ->i_mmap_rwsem 109 * ->anon_vma.lock (vma_merge) 110 * 111 * ->anon_vma.lock 112 * ->page_table_lock or pte_lock (anon_vma_prepare and various) 113 * 114 * ->page_table_lock or pte_lock 115 * ->swap_lock (try_to_unmap_one) 116 * ->private_lock (try_to_unmap_one) 117 * ->i_pages lock (try_to_unmap_one) 118 * ->lruvec->lru_lock (follow_page_mask->mark_page_accessed) 119 * ->lruvec->lru_lock (check_pte_range->folio_isolate_lru) 120 * ->private_lock (folio_remove_rmap_pte->set_page_dirty) 121 * ->i_pages lock (folio_remove_rmap_pte->set_page_dirty) 122 * bdi.wb->list_lock (folio_remove_rmap_pte->set_page_dirty) 123 * ->inode->i_lock (folio_remove_rmap_pte->set_page_dirty) 124 * bdi.wb->list_lock (zap_pte_range->set_page_dirty) 125 * ->inode->i_lock (zap_pte_range->set_page_dirty) 126 * ->private_lock (zap_pte_range->block_dirty_folio) 127 */ 128 129 static void page_cache_delete(struct address_space *mapping, 130 struct folio *folio, void *shadow) 131 { 132 XA_STATE(xas, &mapping->i_pages, folio->index); 133 long nr = 1; 134 135 mapping_set_update(&xas, mapping); 136 137 xas_set_order(&xas, folio->index, folio_order(folio)); 138 nr = folio_nr_pages(folio); 139 140 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 141 142 xas_store(&xas, shadow); 143 xas_init_marks(&xas); 144 145 folio->mapping = NULL; 146 /* Leave folio->index set: truncation lookup relies upon it */ 147 mapping->nrpages -= nr; 148 } 149 150 static void filemap_unaccount_folio(struct address_space *mapping, 151 struct folio *folio) 152 { 153 long nr; 154 155 VM_BUG_ON_FOLIO(folio_mapped(folio), folio); 156 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) { 157 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n", 158 current->comm, folio_pfn(folio)); 159 dump_page(&folio->page, "still mapped when deleted"); 160 dump_stack(); 161 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE); 162 163 if (mapping_exiting(mapping) && !folio_test_large(folio)) { 164 int mapcount = folio_mapcount(folio); 165 166 if (folio_ref_count(folio) >= mapcount + 2) { 167 /* 168 * All vmas have already been torn down, so it's 169 * a good bet that actually the page is unmapped 170 * and we'd rather not leak it: if we're wrong, 171 * another bad page check should catch it later. 172 */ 173 atomic_set(&folio->_mapcount, -1); 174 folio_ref_sub(folio, mapcount); 175 } 176 } 177 } 178 179 /* hugetlb folios do not participate in page cache accounting. */ 180 if (folio_test_hugetlb(folio)) 181 return; 182 183 nr = folio_nr_pages(folio); 184 185 lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr); 186 if (folio_test_swapbacked(folio)) { 187 lruvec_stat_mod_folio(folio, NR_SHMEM, -nr); 188 if (folio_test_pmd_mappable(folio)) 189 lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -nr); 190 } else if (folio_test_pmd_mappable(folio)) { 191 lruvec_stat_mod_folio(folio, NR_FILE_THPS, -nr); 192 filemap_nr_thps_dec(mapping); 193 } 194 if (test_bit(AS_KERNEL_FILE, &folio->mapping->flags)) 195 mod_node_page_state(folio_pgdat(folio), 196 NR_KERNEL_FILE_PAGES, -nr); 197 198 /* 199 * At this point folio must be either written or cleaned by 200 * truncate. Dirty folio here signals a bug and loss of 201 * unwritten data - on ordinary filesystems. 202 * 203 * But it's harmless on in-memory filesystems like tmpfs; and can 204 * occur when a driver which did get_user_pages() sets page dirty 205 * before putting it, while the inode is being finally evicted. 206 * 207 * Below fixes dirty accounting after removing the folio entirely 208 * but leaves the dirty flag set: it has no effect for truncated 209 * folio and anyway will be cleared before returning folio to 210 * buddy allocator. 211 */ 212 if (WARN_ON_ONCE(folio_test_dirty(folio) && 213 mapping_can_writeback(mapping))) 214 folio_account_cleaned(folio, inode_to_wb(mapping->host)); 215 } 216 217 /* 218 * Delete a page from the page cache and free it. Caller has to make 219 * sure the page is locked and that nobody else uses it - or that usage 220 * is safe. The caller must hold the i_pages lock. 221 */ 222 void __filemap_remove_folio(struct folio *folio, void *shadow) 223 { 224 struct address_space *mapping = folio->mapping; 225 226 trace_mm_filemap_delete_from_page_cache(folio); 227 filemap_unaccount_folio(mapping, folio); 228 page_cache_delete(mapping, folio, shadow); 229 } 230 231 static void filemap_free_folio(const struct address_space *mapping, 232 struct folio *folio) 233 { 234 void (*free_folio)(struct folio *); 235 236 free_folio = mapping->a_ops->free_folio; 237 if (free_folio) 238 free_folio(folio); 239 240 folio_put_refs(folio, folio_nr_pages(folio)); 241 } 242 243 /** 244 * filemap_remove_folio - Remove folio from page cache. 245 * @folio: The folio. 246 * 247 * This must be called only on folios that are locked and have been 248 * verified to be in the page cache. It will never put the folio into 249 * the free list because the caller has a reference on the page. 250 */ 251 void filemap_remove_folio(struct folio *folio) 252 { 253 struct address_space *mapping = folio->mapping; 254 255 BUG_ON(!folio_test_locked(folio)); 256 spin_lock(&mapping->host->i_lock); 257 xa_lock_irq(&mapping->i_pages); 258 __filemap_remove_folio(folio, NULL); 259 xa_unlock_irq(&mapping->i_pages); 260 if (mapping_shrinkable(mapping)) 261 inode_lru_list_add(mapping->host); 262 spin_unlock(&mapping->host->i_lock); 263 264 filemap_free_folio(mapping, folio); 265 } 266 267 /* 268 * page_cache_delete_batch - delete several folios from page cache 269 * @mapping: the mapping to which folios belong 270 * @fbatch: batch of folios to delete 271 * 272 * The function walks over mapping->i_pages and removes folios passed in 273 * @fbatch from the mapping. The function expects @fbatch to be sorted 274 * by page index and is optimised for it to be dense. 275 * It tolerates holes in @fbatch (mapping entries at those indices are not 276 * modified). 277 * 278 * The function expects the i_pages lock to be held. 279 */ 280 static void page_cache_delete_batch(struct address_space *mapping, 281 struct folio_batch *fbatch) 282 { 283 XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index); 284 long total_pages = 0; 285 int i = 0; 286 struct folio *folio; 287 288 mapping_set_update(&xas, mapping); 289 xas_for_each(&xas, folio, ULONG_MAX) { 290 if (i >= folio_batch_count(fbatch)) 291 break; 292 293 /* A swap/dax/shadow entry got inserted? Skip it. */ 294 if (xa_is_value(folio)) 295 continue; 296 /* 297 * A page got inserted in our range? Skip it. We have our 298 * pages locked so they are protected from being removed. 299 * If we see a page whose index is higher than ours, it 300 * means our page has been removed, which shouldn't be 301 * possible because we're holding the PageLock. 302 */ 303 if (folio != fbatch->folios[i]) { 304 VM_BUG_ON_FOLIO(folio->index > 305 fbatch->folios[i]->index, folio); 306 continue; 307 } 308 309 WARN_ON_ONCE(!folio_test_locked(folio)); 310 311 folio->mapping = NULL; 312 /* Leave folio->index set: truncation lookup relies on it */ 313 314 i++; 315 xas_store(&xas, NULL); 316 total_pages += folio_nr_pages(folio); 317 } 318 mapping->nrpages -= total_pages; 319 } 320 321 void delete_from_page_cache_batch(struct address_space *mapping, 322 struct folio_batch *fbatch) 323 { 324 int i; 325 326 if (!folio_batch_count(fbatch)) 327 return; 328 329 spin_lock(&mapping->host->i_lock); 330 xa_lock_irq(&mapping->i_pages); 331 for (i = 0; i < folio_batch_count(fbatch); i++) { 332 struct folio *folio = fbatch->folios[i]; 333 334 trace_mm_filemap_delete_from_page_cache(folio); 335 filemap_unaccount_folio(mapping, folio); 336 } 337 page_cache_delete_batch(mapping, fbatch); 338 xa_unlock_irq(&mapping->i_pages); 339 if (mapping_shrinkable(mapping)) 340 inode_lru_list_add(mapping->host); 341 spin_unlock(&mapping->host->i_lock); 342 343 for (i = 0; i < folio_batch_count(fbatch); i++) 344 filemap_free_folio(mapping, fbatch->folios[i]); 345 } 346 347 int filemap_check_errors(struct address_space *mapping) 348 { 349 int ret = 0; 350 /* Check for outstanding write errors */ 351 if (test_bit(AS_ENOSPC, &mapping->flags) && 352 test_and_clear_bit(AS_ENOSPC, &mapping->flags)) 353 ret = -ENOSPC; 354 if (test_bit(AS_EIO, &mapping->flags) && 355 test_and_clear_bit(AS_EIO, &mapping->flags)) 356 ret = -EIO; 357 return ret; 358 } 359 EXPORT_SYMBOL(filemap_check_errors); 360 361 static int filemap_check_and_keep_errors(struct address_space *mapping) 362 { 363 /* Check for outstanding write errors */ 364 if (test_bit(AS_EIO, &mapping->flags)) 365 return -EIO; 366 if (test_bit(AS_ENOSPC, &mapping->flags)) 367 return -ENOSPC; 368 return 0; 369 } 370 371 static int filemap_writeback(struct address_space *mapping, loff_t start, 372 loff_t end, enum writeback_sync_modes sync_mode, 373 long *nr_to_write) 374 { 375 struct writeback_control wbc = { 376 .sync_mode = sync_mode, 377 .nr_to_write = nr_to_write ? *nr_to_write : LONG_MAX, 378 .range_start = start, 379 .range_end = end, 380 }; 381 int ret; 382 383 if (!mapping_can_writeback(mapping) || 384 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) 385 return 0; 386 387 wbc_attach_fdatawrite_inode(&wbc, mapping->host); 388 ret = do_writepages(mapping, &wbc); 389 wbc_detach_inode(&wbc); 390 391 if (!ret && nr_to_write) 392 *nr_to_write = wbc.nr_to_write; 393 return ret; 394 } 395 396 /** 397 * filemap_fdatawrite_range - start writeback on mapping dirty pages in range 398 * @mapping: address space structure to write 399 * @start: offset in bytes where the range starts 400 * @end: offset in bytes where the range ends (inclusive) 401 * 402 * Start writeback against all of a mapping's dirty pages that lie 403 * within the byte offsets <start, end> inclusive. 404 * 405 * This is a data integrity operation that waits upon dirty or in writeback 406 * pages. 407 * 408 * Return: %0 on success, negative error code otherwise. 409 */ 410 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start, 411 loff_t end) 412 { 413 return filemap_writeback(mapping, start, end, WB_SYNC_ALL, NULL); 414 } 415 EXPORT_SYMBOL(filemap_fdatawrite_range); 416 417 int filemap_fdatawrite(struct address_space *mapping) 418 { 419 return filemap_fdatawrite_range(mapping, 0, LLONG_MAX); 420 } 421 EXPORT_SYMBOL(filemap_fdatawrite); 422 423 /** 424 * filemap_flush_range - start writeback on a range 425 * @mapping: target address_space 426 * @start: index to start writeback on 427 * @end: last (inclusive) index for writeback 428 * 429 * This is a non-integrity writeback helper, to start writing back folios 430 * for the indicated range. 431 * 432 * Return: %0 on success, negative error code otherwise. 433 */ 434 int filemap_flush_range(struct address_space *mapping, loff_t start, 435 loff_t end) 436 { 437 return filemap_writeback(mapping, start, end, WB_SYNC_NONE, NULL); 438 } 439 EXPORT_SYMBOL_GPL(filemap_flush_range); 440 441 /** 442 * filemap_flush - mostly a non-blocking flush 443 * @mapping: target address_space 444 * 445 * This is a mostly non-blocking flush. Not suitable for data-integrity 446 * purposes - I/O may not be started against all dirty pages. 447 * 448 * Return: %0 on success, negative error code otherwise. 449 */ 450 int filemap_flush(struct address_space *mapping) 451 { 452 return filemap_flush_range(mapping, 0, LLONG_MAX); 453 } 454 EXPORT_SYMBOL(filemap_flush); 455 456 /* 457 * Start writeback on @nr_to_write pages from @mapping. No one but the existing 458 * btrfs caller should be using this. Talk to linux-mm if you think adding a 459 * new caller is a good idea. 460 */ 461 int filemap_flush_nr(struct address_space *mapping, long *nr_to_write) 462 { 463 return filemap_writeback(mapping, 0, LLONG_MAX, WB_SYNC_NONE, 464 nr_to_write); 465 } 466 EXPORT_SYMBOL_FOR_MODULES(filemap_flush_nr, "btrfs"); 467 468 /** 469 * filemap_range_has_page - check if a page exists in range. 470 * @mapping: address space within which to check 471 * @start_byte: offset in bytes where the range starts 472 * @end_byte: offset in bytes where the range ends (inclusive) 473 * 474 * Find at least one page in the range supplied, usually used to check if 475 * direct writing in this range will trigger a writeback. 476 * 477 * Return: %true if at least one page exists in the specified range, 478 * %false otherwise. 479 */ 480 bool filemap_range_has_page(struct address_space *mapping, 481 loff_t start_byte, loff_t end_byte) 482 { 483 struct folio *folio; 484 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT); 485 pgoff_t max = end_byte >> PAGE_SHIFT; 486 487 if (end_byte < start_byte) 488 return false; 489 490 rcu_read_lock(); 491 for (;;) { 492 folio = xas_find(&xas, max); 493 if (xas_retry(&xas, folio)) 494 continue; 495 /* Shadow entries don't count */ 496 if (xa_is_value(folio)) 497 continue; 498 /* 499 * We don't need to try to pin this page; we're about to 500 * release the RCU lock anyway. It is enough to know that 501 * there was a page here recently. 502 */ 503 break; 504 } 505 rcu_read_unlock(); 506 507 return folio != NULL; 508 } 509 EXPORT_SYMBOL(filemap_range_has_page); 510 511 static void __filemap_fdatawait_range(struct address_space *mapping, 512 loff_t start_byte, loff_t end_byte) 513 { 514 pgoff_t index = start_byte >> PAGE_SHIFT; 515 pgoff_t end = end_byte >> PAGE_SHIFT; 516 struct folio_batch fbatch; 517 unsigned nr_folios; 518 519 folio_batch_init(&fbatch); 520 521 while (index <= end) { 522 unsigned i; 523 524 nr_folios = filemap_get_folios_tag(mapping, &index, end, 525 PAGECACHE_TAG_WRITEBACK, &fbatch); 526 527 if (!nr_folios) 528 break; 529 530 for (i = 0; i < nr_folios; i++) { 531 struct folio *folio = fbatch.folios[i]; 532 533 folio_wait_writeback(folio); 534 } 535 folio_batch_release(&fbatch); 536 cond_resched(); 537 } 538 } 539 540 /** 541 * filemap_fdatawait_range - wait for writeback to complete 542 * @mapping: address space structure to wait for 543 * @start_byte: offset in bytes where the range starts 544 * @end_byte: offset in bytes where the range ends (inclusive) 545 * 546 * Walk the list of under-writeback pages of the given address space 547 * in the given range and wait for all of them. Check error status of 548 * the address space and return it. 549 * 550 * Since the error status of the address space is cleared by this function, 551 * callers are responsible for checking the return value and handling and/or 552 * reporting the error. 553 * 554 * Return: error status of the address space. 555 */ 556 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte, 557 loff_t end_byte) 558 { 559 __filemap_fdatawait_range(mapping, start_byte, end_byte); 560 return filemap_check_errors(mapping); 561 } 562 EXPORT_SYMBOL(filemap_fdatawait_range); 563 564 /** 565 * filemap_fdatawait_range_keep_errors - wait for writeback to complete 566 * @mapping: address space structure to wait for 567 * @start_byte: offset in bytes where the range starts 568 * @end_byte: offset in bytes where the range ends (inclusive) 569 * 570 * Walk the list of under-writeback pages of the given address space in the 571 * given range and wait for all of them. Unlike filemap_fdatawait_range(), 572 * this function does not clear error status of the address space. 573 * 574 * Use this function if callers don't handle errors themselves. Expected 575 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2), 576 * fsfreeze(8) 577 */ 578 int filemap_fdatawait_range_keep_errors(struct address_space *mapping, 579 loff_t start_byte, loff_t end_byte) 580 { 581 __filemap_fdatawait_range(mapping, start_byte, end_byte); 582 return filemap_check_and_keep_errors(mapping); 583 } 584 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors); 585 586 /** 587 * file_fdatawait_range - wait for writeback to complete 588 * @file: file pointing to address space structure to wait for 589 * @start_byte: offset in bytes where the range starts 590 * @end_byte: offset in bytes where the range ends (inclusive) 591 * 592 * Walk the list of under-writeback pages of the address space that file 593 * refers to, in the given range and wait for all of them. Check error 594 * status of the address space vs. the file->f_wb_err cursor and return it. 595 * 596 * Since the error status of the file is advanced by this function, 597 * callers are responsible for checking the return value and handling and/or 598 * reporting the error. 599 * 600 * Return: error status of the address space vs. the file->f_wb_err cursor. 601 */ 602 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte) 603 { 604 struct address_space *mapping = file->f_mapping; 605 606 __filemap_fdatawait_range(mapping, start_byte, end_byte); 607 return file_check_and_advance_wb_err(file); 608 } 609 EXPORT_SYMBOL(file_fdatawait_range); 610 611 /** 612 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors 613 * @mapping: address space structure to wait for 614 * 615 * Walk the list of under-writeback pages of the given address space 616 * and wait for all of them. Unlike filemap_fdatawait(), this function 617 * does not clear error status of the address space. 618 * 619 * Use this function if callers don't handle errors themselves. Expected 620 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2), 621 * fsfreeze(8) 622 * 623 * Return: error status of the address space. 624 */ 625 int filemap_fdatawait_keep_errors(struct address_space *mapping) 626 { 627 __filemap_fdatawait_range(mapping, 0, LLONG_MAX); 628 return filemap_check_and_keep_errors(mapping); 629 } 630 EXPORT_SYMBOL(filemap_fdatawait_keep_errors); 631 632 /* Returns true if writeback might be needed or already in progress. */ 633 static bool mapping_needs_writeback(struct address_space *mapping) 634 { 635 return mapping->nrpages; 636 } 637 638 bool filemap_range_has_writeback(struct address_space *mapping, 639 loff_t start_byte, loff_t end_byte) 640 { 641 XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT); 642 pgoff_t max = end_byte >> PAGE_SHIFT; 643 struct folio *folio; 644 645 if (end_byte < start_byte) 646 return false; 647 648 rcu_read_lock(); 649 xas_for_each(&xas, folio, max) { 650 if (xas_retry(&xas, folio)) 651 continue; 652 if (xa_is_value(folio)) 653 continue; 654 if (folio_test_dirty(folio) || folio_test_locked(folio) || 655 folio_test_writeback(folio)) 656 break; 657 } 658 rcu_read_unlock(); 659 return folio != NULL; 660 } 661 EXPORT_SYMBOL_GPL(filemap_range_has_writeback); 662 663 /** 664 * filemap_write_and_wait_range - write out & wait on a file range 665 * @mapping: the address_space for the pages 666 * @lstart: offset in bytes where the range starts 667 * @lend: offset in bytes where the range ends (inclusive) 668 * 669 * Write out and wait upon file offsets lstart->lend, inclusive. 670 * 671 * Note that @lend is inclusive (describes the last byte to be written) so 672 * that this function can be used to write to the very end-of-file (end = -1). 673 * 674 * Return: error status of the address space. 675 */ 676 int filemap_write_and_wait_range(struct address_space *mapping, 677 loff_t lstart, loff_t lend) 678 { 679 int err = 0, err2; 680 681 if (lend < lstart) 682 return 0; 683 684 if (mapping_needs_writeback(mapping)) { 685 err = filemap_fdatawrite_range(mapping, lstart, lend); 686 /* 687 * Even if the above returned error, the pages may be 688 * written partially (e.g. -ENOSPC), so we wait for it. 689 * But the -EIO is special case, it may indicate the worst 690 * thing (e.g. bug) happened, so we avoid waiting for it. 691 */ 692 if (err != -EIO) 693 __filemap_fdatawait_range(mapping, lstart, lend); 694 } 695 err2 = filemap_check_errors(mapping); 696 if (!err) 697 err = err2; 698 return err; 699 } 700 EXPORT_SYMBOL(filemap_write_and_wait_range); 701 702 void __filemap_set_wb_err(struct address_space *mapping, int err) 703 { 704 errseq_t eseq = errseq_set(&mapping->wb_err, err); 705 706 trace_filemap_set_wb_err(mapping, eseq); 707 } 708 EXPORT_SYMBOL(__filemap_set_wb_err); 709 710 /** 711 * file_check_and_advance_wb_err - report wb error (if any) that was previously 712 * and advance wb_err to current one 713 * @file: struct file on which the error is being reported 714 * 715 * When userland calls fsync (or something like nfsd does the equivalent), we 716 * want to report any writeback errors that occurred since the last fsync (or 717 * since the file was opened if there haven't been any). 718 * 719 * Grab the wb_err from the mapping. If it matches what we have in the file, 720 * then just quickly return 0. The file is all caught up. 721 * 722 * If it doesn't match, then take the mapping value, set the "seen" flag in 723 * it and try to swap it into place. If it works, or another task beat us 724 * to it with the new value, then update the f_wb_err and return the error 725 * portion. The error at this point must be reported via proper channels 726 * (a'la fsync, or NFS COMMIT operation, etc.). 727 * 728 * While we handle mapping->wb_err with atomic operations, the f_wb_err 729 * value is protected by the f_lock since we must ensure that it reflects 730 * the latest value swapped in for this file descriptor. 731 * 732 * Return: %0 on success, negative error code otherwise. 733 */ 734 int file_check_and_advance_wb_err(struct file *file) 735 { 736 int err = 0; 737 errseq_t old = READ_ONCE(file->f_wb_err); 738 struct address_space *mapping = file->f_mapping; 739 740 /* Locklessly handle the common case where nothing has changed */ 741 if (errseq_check(&mapping->wb_err, old)) { 742 /* Something changed, must use slow path */ 743 spin_lock(&file->f_lock); 744 old = file->f_wb_err; 745 err = errseq_check_and_advance(&mapping->wb_err, 746 &file->f_wb_err); 747 trace_file_check_and_advance_wb_err(file, old); 748 spin_unlock(&file->f_lock); 749 } 750 751 /* 752 * We're mostly using this function as a drop in replacement for 753 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect 754 * that the legacy code would have had on these flags. 755 */ 756 clear_bit(AS_EIO, &mapping->flags); 757 clear_bit(AS_ENOSPC, &mapping->flags); 758 return err; 759 } 760 EXPORT_SYMBOL(file_check_and_advance_wb_err); 761 762 /** 763 * file_write_and_wait_range - write out & wait on a file range 764 * @file: file pointing to address_space with pages 765 * @lstart: offset in bytes where the range starts 766 * @lend: offset in bytes where the range ends (inclusive) 767 * 768 * Write out and wait upon file offsets lstart->lend, inclusive. 769 * 770 * Note that @lend is inclusive (describes the last byte to be written) so 771 * that this function can be used to write to the very end-of-file (end = -1). 772 * 773 * After writing out and waiting on the data, we check and advance the 774 * f_wb_err cursor to the latest value, and return any errors detected there. 775 * 776 * Return: %0 on success, negative error code otherwise. 777 */ 778 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend) 779 { 780 int err = 0, err2; 781 struct address_space *mapping = file->f_mapping; 782 783 if (lend < lstart) 784 return 0; 785 786 if (mapping_needs_writeback(mapping)) { 787 err = filemap_fdatawrite_range(mapping, lstart, lend); 788 /* See comment of filemap_write_and_wait() */ 789 if (err != -EIO) 790 __filemap_fdatawait_range(mapping, lstart, lend); 791 } 792 err2 = file_check_and_advance_wb_err(file); 793 if (!err) 794 err = err2; 795 return err; 796 } 797 EXPORT_SYMBOL(file_write_and_wait_range); 798 799 /** 800 * replace_page_cache_folio - replace a pagecache folio with a new one 801 * @old: folio to be replaced 802 * @new: folio to replace with 803 * 804 * This function replaces a folio in the pagecache with a new one. On 805 * success it acquires the pagecache reference for the new folio and 806 * drops it for the old folio. Both the old and new folios must be 807 * locked. This function does not add the new folio to the LRU, the 808 * caller must do that. 809 * 810 * The remove + add is atomic. This function cannot fail. 811 */ 812 void replace_page_cache_folio(struct folio *old, struct folio *new) 813 { 814 struct address_space *mapping = old->mapping; 815 void (*free_folio)(struct folio *) = mapping->a_ops->free_folio; 816 pgoff_t offset = old->index; 817 XA_STATE(xas, &mapping->i_pages, offset); 818 819 VM_BUG_ON_FOLIO(!folio_test_locked(old), old); 820 VM_BUG_ON_FOLIO(!folio_test_locked(new), new); 821 VM_BUG_ON_FOLIO(new->mapping, new); 822 823 folio_get(new); 824 new->mapping = mapping; 825 new->index = offset; 826 827 mem_cgroup_replace_folio(old, new); 828 829 xas_lock_irq(&xas); 830 xas_store(&xas, new); 831 832 old->mapping = NULL; 833 /* hugetlb pages do not participate in page cache accounting. */ 834 if (!folio_test_hugetlb(old)) 835 lruvec_stat_sub_folio(old, NR_FILE_PAGES); 836 if (!folio_test_hugetlb(new)) 837 lruvec_stat_add_folio(new, NR_FILE_PAGES); 838 if (folio_test_swapbacked(old)) 839 lruvec_stat_sub_folio(old, NR_SHMEM); 840 if (folio_test_swapbacked(new)) 841 lruvec_stat_add_folio(new, NR_SHMEM); 842 xas_unlock_irq(&xas); 843 if (free_folio) 844 free_folio(old); 845 folio_put(old); 846 } 847 EXPORT_SYMBOL_GPL(replace_page_cache_folio); 848 849 noinline int __filemap_add_folio(struct address_space *mapping, 850 struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp) 851 { 852 XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio)); 853 bool huge; 854 long nr; 855 unsigned int forder = folio_order(folio); 856 857 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 858 VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio); 859 VM_BUG_ON_FOLIO(folio_order(folio) < mapping_min_folio_order(mapping), 860 folio); 861 mapping_set_update(&xas, mapping); 862 863 VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio); 864 huge = folio_test_hugetlb(folio); 865 nr = folio_nr_pages(folio); 866 867 gfp &= GFP_RECLAIM_MASK; 868 folio_ref_add(folio, nr); 869 folio->mapping = mapping; 870 folio->index = xas.xa_index; 871 872 for (;;) { 873 int order = -1; 874 void *entry, *old = NULL; 875 876 xas_lock_irq(&xas); 877 xas_for_each_conflict(&xas, entry) { 878 old = entry; 879 if (!xa_is_value(entry)) { 880 xas_set_err(&xas, -EEXIST); 881 goto unlock; 882 } 883 /* 884 * If a larger entry exists, 885 * it will be the first and only entry iterated. 886 */ 887 if (order == -1) 888 order = xas_get_order(&xas); 889 } 890 891 if (old) { 892 if (order > 0 && order > forder) { 893 unsigned int split_order = max(forder, 894 xas_try_split_min_order(order)); 895 896 /* How to handle large swap entries? */ 897 BUG_ON(shmem_mapping(mapping)); 898 899 while (order > forder) { 900 xas_set_order(&xas, index, split_order); 901 xas_try_split(&xas, old, order); 902 if (xas_error(&xas)) 903 goto unlock; 904 order = split_order; 905 split_order = 906 max(xas_try_split_min_order( 907 split_order), 908 forder); 909 } 910 xas_reset(&xas); 911 } 912 if (shadowp) 913 *shadowp = old; 914 } 915 916 xas_store(&xas, folio); 917 if (xas_error(&xas)) 918 goto unlock; 919 920 mapping->nrpages += nr; 921 922 /* hugetlb pages do not participate in page cache accounting */ 923 if (!huge) { 924 lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr); 925 if (folio_test_pmd_mappable(folio)) 926 lruvec_stat_mod_folio(folio, 927 NR_FILE_THPS, nr); 928 } 929 930 unlock: 931 xas_unlock_irq(&xas); 932 933 if (!xas_nomem(&xas, gfp)) 934 break; 935 } 936 937 if (xas_error(&xas)) 938 goto error; 939 940 trace_mm_filemap_add_to_page_cache(folio); 941 return 0; 942 error: 943 folio->mapping = NULL; 944 /* Leave folio->index set: truncation relies upon it */ 945 folio_put_refs(folio, nr); 946 return xas_error(&xas); 947 } 948 ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO); 949 950 int filemap_add_folio(struct address_space *mapping, struct folio *folio, 951 pgoff_t index, gfp_t gfp) 952 { 953 void *shadow = NULL; 954 int ret; 955 struct mem_cgroup *tmp; 956 bool kernel_file = test_bit(AS_KERNEL_FILE, &mapping->flags); 957 958 if (kernel_file) 959 tmp = set_active_memcg(root_mem_cgroup); 960 ret = mem_cgroup_charge(folio, NULL, gfp); 961 if (kernel_file) 962 set_active_memcg(tmp); 963 if (ret) 964 return ret; 965 966 __folio_set_locked(folio); 967 ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow); 968 if (unlikely(ret)) { 969 mem_cgroup_uncharge(folio); 970 __folio_clear_locked(folio); 971 } else { 972 /* 973 * The folio might have been evicted from cache only 974 * recently, in which case it should be activated like 975 * any other repeatedly accessed folio. 976 * The exception is folios getting rewritten; evicting other 977 * data from the working set, only to cache data that will 978 * get overwritten with something else, is a waste of memory. 979 */ 980 WARN_ON_ONCE(folio_test_active(folio)); 981 if (!(gfp & __GFP_WRITE) && shadow) 982 workingset_refault(folio, shadow); 983 folio_add_lru(folio); 984 if (kernel_file) 985 mod_node_page_state(folio_pgdat(folio), 986 NR_KERNEL_FILE_PAGES, 987 folio_nr_pages(folio)); 988 } 989 return ret; 990 } 991 EXPORT_SYMBOL_GPL(filemap_add_folio); 992 993 #ifdef CONFIG_NUMA 994 struct folio *filemap_alloc_folio_noprof(gfp_t gfp, unsigned int order, 995 struct mempolicy *policy) 996 { 997 int n; 998 struct folio *folio; 999 1000 if (policy) 1001 return folio_alloc_mpol_noprof(gfp, order, policy, 1002 NO_INTERLEAVE_INDEX, numa_node_id()); 1003 1004 if (cpuset_do_page_mem_spread()) { 1005 unsigned int cpuset_mems_cookie; 1006 do { 1007 cpuset_mems_cookie = read_mems_allowed_begin(); 1008 n = cpuset_mem_spread_node(); 1009 folio = __folio_alloc_node_noprof(gfp, order, n); 1010 } while (!folio && read_mems_allowed_retry(cpuset_mems_cookie)); 1011 1012 return folio; 1013 } 1014 return folio_alloc_noprof(gfp, order); 1015 } 1016 EXPORT_SYMBOL(filemap_alloc_folio_noprof); 1017 #endif 1018 1019 /* 1020 * filemap_invalidate_lock_two - lock invalidate_lock for two mappings 1021 * 1022 * Lock exclusively invalidate_lock of any passed mapping that is not NULL. 1023 * 1024 * @mapping1: the first mapping to lock 1025 * @mapping2: the second mapping to lock 1026 */ 1027 void filemap_invalidate_lock_two(struct address_space *mapping1, 1028 struct address_space *mapping2) 1029 { 1030 if (mapping1 > mapping2) 1031 swap(mapping1, mapping2); 1032 if (mapping1) 1033 down_write(&mapping1->invalidate_lock); 1034 if (mapping2 && mapping1 != mapping2) 1035 down_write_nested(&mapping2->invalidate_lock, 1); 1036 } 1037 EXPORT_SYMBOL(filemap_invalidate_lock_two); 1038 1039 /* 1040 * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings 1041 * 1042 * Unlock exclusive invalidate_lock of any passed mapping that is not NULL. 1043 * 1044 * @mapping1: the first mapping to unlock 1045 * @mapping2: the second mapping to unlock 1046 */ 1047 void filemap_invalidate_unlock_two(struct address_space *mapping1, 1048 struct address_space *mapping2) 1049 { 1050 if (mapping1) 1051 up_write(&mapping1->invalidate_lock); 1052 if (mapping2 && mapping1 != mapping2) 1053 up_write(&mapping2->invalidate_lock); 1054 } 1055 EXPORT_SYMBOL(filemap_invalidate_unlock_two); 1056 1057 /* 1058 * In order to wait for pages to become available there must be 1059 * waitqueues associated with pages. By using a hash table of 1060 * waitqueues where the bucket discipline is to maintain all 1061 * waiters on the same queue and wake all when any of the pages 1062 * become available, and for the woken contexts to check to be 1063 * sure the appropriate page became available, this saves space 1064 * at a cost of "thundering herd" phenomena during rare hash 1065 * collisions. 1066 */ 1067 #define PAGE_WAIT_TABLE_BITS 8 1068 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS) 1069 static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned; 1070 1071 static wait_queue_head_t *folio_waitqueue(struct folio *folio) 1072 { 1073 return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)]; 1074 } 1075 1076 /* How many times do we accept lock stealing from under a waiter? */ 1077 static int sysctl_page_lock_unfairness = 5; 1078 static const struct ctl_table filemap_sysctl_table[] = { 1079 { 1080 .procname = "page_lock_unfairness", 1081 .data = &sysctl_page_lock_unfairness, 1082 .maxlen = sizeof(sysctl_page_lock_unfairness), 1083 .mode = 0644, 1084 .proc_handler = proc_dointvec_minmax, 1085 .extra1 = SYSCTL_ZERO, 1086 } 1087 }; 1088 1089 void __init pagecache_init(void) 1090 { 1091 int i; 1092 1093 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++) 1094 init_waitqueue_head(&folio_wait_table[i]); 1095 1096 page_writeback_init(); 1097 register_sysctl_init("vm", filemap_sysctl_table); 1098 } 1099 1100 /* 1101 * The page wait code treats the "wait->flags" somewhat unusually, because 1102 * we have multiple different kinds of waits, not just the usual "exclusive" 1103 * one. 1104 * 1105 * We have: 1106 * 1107 * (a) no special bits set: 1108 * 1109 * We're just waiting for the bit to be released, and when a waker 1110 * calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up, 1111 * and remove it from the wait queue. 1112 * 1113 * Simple and straightforward. 1114 * 1115 * (b) WQ_FLAG_EXCLUSIVE: 1116 * 1117 * The waiter is waiting to get the lock, and only one waiter should 1118 * be woken up to avoid any thundering herd behavior. We'll set the 1119 * WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue. 1120 * 1121 * This is the traditional exclusive wait. 1122 * 1123 * (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM: 1124 * 1125 * The waiter is waiting to get the bit, and additionally wants the 1126 * lock to be transferred to it for fair lock behavior. If the lock 1127 * cannot be taken, we stop walking the wait queue without waking 1128 * the waiter. 1129 * 1130 * This is the "fair lock handoff" case, and in addition to setting 1131 * WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see 1132 * that it now has the lock. 1133 */ 1134 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg) 1135 { 1136 unsigned int flags; 1137 struct wait_page_key *key = arg; 1138 struct wait_page_queue *wait_page 1139 = container_of(wait, struct wait_page_queue, wait); 1140 1141 if (!wake_page_match(wait_page, key)) 1142 return 0; 1143 1144 /* 1145 * If it's a lock handoff wait, we get the bit for it, and 1146 * stop walking (and do not wake it up) if we can't. 1147 */ 1148 flags = wait->flags; 1149 if (flags & WQ_FLAG_EXCLUSIVE) { 1150 if (test_bit(key->bit_nr, &key->folio->flags.f)) 1151 return -1; 1152 if (flags & WQ_FLAG_CUSTOM) { 1153 if (test_and_set_bit(key->bit_nr, &key->folio->flags.f)) 1154 return -1; 1155 flags |= WQ_FLAG_DONE; 1156 } 1157 } 1158 1159 /* 1160 * We are holding the wait-queue lock, but the waiter that 1161 * is waiting for this will be checking the flags without 1162 * any locking. 1163 * 1164 * So update the flags atomically, and wake up the waiter 1165 * afterwards to avoid any races. This store-release pairs 1166 * with the load-acquire in folio_wait_bit_common(). 1167 */ 1168 smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN); 1169 wake_up_state(wait->private, mode); 1170 1171 /* 1172 * Ok, we have successfully done what we're waiting for, 1173 * and we can unconditionally remove the wait entry. 1174 * 1175 * Note that this pairs with the "finish_wait()" in the 1176 * waiter, and has to be the absolute last thing we do. 1177 * After this list_del_init(&wait->entry) the wait entry 1178 * might be de-allocated and the process might even have 1179 * exited. 1180 */ 1181 list_del_init_careful(&wait->entry); 1182 return (flags & WQ_FLAG_EXCLUSIVE) != 0; 1183 } 1184 1185 static void folio_wake_bit(struct folio *folio, int bit_nr) 1186 { 1187 wait_queue_head_t *q = folio_waitqueue(folio); 1188 struct wait_page_key key; 1189 unsigned long flags; 1190 1191 key.folio = folio; 1192 key.bit_nr = bit_nr; 1193 key.page_match = 0; 1194 1195 spin_lock_irqsave(&q->lock, flags); 1196 __wake_up_locked_key(q, TASK_NORMAL, &key); 1197 1198 /* 1199 * It's possible to miss clearing waiters here, when we woke our page 1200 * waiters, but the hashed waitqueue has waiters for other pages on it. 1201 * That's okay, it's a rare case. The next waker will clear it. 1202 * 1203 * Note that, depending on the page pool (buddy, hugetlb, ZONE_DEVICE, 1204 * other), the flag may be cleared in the course of freeing the page; 1205 * but that is not required for correctness. 1206 */ 1207 if (!waitqueue_active(q) || !key.page_match) 1208 folio_clear_waiters(folio); 1209 1210 spin_unlock_irqrestore(&q->lock, flags); 1211 } 1212 1213 /* 1214 * A choice of three behaviors for folio_wait_bit_common(): 1215 */ 1216 enum behavior { 1217 EXCLUSIVE, /* Hold ref to page and take the bit when woken, like 1218 * __folio_lock() waiting on then setting PG_locked. 1219 */ 1220 SHARED, /* Hold ref to page and check the bit when woken, like 1221 * folio_wait_writeback() waiting on PG_writeback. 1222 */ 1223 DROP, /* Drop ref to page before wait, no check when woken, 1224 * like folio_put_wait_locked() on PG_locked. 1225 */ 1226 }; 1227 1228 /* 1229 * Attempt to check (or get) the folio flag, and mark us done 1230 * if successful. 1231 */ 1232 static inline bool folio_trylock_flag(struct folio *folio, int bit_nr, 1233 struct wait_queue_entry *wait) 1234 { 1235 if (wait->flags & WQ_FLAG_EXCLUSIVE) { 1236 if (test_and_set_bit(bit_nr, &folio->flags.f)) 1237 return false; 1238 } else if (test_bit(bit_nr, &folio->flags.f)) 1239 return false; 1240 1241 wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE; 1242 return true; 1243 } 1244 1245 static inline int folio_wait_bit_common(struct folio *folio, int bit_nr, 1246 int state, enum behavior behavior) 1247 { 1248 wait_queue_head_t *q = folio_waitqueue(folio); 1249 int unfairness = sysctl_page_lock_unfairness; 1250 struct wait_page_queue wait_page; 1251 wait_queue_entry_t *wait = &wait_page.wait; 1252 bool thrashing = false; 1253 unsigned long pflags; 1254 bool in_thrashing; 1255 1256 if (bit_nr == PG_locked && 1257 !folio_test_uptodate(folio) && folio_test_workingset(folio)) { 1258 delayacct_thrashing_start(&in_thrashing); 1259 psi_memstall_enter(&pflags); 1260 thrashing = true; 1261 } 1262 1263 init_wait(wait); 1264 wait->func = wake_page_function; 1265 wait_page.folio = folio; 1266 wait_page.bit_nr = bit_nr; 1267 1268 repeat: 1269 wait->flags = 0; 1270 if (behavior == EXCLUSIVE) { 1271 wait->flags = WQ_FLAG_EXCLUSIVE; 1272 if (--unfairness < 0) 1273 wait->flags |= WQ_FLAG_CUSTOM; 1274 } 1275 1276 /* 1277 * Do one last check whether we can get the 1278 * page bit synchronously. 1279 * 1280 * Do the folio_set_waiters() marking before that 1281 * to let any waker we _just_ missed know they 1282 * need to wake us up (otherwise they'll never 1283 * even go to the slow case that looks at the 1284 * page queue), and add ourselves to the wait 1285 * queue if we need to sleep. 1286 * 1287 * This part needs to be done under the queue 1288 * lock to avoid races. 1289 */ 1290 spin_lock_irq(&q->lock); 1291 folio_set_waiters(folio); 1292 if (!folio_trylock_flag(folio, bit_nr, wait)) 1293 __add_wait_queue_entry_tail(q, wait); 1294 spin_unlock_irq(&q->lock); 1295 1296 /* 1297 * From now on, all the logic will be based on 1298 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to 1299 * see whether the page bit testing has already 1300 * been done by the wake function. 1301 * 1302 * We can drop our reference to the folio. 1303 */ 1304 if (behavior == DROP) 1305 folio_put(folio); 1306 1307 /* 1308 * Note that until the "finish_wait()", or until 1309 * we see the WQ_FLAG_WOKEN flag, we need to 1310 * be very careful with the 'wait->flags', because 1311 * we may race with a waker that sets them. 1312 */ 1313 for (;;) { 1314 unsigned int flags; 1315 1316 set_current_state(state); 1317 1318 /* Loop until we've been woken or interrupted */ 1319 flags = smp_load_acquire(&wait->flags); 1320 if (!(flags & WQ_FLAG_WOKEN)) { 1321 if (signal_pending_state(state, current)) 1322 break; 1323 1324 io_schedule(); 1325 continue; 1326 } 1327 1328 /* If we were non-exclusive, we're done */ 1329 if (behavior != EXCLUSIVE) 1330 break; 1331 1332 /* If the waker got the lock for us, we're done */ 1333 if (flags & WQ_FLAG_DONE) 1334 break; 1335 1336 /* 1337 * Otherwise, if we're getting the lock, we need to 1338 * try to get it ourselves. 1339 * 1340 * And if that fails, we'll have to retry this all. 1341 */ 1342 if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0)))) 1343 goto repeat; 1344 1345 wait->flags |= WQ_FLAG_DONE; 1346 break; 1347 } 1348 1349 /* 1350 * If a signal happened, this 'finish_wait()' may remove the last 1351 * waiter from the wait-queues, but the folio waiters bit will remain 1352 * set. That's ok. The next wakeup will take care of it, and trying 1353 * to do it here would be difficult and prone to races. 1354 */ 1355 finish_wait(q, wait); 1356 1357 if (thrashing) { 1358 delayacct_thrashing_end(&in_thrashing); 1359 psi_memstall_leave(&pflags); 1360 } 1361 1362 /* 1363 * NOTE! The wait->flags weren't stable until we've done the 1364 * 'finish_wait()', and we could have exited the loop above due 1365 * to a signal, and had a wakeup event happen after the signal 1366 * test but before the 'finish_wait()'. 1367 * 1368 * So only after the finish_wait() can we reliably determine 1369 * if we got woken up or not, so we can now figure out the final 1370 * return value based on that state without races. 1371 * 1372 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive 1373 * waiter, but an exclusive one requires WQ_FLAG_DONE. 1374 */ 1375 if (behavior == EXCLUSIVE) 1376 return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR; 1377 1378 return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR; 1379 } 1380 1381 #ifdef CONFIG_MIGRATION 1382 /** 1383 * softleaf_entry_wait_on_locked - Wait for a migration entry or 1384 * device_private entry to be removed. 1385 * @entry: migration or device_private swap entry. 1386 * @ptl: already locked ptl. This function will drop the lock. 1387 * 1388 * Wait for a migration entry referencing the given page, or device_private 1389 * entry referencing a dvice_private page to be unlocked. This is 1390 * equivalent to folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE) except 1391 * this can be called without taking a reference on the page. Instead this 1392 * should be called while holding the ptl for @entry referencing 1393 * the page. 1394 * 1395 * Returns after unlocking the ptl. 1396 * 1397 * This follows the same logic as folio_wait_bit_common() so see the comments 1398 * there. 1399 */ 1400 void softleaf_entry_wait_on_locked(softleaf_t entry, spinlock_t *ptl) 1401 __releases(ptl) 1402 { 1403 struct wait_page_queue wait_page; 1404 wait_queue_entry_t *wait = &wait_page.wait; 1405 bool thrashing = false; 1406 unsigned long pflags; 1407 bool in_thrashing; 1408 wait_queue_head_t *q; 1409 struct folio *folio = softleaf_to_folio(entry); 1410 1411 q = folio_waitqueue(folio); 1412 if (!folio_test_uptodate(folio) && folio_test_workingset(folio)) { 1413 delayacct_thrashing_start(&in_thrashing); 1414 psi_memstall_enter(&pflags); 1415 thrashing = true; 1416 } 1417 1418 init_wait(wait); 1419 wait->func = wake_page_function; 1420 wait_page.folio = folio; 1421 wait_page.bit_nr = PG_locked; 1422 wait->flags = 0; 1423 1424 spin_lock_irq(&q->lock); 1425 folio_set_waiters(folio); 1426 if (!folio_trylock_flag(folio, PG_locked, wait)) 1427 __add_wait_queue_entry_tail(q, wait); 1428 spin_unlock_irq(&q->lock); 1429 1430 /* 1431 * If a migration entry exists for the page the migration path must hold 1432 * a valid reference to the page, and it must take the ptl to remove the 1433 * migration entry. So the page is valid until the ptl is dropped. 1434 * Similarly any path attempting to drop the last reference to a 1435 * device-private page needs to grab the ptl to remove the device-private 1436 * entry. 1437 */ 1438 spin_unlock(ptl); 1439 1440 for (;;) { 1441 unsigned int flags; 1442 1443 set_current_state(TASK_UNINTERRUPTIBLE); 1444 1445 /* Loop until we've been woken or interrupted */ 1446 flags = smp_load_acquire(&wait->flags); 1447 if (!(flags & WQ_FLAG_WOKEN)) { 1448 if (signal_pending_state(TASK_UNINTERRUPTIBLE, current)) 1449 break; 1450 1451 io_schedule(); 1452 continue; 1453 } 1454 break; 1455 } 1456 1457 finish_wait(q, wait); 1458 1459 if (thrashing) { 1460 delayacct_thrashing_end(&in_thrashing); 1461 psi_memstall_leave(&pflags); 1462 } 1463 } 1464 #endif 1465 1466 void folio_wait_bit(struct folio *folio, int bit_nr) 1467 { 1468 folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED); 1469 } 1470 EXPORT_SYMBOL(folio_wait_bit); 1471 1472 int folio_wait_bit_killable(struct folio *folio, int bit_nr) 1473 { 1474 return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED); 1475 } 1476 EXPORT_SYMBOL(folio_wait_bit_killable); 1477 1478 /** 1479 * folio_put_wait_locked - Drop a reference and wait for it to be unlocked 1480 * @folio: The folio to wait for. 1481 * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc). 1482 * 1483 * The caller should hold a reference on @folio. They expect the page to 1484 * become unlocked relatively soon, but do not wish to hold up migration 1485 * (for example) by holding the reference while waiting for the folio to 1486 * come unlocked. After this function returns, the caller should not 1487 * dereference @folio. 1488 * 1489 * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal. 1490 */ 1491 static int folio_put_wait_locked(struct folio *folio, int state) 1492 { 1493 return folio_wait_bit_common(folio, PG_locked, state, DROP); 1494 } 1495 1496 /** 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. 1504 */ 1505 void folio_unlock(struct folio *folio) 1506 { 1507 /* Bit 7 allows x86 to check the byte's sign bit */ 1508 BUILD_BUG_ON(PG_waiters != 7); 1509 BUILD_BUG_ON(PG_locked > 7); 1510 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 1511 if (folio_xor_flags_has_waiters(folio, 1 << PG_locked)) 1512 folio_wake_bit(folio, PG_locked); 1513 } 1514 EXPORT_SYMBOL(folio_unlock); 1515 1516 /** 1517 * folio_end_read - End read on a folio. 1518 * @folio: The folio. 1519 * @success: True if all reads completed successfully. 1520 * 1521 * When all reads against a folio have completed, filesystems should 1522 * call this function to let the pagecache know that no more reads 1523 * are outstanding. This will unlock the folio and wake up any thread 1524 * sleeping on the lock. The folio will also be marked uptodate if all 1525 * reads succeeded. 1526 * 1527 * Context: May be called from interrupt or process context. May not be 1528 * called from NMI context. 1529 */ 1530 void folio_end_read(struct folio *folio, bool success) 1531 { 1532 unsigned long mask = 1 << PG_locked; 1533 1534 /* Must be in bottom byte for x86 to work */ 1535 BUILD_BUG_ON(PG_uptodate > 7); 1536 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 1537 VM_BUG_ON_FOLIO(success && folio_test_uptodate(folio), folio); 1538 1539 if (likely(success)) 1540 mask |= 1 << PG_uptodate; 1541 if (folio_xor_flags_has_waiters(folio, mask)) 1542 folio_wake_bit(folio, PG_locked); 1543 } 1544 EXPORT_SYMBOL(folio_end_read); 1545 1546 /** 1547 * folio_end_private_2 - Clear PG_private_2 and wake any waiters. 1548 * @folio: The folio. 1549 * 1550 * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for 1551 * it. The folio reference held for PG_private_2 being set is released. 1552 * 1553 * This is, for example, used when a netfs folio is being written to a local 1554 * disk cache, thereby allowing writes to the cache for the same folio to be 1555 * serialised. 1556 */ 1557 void folio_end_private_2(struct folio *folio) 1558 { 1559 VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio); 1560 clear_bit_unlock(PG_private_2, folio_flags(folio, 0)); 1561 folio_wake_bit(folio, PG_private_2); 1562 folio_put(folio); 1563 } 1564 EXPORT_SYMBOL(folio_end_private_2); 1565 1566 /** 1567 * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio. 1568 * @folio: The folio to wait on. 1569 * 1570 * Wait for PG_private_2 to be cleared on a folio. 1571 */ 1572 void folio_wait_private_2(struct folio *folio) 1573 { 1574 while (folio_test_private_2(folio)) 1575 folio_wait_bit(folio, PG_private_2); 1576 } 1577 EXPORT_SYMBOL(folio_wait_private_2); 1578 1579 /** 1580 * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio. 1581 * @folio: The folio to wait on. 1582 * 1583 * Wait for PG_private_2 to be cleared on a folio or until a fatal signal is 1584 * received by the calling task. 1585 * 1586 * Return: 1587 * - 0 if successful. 1588 * - -EINTR if a fatal signal was encountered. 1589 */ 1590 int folio_wait_private_2_killable(struct folio *folio) 1591 { 1592 int ret = 0; 1593 1594 while (folio_test_private_2(folio)) { 1595 ret = folio_wait_bit_killable(folio, PG_private_2); 1596 if (ret < 0) 1597 break; 1598 } 1599 1600 return ret; 1601 } 1602 EXPORT_SYMBOL(folio_wait_private_2_killable); 1603 1604 static void filemap_end_dropbehind(struct folio *folio) 1605 { 1606 struct address_space *mapping = folio->mapping; 1607 1608 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio); 1609 1610 if (folio_test_writeback(folio) || folio_test_dirty(folio)) 1611 return; 1612 if (!folio_test_clear_dropbehind(folio)) 1613 return; 1614 if (mapping) 1615 folio_unmap_invalidate(mapping, folio, 0); 1616 } 1617 1618 /* 1619 * If folio was marked as dropbehind, then pages should be dropped when writeback 1620 * completes. Do that now. If we fail, it's likely because of a big folio - 1621 * just reset dropbehind for that case and latter completions should invalidate. 1622 */ 1623 void folio_end_dropbehind(struct folio *folio) 1624 { 1625 if (!folio_test_dropbehind(folio)) 1626 return; 1627 1628 /* 1629 * Hitting !in_task() should not happen off RWF_DONTCACHE writeback, 1630 * but can happen if normal writeback just happens to find dirty folios 1631 * that were created as part of uncached writeback, and that writeback 1632 * would otherwise not need non-IRQ handling. Just skip the 1633 * invalidation in that case. 1634 */ 1635 if (in_task() && folio_trylock(folio)) { 1636 filemap_end_dropbehind(folio); 1637 folio_unlock(folio); 1638 } 1639 } 1640 EXPORT_SYMBOL_GPL(folio_end_dropbehind); 1641 1642 /** 1643 * folio_end_writeback_no_dropbehind - End writeback against a folio. 1644 * @folio: The folio. 1645 * 1646 * The folio must actually be under writeback. 1647 * This call is intended for filesystems that need to defer dropbehind. 1648 * 1649 * Context: May be called from process or interrupt context. 1650 */ 1651 void folio_end_writeback_no_dropbehind(struct folio *folio) 1652 { 1653 VM_BUG_ON_FOLIO(!folio_test_writeback(folio), folio); 1654 1655 /* 1656 * folio_test_clear_reclaim() could be used here but it is an 1657 * atomic operation and overkill in this particular case. Failing 1658 * to shuffle a folio marked for immediate reclaim is too mild 1659 * a gain to justify taking an atomic operation penalty at the 1660 * end of every folio writeback. 1661 */ 1662 if (folio_test_reclaim(folio)) { 1663 folio_clear_reclaim(folio); 1664 folio_rotate_reclaimable(folio); 1665 } 1666 1667 if (__folio_end_writeback(folio)) 1668 folio_wake_bit(folio, PG_writeback); 1669 1670 acct_reclaim_writeback(folio); 1671 } 1672 EXPORT_SYMBOL_GPL(folio_end_writeback_no_dropbehind); 1673 1674 /** 1675 * folio_end_writeback - End writeback against a folio. 1676 * @folio: The folio. 1677 * 1678 * The folio must actually be under writeback. 1679 * 1680 * Context: May be called from process or interrupt context. 1681 */ 1682 void folio_end_writeback(struct folio *folio) 1683 { 1684 VM_BUG_ON_FOLIO(!folio_test_writeback(folio), folio); 1685 1686 /* 1687 * Writeback does not hold a folio reference of its own, relying 1688 * on truncation to wait for the clearing of PG_writeback. 1689 * But here we must make sure that the folio is not freed and 1690 * reused before the folio_wake_bit(). 1691 */ 1692 folio_get(folio); 1693 folio_end_writeback_no_dropbehind(folio); 1694 folio_end_dropbehind(folio); 1695 folio_put(folio); 1696 } 1697 EXPORT_SYMBOL(folio_end_writeback); 1698 1699 /** 1700 * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it. 1701 * @folio: The folio to lock 1702 */ 1703 void __folio_lock(struct folio *folio) 1704 { 1705 folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE, 1706 EXCLUSIVE); 1707 } 1708 EXPORT_SYMBOL(__folio_lock); 1709 1710 int __folio_lock_killable(struct folio *folio) 1711 { 1712 return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE, 1713 EXCLUSIVE); 1714 } 1715 EXPORT_SYMBOL_GPL(__folio_lock_killable); 1716 1717 static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait) 1718 { 1719 struct wait_queue_head *q = folio_waitqueue(folio); 1720 int ret; 1721 1722 wait->folio = folio; 1723 wait->bit_nr = PG_locked; 1724 1725 spin_lock_irq(&q->lock); 1726 __add_wait_queue_entry_tail(q, &wait->wait); 1727 folio_set_waiters(folio); 1728 ret = !folio_trylock(folio); 1729 /* 1730 * If we were successful now, we know we're still on the 1731 * waitqueue as we're still under the lock. This means it's 1732 * safe to remove and return success, we know the callback 1733 * isn't going to trigger. 1734 */ 1735 if (!ret) 1736 __remove_wait_queue(q, &wait->wait); 1737 else 1738 ret = -EIOCBQUEUED; 1739 spin_unlock_irq(&q->lock); 1740 return ret; 1741 } 1742 1743 /* 1744 * Return values: 1745 * 0 - folio is locked. 1746 * non-zero - folio is not locked. 1747 * mmap_lock or per-VMA lock has been released (mmap_read_unlock() or 1748 * vma_end_read()), unless flags had both FAULT_FLAG_ALLOW_RETRY and 1749 * FAULT_FLAG_RETRY_NOWAIT set, in which case the lock is still held. 1750 * 1751 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 0 1752 * with the folio locked and the mmap_lock/per-VMA lock is left unperturbed. 1753 */ 1754 vm_fault_t __folio_lock_or_retry(struct folio *folio, struct vm_fault *vmf) 1755 { 1756 unsigned int flags = vmf->flags; 1757 1758 if (fault_flag_allow_retry_first(flags)) { 1759 /* 1760 * CAUTION! In this case, mmap_lock/per-VMA lock is not 1761 * released even though returning VM_FAULT_RETRY. 1762 */ 1763 if (flags & FAULT_FLAG_RETRY_NOWAIT) 1764 return VM_FAULT_RETRY; 1765 1766 release_fault_lock(vmf); 1767 if (flags & FAULT_FLAG_KILLABLE) 1768 folio_wait_locked_killable(folio); 1769 else 1770 folio_wait_locked(folio); 1771 return VM_FAULT_RETRY; 1772 } 1773 if (flags & FAULT_FLAG_KILLABLE) { 1774 bool ret; 1775 1776 ret = __folio_lock_killable(folio); 1777 if (ret) { 1778 release_fault_lock(vmf); 1779 return VM_FAULT_RETRY; 1780 } 1781 } else { 1782 __folio_lock(folio); 1783 } 1784 1785 return 0; 1786 } 1787 1788 /** 1789 * page_cache_next_miss() - Find the next gap in the page cache. 1790 * @mapping: Mapping. 1791 * @index: Index. 1792 * @max_scan: Maximum range to search. 1793 * 1794 * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the 1795 * gap with the lowest index. 1796 * 1797 * This function may be called under the rcu_read_lock. However, this will 1798 * not atomically search a snapshot of the cache at a single point in time. 1799 * For example, if a gap is created at index 5, then subsequently a gap is 1800 * created at index 10, page_cache_next_miss covering both indices may 1801 * return 10 if called under the rcu_read_lock. 1802 * 1803 * Return: The index of the gap if found, otherwise an index outside the 1804 * range specified (in which case 'return - index >= max_scan' will be true). 1805 * In the rare case of index wrap-around, 0 will be returned. 1806 */ 1807 pgoff_t page_cache_next_miss(struct address_space *mapping, 1808 pgoff_t index, unsigned long max_scan) 1809 { 1810 XA_STATE(xas, &mapping->i_pages, index); 1811 1812 while (max_scan--) { 1813 void *entry = xas_next(&xas); 1814 if (!entry || xa_is_value(entry)) 1815 return xas.xa_index; 1816 if (xas.xa_index == 0) 1817 return 0; 1818 } 1819 1820 /* Return end of the range + 1 when no hole is found */ 1821 return xas.xa_index + 1; 1822 } 1823 EXPORT_SYMBOL(page_cache_next_miss); 1824 1825 /** 1826 * page_cache_prev_miss() - Find the previous gap in the page cache. 1827 * @mapping: Mapping. 1828 * @index: Index. 1829 * @max_scan: Maximum range to search. 1830 * 1831 * Search the range [max(index - max_scan + 1, 0), index] for the 1832 * gap with the highest index. 1833 * 1834 * This function may be called under the rcu_read_lock. However, this will 1835 * not atomically search a snapshot of the cache at a single point in time. 1836 * For example, if a gap is created at index 10, then subsequently a gap is 1837 * created at index 5, page_cache_prev_miss() covering both indices may 1838 * return 5 if called under the rcu_read_lock. 1839 * 1840 * Return: The index of the gap if found, otherwise an index outside the 1841 * range specified (in which case 'index - return >= max_scan' will be true). 1842 * In the rare case of wrap-around, ULONG_MAX will be returned. 1843 */ 1844 pgoff_t page_cache_prev_miss(struct address_space *mapping, 1845 pgoff_t index, unsigned long max_scan) 1846 { 1847 XA_STATE(xas, &mapping->i_pages, index); 1848 1849 while (max_scan--) { 1850 void *entry = xas_prev(&xas); 1851 if (!entry || xa_is_value(entry)) 1852 return xas.xa_index; 1853 if (xas.xa_index == ULONG_MAX) 1854 return ULONG_MAX; 1855 } 1856 1857 /* Return start of the range - 1 when no hole is found */ 1858 return xas.xa_index - 1; 1859 } 1860 EXPORT_SYMBOL(page_cache_prev_miss); 1861 1862 /* 1863 * Lockless page cache protocol: 1864 * On the lookup side: 1865 * 1. Load the folio from i_pages 1866 * 2. Increment the refcount if it's not zero 1867 * 3. If the folio is not found by xas_reload(), put the refcount and retry 1868 * 1869 * On the removal side: 1870 * A. Freeze the page (by zeroing the refcount if nobody else has a reference) 1871 * B. Remove the page from i_pages 1872 * C. Return the page to the page allocator 1873 * 1874 * This means that any page may have its reference count temporarily 1875 * increased by a speculative page cache (or GUP-fast) lookup as it can 1876 * be allocated by another user before the RCU grace period expires. 1877 * Because the refcount temporarily acquired here may end up being the 1878 * last refcount on the page, any page allocation must be freeable by 1879 * folio_put(). 1880 */ 1881 1882 /* 1883 * filemap_get_entry - Get a page cache entry. 1884 * @mapping: the address_space to search 1885 * @index: The page cache index. 1886 * 1887 * Looks up the page cache entry at @mapping & @index. If it is a folio, 1888 * it is returned with an increased refcount. If it is a shadow entry 1889 * of a previously evicted folio, or a swap entry from shmem/tmpfs, 1890 * it is returned without further action. 1891 * 1892 * Return: The folio, swap or shadow entry, %NULL if nothing is found. 1893 */ 1894 void *filemap_get_entry(struct address_space *mapping, pgoff_t index) 1895 { 1896 XA_STATE(xas, &mapping->i_pages, index); 1897 struct folio *folio; 1898 1899 rcu_read_lock(); 1900 repeat: 1901 xas_reset(&xas); 1902 folio = xas_load(&xas); 1903 if (xas_retry(&xas, folio)) 1904 goto repeat; 1905 /* 1906 * A shadow entry of a recently evicted page, or a swap entry from 1907 * shmem/tmpfs. Return it without attempting to raise page count. 1908 */ 1909 if (!folio || xa_is_value(folio)) 1910 goto out; 1911 1912 if (!folio_try_get(folio)) 1913 goto repeat; 1914 1915 if (unlikely(folio != xas_reload(&xas))) { 1916 folio_put(folio); 1917 goto repeat; 1918 } 1919 out: 1920 rcu_read_unlock(); 1921 1922 return folio; 1923 } 1924 1925 /** 1926 * __filemap_get_folio_mpol - Find and get a reference to a folio. 1927 * @mapping: The address_space to search. 1928 * @index: The page index. 1929 * @fgp_flags: %FGP flags modify how the folio is returned. 1930 * @gfp: Memory allocation flags to use if %FGP_CREAT is specified. 1931 * @policy: NUMA memory allocation policy to follow. 1932 * 1933 * Looks up the page cache entry at @mapping & @index. 1934 * 1935 * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even 1936 * if the %GFP flags specified for %FGP_CREAT are atomic. 1937 * 1938 * If this function returns a folio, it is returned with an increased refcount. 1939 * 1940 * Return: The found folio or an ERR_PTR() otherwise. 1941 */ 1942 struct folio *__filemap_get_folio_mpol(struct address_space *mapping, 1943 pgoff_t index, fgf_t fgp_flags, gfp_t gfp, struct mempolicy *policy) 1944 { 1945 struct folio *folio; 1946 1947 repeat: 1948 folio = filemap_get_entry(mapping, index); 1949 if (xa_is_value(folio)) 1950 folio = NULL; 1951 if (!folio) 1952 goto no_page; 1953 1954 if (fgp_flags & FGP_LOCK) { 1955 if (fgp_flags & FGP_NOWAIT) { 1956 if (!folio_trylock(folio)) { 1957 folio_put(folio); 1958 return ERR_PTR(-EAGAIN); 1959 } 1960 } else { 1961 folio_lock(folio); 1962 } 1963 1964 /* Has the page been truncated? */ 1965 if (unlikely(folio->mapping != mapping)) { 1966 folio_unlock(folio); 1967 folio_put(folio); 1968 goto repeat; 1969 } 1970 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio); 1971 } 1972 1973 if (fgp_flags & FGP_ACCESSED) 1974 folio_mark_accessed(folio); 1975 else if (fgp_flags & FGP_WRITE) { 1976 /* Clear idle flag for buffer write */ 1977 if (folio_test_idle(folio)) 1978 folio_clear_idle(folio); 1979 } 1980 1981 if (fgp_flags & FGP_STABLE) 1982 folio_wait_stable(folio); 1983 no_page: 1984 if (!folio && (fgp_flags & FGP_CREAT)) { 1985 unsigned int min_order = mapping_min_folio_order(mapping); 1986 unsigned int order = max(min_order, FGF_GET_ORDER(fgp_flags)); 1987 int err; 1988 index = mapping_align_index(mapping, index); 1989 1990 if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping)) 1991 gfp |= __GFP_WRITE; 1992 if (fgp_flags & FGP_NOFS) 1993 gfp &= ~__GFP_FS; 1994 if (fgp_flags & FGP_NOWAIT) { 1995 gfp &= ~GFP_KERNEL; 1996 gfp |= GFP_NOWAIT; 1997 } 1998 if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP)))) 1999 fgp_flags |= FGP_LOCK; 2000 2001 if (order > mapping_max_folio_order(mapping)) 2002 order = mapping_max_folio_order(mapping); 2003 /* If we're not aligned, allocate a smaller folio */ 2004 if (index & ((1UL << order) - 1)) 2005 order = __ffs(index); 2006 2007 do { 2008 gfp_t alloc_gfp = gfp; 2009 2010 err = -ENOMEM; 2011 if (order > min_order) 2012 alloc_gfp |= __GFP_NORETRY | __GFP_NOWARN; 2013 folio = filemap_alloc_folio(alloc_gfp, order, policy); 2014 if (!folio) 2015 continue; 2016 2017 /* Init accessed so avoid atomic mark_page_accessed later */ 2018 if (fgp_flags & FGP_ACCESSED) 2019 __folio_set_referenced(folio); 2020 if (fgp_flags & FGP_DONTCACHE) 2021 __folio_set_dropbehind(folio); 2022 2023 err = filemap_add_folio(mapping, folio, index, gfp); 2024 if (!err) 2025 break; 2026 folio_put(folio); 2027 folio = NULL; 2028 } while (order-- > min_order); 2029 2030 if (err == -EEXIST) 2031 goto repeat; 2032 if (err) { 2033 /* 2034 * When NOWAIT I/O fails to allocate folios this could 2035 * be due to a nonblocking memory allocation and not 2036 * because the system actually is out of memory. 2037 * Return -EAGAIN so that there caller retries in a 2038 * blocking fashion instead of propagating -ENOMEM 2039 * to the application. 2040 */ 2041 if ((fgp_flags & FGP_NOWAIT) && err == -ENOMEM) 2042 err = -EAGAIN; 2043 return ERR_PTR(err); 2044 } 2045 /* 2046 * filemap_add_folio locks the page, and for mmap 2047 * we expect an unlocked page. 2048 */ 2049 if (folio && (fgp_flags & FGP_FOR_MMAP)) 2050 folio_unlock(folio); 2051 } 2052 2053 if (!folio) 2054 return ERR_PTR(-ENOENT); 2055 /* not an uncached lookup, clear uncached if set */ 2056 if (!(fgp_flags & FGP_DONTCACHE) && folio_test_clear_dropbehind(folio)) { 2057 if (folio_test_dirty(folio) && 2058 mapping_can_writeback(mapping)) { 2059 struct inode *inode = mapping->host; 2060 struct bdi_writeback *wb; 2061 struct wb_lock_cookie cookie = {}; 2062 long nr = folio_nr_pages(folio); 2063 2064 wb = unlocked_inode_to_wb_begin(inode, &cookie); 2065 wb_stat_mod(wb, WB_DONTCACHE_DIRTY, -nr); 2066 unlocked_inode_to_wb_end(inode, &cookie); 2067 } 2068 } 2069 return folio; 2070 } 2071 EXPORT_SYMBOL(__filemap_get_folio_mpol); 2072 2073 static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max, 2074 xa_mark_t mark) 2075 { 2076 struct folio *folio; 2077 2078 retry: 2079 if (mark == XA_PRESENT) 2080 folio = xas_find(xas, max); 2081 else 2082 folio = xas_find_marked(xas, max, mark); 2083 2084 if (xas_retry(xas, folio)) 2085 goto retry; 2086 /* 2087 * A shadow entry of a recently evicted page, a swap 2088 * entry from shmem/tmpfs or a DAX entry. Return it 2089 * without attempting to raise page count. 2090 */ 2091 if (!folio || xa_is_value(folio)) 2092 return folio; 2093 2094 if (!folio_try_get(folio)) 2095 goto reset; 2096 2097 if (unlikely(folio != xas_reload(xas))) { 2098 folio_put(folio); 2099 goto reset; 2100 } 2101 2102 return folio; 2103 reset: 2104 xas_reset(xas); 2105 goto retry; 2106 } 2107 2108 /** 2109 * find_get_entries - gang pagecache lookup 2110 * @mapping: The address_space to search 2111 * @start: The starting page cache index 2112 * @end: The final page index (inclusive). 2113 * @fbatch: Where the resulting entries are placed. 2114 * @indices: The cache indices corresponding to the entries in @entries 2115 * 2116 * find_get_entries() will search for and return a batch of entries in 2117 * the mapping. The entries are placed in @fbatch. find_get_entries() 2118 * takes a reference on any actual folios it returns. 2119 * 2120 * The entries have ascending indexes. The indices may not be consecutive 2121 * due to not-present entries or large folios. 2122 * 2123 * Any shadow entries of evicted folios, or swap entries from 2124 * shmem/tmpfs, are included in the returned array. 2125 * 2126 * Return: The number of entries which were found. 2127 */ 2128 unsigned find_get_entries(struct address_space *mapping, pgoff_t *start, 2129 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices) 2130 { 2131 XA_STATE(xas, &mapping->i_pages, *start); 2132 struct folio *folio; 2133 2134 rcu_read_lock(); 2135 while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) { 2136 indices[fbatch->nr] = xas.xa_index; 2137 if (!folio_batch_add(fbatch, folio)) 2138 break; 2139 } 2140 2141 if (folio_batch_count(fbatch)) { 2142 unsigned long nr; 2143 int idx = folio_batch_count(fbatch) - 1; 2144 2145 folio = fbatch->folios[idx]; 2146 if (!xa_is_value(folio)) 2147 nr = folio_nr_pages(folio); 2148 else 2149 nr = 1 << xa_get_order(&mapping->i_pages, indices[idx]); 2150 *start = round_down(indices[idx] + nr, nr); 2151 } 2152 rcu_read_unlock(); 2153 2154 return folio_batch_count(fbatch); 2155 } 2156 2157 /** 2158 * find_lock_entries - Find a batch of pagecache entries. 2159 * @mapping: The address_space to search. 2160 * @start: The starting page cache index. 2161 * @end: The final page index (inclusive). 2162 * @fbatch: Where the resulting entries are placed. 2163 * @indices: The cache indices of the entries in @fbatch. 2164 * 2165 * find_lock_entries() will return a batch of entries from @mapping. 2166 * Swap, shadow and DAX entries are included. Folios are returned 2167 * locked and with an incremented refcount. Folios which are locked 2168 * by somebody else or under writeback are skipped. Folios which are 2169 * partially outside the range are not returned. 2170 * 2171 * The entries have ascending indexes. The indices may not be consecutive 2172 * due to not-present entries, large folios, folios which could not be 2173 * locked or folios under writeback. 2174 * 2175 * Return: The number of entries which were found. 2176 */ 2177 unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start, 2178 pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices) 2179 { 2180 XA_STATE(xas, &mapping->i_pages, *start); 2181 struct folio *folio; 2182 2183 rcu_read_lock(); 2184 while ((folio = find_get_entry(&xas, end, XA_PRESENT))) { 2185 unsigned long base; 2186 unsigned long nr; 2187 2188 if (!xa_is_value(folio)) { 2189 nr = folio_nr_pages(folio); 2190 base = folio->index; 2191 /* Omit large folio which begins before the start */ 2192 if (base < *start) 2193 goto put; 2194 /* Omit large folio which extends beyond the end */ 2195 if (base + nr - 1 > end) 2196 goto put; 2197 if (!folio_trylock(folio)) 2198 goto put; 2199 if (folio->mapping != mapping || 2200 folio_test_writeback(folio)) 2201 goto unlock; 2202 VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index), 2203 folio); 2204 } else { 2205 nr = 1 << xas_get_order(&xas); 2206 base = xas.xa_index & ~(nr - 1); 2207 /* Omit order>0 value which begins before the start */ 2208 if (base < *start) 2209 continue; 2210 /* Omit order>0 value which extends beyond the end */ 2211 if (base + nr - 1 > end) 2212 break; 2213 } 2214 2215 /* Update start now so that last update is correct on return */ 2216 *start = base + nr; 2217 indices[fbatch->nr] = xas.xa_index; 2218 if (!folio_batch_add(fbatch, folio)) 2219 break; 2220 continue; 2221 unlock: 2222 folio_unlock(folio); 2223 put: 2224 folio_put(folio); 2225 } 2226 rcu_read_unlock(); 2227 2228 return folio_batch_count(fbatch); 2229 } 2230 2231 /** 2232 * filemap_get_folios - Get a batch of folios 2233 * @mapping: The address_space to search 2234 * @start: The starting page index 2235 * @end: The final page index (inclusive) 2236 * @fbatch: The batch to fill. 2237 * 2238 * Search for and return a batch of folios in the mapping starting at 2239 * index @start and up to index @end (inclusive). The folios are returned 2240 * in @fbatch with an elevated reference count. 2241 * 2242 * Return: The number of folios which were found. 2243 * We also update @start to index the next folio for the traversal. 2244 */ 2245 unsigned filemap_get_folios(struct address_space *mapping, pgoff_t *start, 2246 pgoff_t end, struct folio_batch *fbatch) 2247 { 2248 return filemap_get_folios_tag(mapping, start, end, XA_PRESENT, fbatch); 2249 } 2250 EXPORT_SYMBOL(filemap_get_folios); 2251 2252 /** 2253 * filemap_get_folios_contig - Get a batch of contiguous folios 2254 * @mapping: The address_space to search 2255 * @start: The starting page index 2256 * @end: The final page index (inclusive) 2257 * @fbatch: The batch to fill 2258 * 2259 * filemap_get_folios_contig() works exactly like filemap_get_folios(), 2260 * except the returned folios are guaranteed to be contiguous. This may 2261 * not return all contiguous folios if the batch gets filled up. 2262 * 2263 * Return: The number of folios found. 2264 * Also update @start to be positioned for traversal of the next folio. 2265 */ 2266 2267 unsigned filemap_get_folios_contig(struct address_space *mapping, 2268 pgoff_t *start, pgoff_t end, struct folio_batch *fbatch) 2269 { 2270 XA_STATE(xas, &mapping->i_pages, *start); 2271 unsigned long nr; 2272 struct folio *folio; 2273 2274 rcu_read_lock(); 2275 2276 for (folio = xas_load(&xas); folio && xas.xa_index <= end; 2277 folio = xas_next(&xas)) { 2278 if (xas_retry(&xas, folio)) 2279 continue; 2280 /* 2281 * If the entry has been swapped out, we can stop looking. 2282 * No current caller is looking for DAX entries. 2283 */ 2284 if (xa_is_value(folio)) 2285 goto update_start; 2286 2287 /* If we landed in the middle of a THP, continue at its end. */ 2288 if (xa_is_sibling(folio)) 2289 goto update_start; 2290 2291 if (!folio_try_get(folio)) 2292 goto retry; 2293 2294 if (unlikely(folio != xas_reload(&xas))) 2295 goto put_folio; 2296 2297 if (!folio_batch_add(fbatch, folio)) { 2298 *start = folio_next_index(folio); 2299 goto out; 2300 } 2301 xas_advance(&xas, folio_next_index(folio) - 1); 2302 continue; 2303 put_folio: 2304 folio_put(folio); 2305 2306 retry: 2307 xas_reset(&xas); 2308 } 2309 2310 update_start: 2311 nr = folio_batch_count(fbatch); 2312 2313 if (nr) { 2314 folio = fbatch->folios[nr - 1]; 2315 *start = folio_next_index(folio); 2316 } 2317 out: 2318 rcu_read_unlock(); 2319 return folio_batch_count(fbatch); 2320 } 2321 EXPORT_SYMBOL(filemap_get_folios_contig); 2322 2323 /** 2324 * filemap_get_folios_tag - Get a batch of folios matching @tag 2325 * @mapping: The address_space to search 2326 * @start: The starting page index 2327 * @end: The final page index (inclusive) 2328 * @tag: The tag index 2329 * @fbatch: The batch to fill 2330 * 2331 * The first folio may start before @start; if it does, it will contain 2332 * @start. The final folio may extend beyond @end; if it does, it will 2333 * contain @end. The folios have ascending indices. There may be gaps 2334 * between the folios if there are indices which have no folio in the 2335 * page cache. If folios are added to or removed from the page cache 2336 * while this is running, they may or may not be found by this call. 2337 * Only returns folios that are tagged with @tag. 2338 * 2339 * Return: The number of folios found. 2340 * Also update @start to index the next folio for traversal. 2341 */ 2342 unsigned filemap_get_folios_tag(struct address_space *mapping, pgoff_t *start, 2343 pgoff_t end, xa_mark_t tag, struct folio_batch *fbatch) 2344 { 2345 XA_STATE(xas, &mapping->i_pages, *start); 2346 struct folio *folio; 2347 2348 rcu_read_lock(); 2349 while ((folio = find_get_entry(&xas, end, tag)) != NULL) { 2350 /* 2351 * Shadow entries should never be tagged, but this iteration 2352 * is lockless so there is a window for page reclaim to evict 2353 * a page we saw tagged. Skip over it. 2354 */ 2355 if (xa_is_value(folio)) 2356 continue; 2357 if (!folio_batch_add(fbatch, folio)) { 2358 *start = folio_next_index(folio); 2359 goto out; 2360 } 2361 } 2362 /* 2363 * We come here when there is no page beyond @end. We take care to not 2364 * overflow the index @start as it confuses some of the callers. This 2365 * breaks the iteration when there is a page at index -1 but that is 2366 * already broke anyway. 2367 */ 2368 if (end == (pgoff_t)-1) 2369 *start = (pgoff_t)-1; 2370 else 2371 *start = end + 1; 2372 out: 2373 rcu_read_unlock(); 2374 2375 return folio_batch_count(fbatch); 2376 } 2377 EXPORT_SYMBOL(filemap_get_folios_tag); 2378 2379 /** 2380 * filemap_get_folios_dirty - Get a batch of dirty folios 2381 * @mapping: The address_space to search 2382 * @start: The starting folio index 2383 * @end: The final folio index (inclusive) 2384 * @fbatch: The batch to fill 2385 * 2386 * filemap_get_folios_dirty() works exactly like filemap_get_folios(), except 2387 * the returned folios are presumed to be dirty or undergoing writeback. Dirty 2388 * state is presumed because we don't block on folio lock nor want to miss 2389 * folios. Callers that need to can recheck state upon locking the folio. 2390 * 2391 * This may not return all dirty folios if the batch gets filled up. 2392 * 2393 * Return: The number of folios found. 2394 * Also update @start to be positioned for traversal of the next folio. 2395 */ 2396 unsigned filemap_get_folios_dirty(struct address_space *mapping, pgoff_t *start, 2397 pgoff_t end, struct folio_batch *fbatch) 2398 { 2399 XA_STATE(xas, &mapping->i_pages, *start); 2400 struct folio *folio; 2401 2402 rcu_read_lock(); 2403 while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) { 2404 if (xa_is_value(folio)) 2405 continue; 2406 if (folio_trylock(folio)) { 2407 bool clean = !folio_test_dirty(folio) && 2408 !folio_test_writeback(folio); 2409 folio_unlock(folio); 2410 if (clean) { 2411 folio_put(folio); 2412 continue; 2413 } 2414 } 2415 if (!folio_batch_add(fbatch, folio)) { 2416 *start = folio_next_index(folio); 2417 goto out; 2418 } 2419 } 2420 /* 2421 * We come here when there is no folio beyond @end. We take care to not 2422 * overflow the index @start as it confuses some of the callers. This 2423 * breaks the iteration when there is a folio at index -1 but that is 2424 * already broke anyway. 2425 */ 2426 if (end == (pgoff_t)-1) 2427 *start = (pgoff_t)-1; 2428 else 2429 *start = end + 1; 2430 out: 2431 rcu_read_unlock(); 2432 2433 return folio_batch_count(fbatch); 2434 } 2435 2436 /* 2437 * CD/DVDs are error prone. When a medium error occurs, the driver may fail 2438 * a _large_ part of the i/o request. Imagine the worst scenario: 2439 * 2440 * ---R__________________________________________B__________ 2441 * ^ reading here ^ bad block(assume 4k) 2442 * 2443 * read(R) => miss => readahead(R...B) => media error => frustrating retries 2444 * => failing the whole request => read(R) => read(R+1) => 2445 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) => 2446 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) => 2447 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ...... 2448 * 2449 * It is going insane. Fix it by quickly scaling down the readahead size. 2450 */ 2451 static void shrink_readahead_size_eio(struct file_ra_state *ra) 2452 { 2453 ra->ra_pages /= 4; 2454 } 2455 2456 /* 2457 * filemap_get_read_batch - Get a batch of folios for read 2458 * 2459 * Get a batch of folios which represent a contiguous range of bytes in 2460 * the file. No exceptional entries will be returned. If @index is in 2461 * the middle of a folio, the entire folio will be returned. The last 2462 * folio in the batch may have the readahead flag set or the uptodate flag 2463 * clear so that the caller can take the appropriate action. 2464 */ 2465 static void filemap_get_read_batch(struct address_space *mapping, 2466 pgoff_t index, pgoff_t max, struct folio_batch *fbatch) 2467 { 2468 XA_STATE(xas, &mapping->i_pages, index); 2469 struct folio *folio; 2470 2471 rcu_read_lock(); 2472 for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) { 2473 if (xas_retry(&xas, folio)) 2474 continue; 2475 if (xas.xa_index > max || xa_is_value(folio)) 2476 break; 2477 if (xa_is_sibling(folio)) 2478 break; 2479 if (!folio_try_get(folio)) 2480 goto retry; 2481 2482 if (unlikely(folio != xas_reload(&xas))) 2483 goto put_folio; 2484 2485 if (!folio_batch_add(fbatch, folio)) 2486 break; 2487 if (!folio_test_uptodate(folio)) 2488 break; 2489 if (folio_test_readahead(folio)) 2490 break; 2491 xas_advance(&xas, folio_next_index(folio) - 1); 2492 continue; 2493 put_folio: 2494 folio_put(folio); 2495 retry: 2496 xas_reset(&xas); 2497 } 2498 rcu_read_unlock(); 2499 } 2500 2501 static int filemap_read_folio(struct file *file, filler_t filler, 2502 struct folio *folio) 2503 { 2504 bool workingset = folio_test_workingset(folio); 2505 unsigned long pflags; 2506 int error; 2507 2508 /* Start the actual read. The read will unlock the page. */ 2509 if (unlikely(workingset)) 2510 psi_memstall_enter(&pflags); 2511 error = filler(file, folio); 2512 if (unlikely(workingset)) 2513 psi_memstall_leave(&pflags); 2514 if (error) 2515 return error; 2516 2517 error = folio_wait_locked_killable(folio); 2518 if (error) 2519 return error; 2520 if (folio_test_uptodate(folio)) 2521 return 0; 2522 if (file) 2523 shrink_readahead_size_eio(&file->f_ra); 2524 return -EIO; 2525 } 2526 2527 static bool filemap_range_uptodate(struct address_space *mapping, 2528 loff_t pos, size_t count, struct folio *folio, 2529 bool need_uptodate) 2530 { 2531 if (folio_test_uptodate(folio)) 2532 return true; 2533 /* pipes can't handle partially uptodate pages */ 2534 if (need_uptodate) 2535 return false; 2536 if (!mapping->a_ops->is_partially_uptodate) 2537 return false; 2538 if (mapping->host->i_blkbits >= folio_shift(folio)) 2539 return false; 2540 2541 if (folio_pos(folio) > pos) { 2542 count -= folio_pos(folio) - pos; 2543 pos = 0; 2544 } else { 2545 pos -= folio_pos(folio); 2546 } 2547 2548 if (pos == 0 && count >= folio_size(folio)) 2549 return false; 2550 2551 return mapping->a_ops->is_partially_uptodate(folio, pos, count); 2552 } 2553 2554 static int filemap_update_page(struct kiocb *iocb, 2555 struct address_space *mapping, size_t count, 2556 struct folio *folio, bool need_uptodate) 2557 { 2558 int error; 2559 2560 if (iocb->ki_flags & IOCB_NOWAIT) { 2561 if (!filemap_invalidate_trylock_shared(mapping)) 2562 return -EAGAIN; 2563 } else { 2564 filemap_invalidate_lock_shared(mapping); 2565 } 2566 2567 if (!folio_trylock(folio)) { 2568 error = -EAGAIN; 2569 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO)) 2570 goto unlock_mapping; 2571 if (!(iocb->ki_flags & IOCB_WAITQ)) { 2572 filemap_invalidate_unlock_shared(mapping); 2573 /* 2574 * This is where we usually end up waiting for a 2575 * previously submitted readahead to finish. 2576 */ 2577 folio_put_wait_locked(folio, TASK_KILLABLE); 2578 return AOP_TRUNCATED_PAGE; 2579 } 2580 error = __folio_lock_async(folio, iocb->ki_waitq); 2581 if (error) 2582 goto unlock_mapping; 2583 } 2584 2585 error = AOP_TRUNCATED_PAGE; 2586 if (!folio->mapping) 2587 goto unlock; 2588 2589 error = 0; 2590 if (filemap_range_uptodate(mapping, iocb->ki_pos, count, folio, 2591 need_uptodate)) 2592 goto unlock; 2593 2594 error = -EAGAIN; 2595 if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ)) 2596 goto unlock; 2597 2598 error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio, 2599 folio); 2600 goto unlock_mapping; 2601 unlock: 2602 folio_unlock(folio); 2603 unlock_mapping: 2604 filemap_invalidate_unlock_shared(mapping); 2605 if (error == AOP_TRUNCATED_PAGE) 2606 folio_put(folio); 2607 return error; 2608 } 2609 2610 static int filemap_create_folio(struct kiocb *iocb, struct folio_batch *fbatch) 2611 { 2612 struct address_space *mapping = iocb->ki_filp->f_mapping; 2613 struct folio *folio; 2614 int error; 2615 unsigned int min_order = mapping_min_folio_order(mapping); 2616 pgoff_t index; 2617 2618 if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ)) 2619 return -EAGAIN; 2620 2621 folio = filemap_alloc_folio(mapping_gfp_mask(mapping), min_order, NULL); 2622 if (!folio) 2623 return -ENOMEM; 2624 if (iocb->ki_flags & IOCB_DONTCACHE) 2625 __folio_set_dropbehind(folio); 2626 2627 /* 2628 * Protect against truncate / hole punch. Grabbing invalidate_lock 2629 * here assures we cannot instantiate and bring uptodate new 2630 * pagecache folios after evicting page cache during truncate 2631 * and before actually freeing blocks. Note that we could 2632 * release invalidate_lock after inserting the folio into 2633 * the page cache as the locked folio would then be enough to 2634 * synchronize with hole punching. But there are code paths 2635 * such as filemap_update_page() filling in partially uptodate 2636 * pages or ->readahead() that need to hold invalidate_lock 2637 * while mapping blocks for IO so let's hold the lock here as 2638 * well to keep locking rules simple. 2639 */ 2640 filemap_invalidate_lock_shared(mapping); 2641 index = (iocb->ki_pos >> (PAGE_SHIFT + min_order)) << min_order; 2642 error = filemap_add_folio(mapping, folio, index, 2643 mapping_gfp_constraint(mapping, GFP_KERNEL)); 2644 if (error == -EEXIST) 2645 error = AOP_TRUNCATED_PAGE; 2646 if (error) 2647 goto error; 2648 2649 error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio, 2650 folio); 2651 if (error) 2652 goto error; 2653 2654 filemap_invalidate_unlock_shared(mapping); 2655 folio_batch_add(fbatch, folio); 2656 return 0; 2657 error: 2658 filemap_invalidate_unlock_shared(mapping); 2659 folio_put(folio); 2660 return error; 2661 } 2662 2663 static int filemap_readahead(struct kiocb *iocb, struct file *file, 2664 struct address_space *mapping, struct folio *folio, 2665 pgoff_t last_index) 2666 { 2667 DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index); 2668 2669 if (iocb->ki_flags & IOCB_NOIO) 2670 return -EAGAIN; 2671 if (iocb->ki_flags & IOCB_DONTCACHE) 2672 ractl.dropbehind = 1; 2673 page_cache_async_ra(&ractl, folio, last_index - folio->index); 2674 return 0; 2675 } 2676 2677 static int filemap_get_pages(struct kiocb *iocb, size_t count, 2678 struct folio_batch *fbatch, bool need_uptodate) 2679 { 2680 struct file *filp = iocb->ki_filp; 2681 struct address_space *mapping = filp->f_mapping; 2682 pgoff_t index = iocb->ki_pos >> PAGE_SHIFT; 2683 pgoff_t last_index; 2684 struct folio *folio; 2685 unsigned int flags; 2686 int err = 0; 2687 2688 /* "last_index" is the index of the folio beyond the end of the read */ 2689 last_index = round_up(iocb->ki_pos + count, 2690 mapping_min_folio_nrbytes(mapping)) >> PAGE_SHIFT; 2691 retry: 2692 if (fatal_signal_pending(current)) 2693 return -EINTR; 2694 2695 filemap_get_read_batch(mapping, index, last_index - 1, fbatch); 2696 if (!folio_batch_count(fbatch)) { 2697 DEFINE_READAHEAD(ractl, filp, &filp->f_ra, mapping, index); 2698 2699 if (iocb->ki_flags & IOCB_NOIO) 2700 return -EAGAIN; 2701 if (iocb->ki_flags & IOCB_NOWAIT) 2702 flags = memalloc_noio_save(); 2703 if (iocb->ki_flags & IOCB_DONTCACHE) 2704 ractl.dropbehind = 1; 2705 page_cache_sync_ra(&ractl, last_index - index); 2706 if (iocb->ki_flags & IOCB_NOWAIT) 2707 memalloc_noio_restore(flags); 2708 filemap_get_read_batch(mapping, index, last_index - 1, fbatch); 2709 } 2710 if (!folio_batch_count(fbatch)) { 2711 err = filemap_create_folio(iocb, fbatch); 2712 if (err == AOP_TRUNCATED_PAGE) 2713 goto retry; 2714 return err; 2715 } 2716 2717 folio = fbatch->folios[folio_batch_count(fbatch) - 1]; 2718 if (folio_test_readahead(folio)) { 2719 err = filemap_readahead(iocb, filp, mapping, folio, last_index); 2720 if (err) 2721 goto err; 2722 } 2723 if (!folio_test_uptodate(folio)) { 2724 if (folio_batch_count(fbatch) > 1) { 2725 err = -EAGAIN; 2726 goto err; 2727 } 2728 err = filemap_update_page(iocb, mapping, count, folio, 2729 need_uptodate); 2730 if (err) 2731 goto err; 2732 } 2733 2734 trace_mm_filemap_get_pages(mapping, index, last_index - 1); 2735 return 0; 2736 err: 2737 if (err < 0) 2738 folio_put(folio); 2739 if (likely(--fbatch->nr)) 2740 return 0; 2741 if (err == AOP_TRUNCATED_PAGE) 2742 goto retry; 2743 return err; 2744 } 2745 2746 static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio) 2747 { 2748 unsigned int shift = folio_shift(folio); 2749 2750 return (pos1 >> shift == pos2 >> shift); 2751 } 2752 2753 static void filemap_end_dropbehind_read(struct folio *folio) 2754 { 2755 if (!folio_test_dropbehind(folio)) 2756 return; 2757 if (folio_test_writeback(folio) || folio_test_dirty(folio)) 2758 return; 2759 if (folio_trylock(folio)) { 2760 filemap_end_dropbehind(folio); 2761 folio_unlock(folio); 2762 } 2763 } 2764 2765 /** 2766 * filemap_read - Read data from the page cache. 2767 * @iocb: The iocb to read. 2768 * @iter: Destination for the data. 2769 * @already_read: Number of bytes already read by the caller. 2770 * 2771 * Copies data from the page cache. If the data is not currently present, 2772 * uses the readahead and read_folio address_space operations to fetch it. 2773 * 2774 * Return: Total number of bytes copied, including those already read by 2775 * the caller. If an error happens before any bytes are copied, returns 2776 * a negative error number. 2777 */ 2778 ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter, 2779 ssize_t already_read) 2780 { 2781 struct file *filp = iocb->ki_filp; 2782 struct file_ra_state *ra = &filp->f_ra; 2783 struct address_space *mapping = filp->f_mapping; 2784 struct inode *inode = mapping->host; 2785 struct folio_batch fbatch; 2786 int i, error = 0; 2787 bool writably_mapped; 2788 loff_t isize, end_offset; 2789 loff_t last_pos = ra->prev_pos; 2790 2791 if (unlikely(iocb->ki_pos < 0)) 2792 return -EINVAL; 2793 if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes)) 2794 return 0; 2795 if (unlikely(!iov_iter_count(iter))) 2796 return 0; 2797 2798 iov_iter_truncate(iter, inode->i_sb->s_maxbytes - iocb->ki_pos); 2799 folio_batch_init(&fbatch); 2800 2801 do { 2802 cond_resched(); 2803 2804 /* 2805 * If we've already successfully copied some data, then we 2806 * can no longer safely return -EIOCBQUEUED. Hence mark 2807 * an async read NOWAIT at that point. 2808 */ 2809 if ((iocb->ki_flags & IOCB_WAITQ) && already_read) 2810 iocb->ki_flags |= IOCB_NOWAIT; 2811 2812 if (unlikely(iocb->ki_pos >= i_size_read(inode))) 2813 break; 2814 2815 error = filemap_get_pages(iocb, iter->count, &fbatch, false); 2816 if (error < 0) 2817 break; 2818 2819 /* 2820 * i_size must be checked after we know the pages are Uptodate. 2821 * 2822 * Checking i_size after the check allows us to calculate 2823 * the correct value for "nr", which means the zero-filled 2824 * part of the page is not copied back to userspace (unless 2825 * another truncate extends the file - this is desired though). 2826 */ 2827 isize = i_size_read(inode); 2828 if (unlikely(iocb->ki_pos >= isize)) 2829 goto put_folios; 2830 end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count); 2831 2832 /* 2833 * Once we start copying data, we don't want to be touching any 2834 * cachelines that might be contended: 2835 */ 2836 writably_mapped = mapping_writably_mapped(mapping); 2837 2838 /* 2839 * When a read accesses the same folio several times, only 2840 * mark it as accessed the first time. 2841 */ 2842 if (!pos_same_folio(iocb->ki_pos, last_pos - 1, 2843 fbatch.folios[0])) 2844 folio_mark_accessed(fbatch.folios[0]); 2845 2846 for (i = 0; i < folio_batch_count(&fbatch); i++) { 2847 struct folio *folio = fbatch.folios[i]; 2848 size_t fsize = folio_size(folio); 2849 size_t offset = iocb->ki_pos & (fsize - 1); 2850 size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos, 2851 fsize - offset); 2852 size_t copied; 2853 2854 if (end_offset < folio_pos(folio)) 2855 break; 2856 if (i > 0) 2857 folio_mark_accessed(folio); 2858 /* 2859 * If users can be writing to this folio using arbitrary 2860 * virtual addresses, take care of potential aliasing 2861 * before reading the folio on the kernel side. 2862 */ 2863 if (writably_mapped) 2864 flush_dcache_folio(folio); 2865 2866 copied = copy_folio_to_iter(folio, offset, bytes, iter); 2867 2868 already_read += copied; 2869 iocb->ki_pos += copied; 2870 last_pos = iocb->ki_pos; 2871 2872 if (copied < bytes) { 2873 error = -EFAULT; 2874 break; 2875 } 2876 } 2877 put_folios: 2878 for (i = 0; i < folio_batch_count(&fbatch); i++) { 2879 struct folio *folio = fbatch.folios[i]; 2880 2881 filemap_end_dropbehind_read(folio); 2882 folio_put(folio); 2883 } 2884 folio_batch_init(&fbatch); 2885 } while (iov_iter_count(iter) && iocb->ki_pos < isize && !error); 2886 2887 file_accessed(filp); 2888 ra->prev_pos = last_pos; 2889 return already_read ? already_read : error; 2890 } 2891 EXPORT_SYMBOL_GPL(filemap_read); 2892 2893 int kiocb_write_and_wait(struct kiocb *iocb, size_t count) 2894 { 2895 struct address_space *mapping = iocb->ki_filp->f_mapping; 2896 loff_t pos = iocb->ki_pos; 2897 loff_t end = pos + count - 1; 2898 2899 if (iocb->ki_flags & IOCB_NOWAIT) { 2900 if (filemap_range_needs_writeback(mapping, pos, end)) 2901 return -EAGAIN; 2902 return 0; 2903 } 2904 2905 return filemap_write_and_wait_range(mapping, pos, end); 2906 } 2907 EXPORT_SYMBOL_GPL(kiocb_write_and_wait); 2908 2909 int filemap_invalidate_pages(struct address_space *mapping, 2910 loff_t pos, loff_t end, bool nowait) 2911 { 2912 int ret; 2913 2914 if (nowait) { 2915 /* we could block if there are any pages in the range */ 2916 if (filemap_range_has_page(mapping, pos, end)) 2917 return -EAGAIN; 2918 } else { 2919 ret = filemap_write_and_wait_range(mapping, pos, end); 2920 if (ret) 2921 return ret; 2922 } 2923 2924 /* 2925 * After a write we want buffered reads to be sure to go to disk to get 2926 * the new data. We invalidate clean cached page from the region we're 2927 * about to write. We do this *before* the write so that we can return 2928 * without clobbering -EIOCBQUEUED from ->direct_IO(). 2929 */ 2930 return invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT, 2931 end >> PAGE_SHIFT); 2932 } 2933 2934 int kiocb_invalidate_pages(struct kiocb *iocb, size_t count) 2935 { 2936 struct address_space *mapping = iocb->ki_filp->f_mapping; 2937 2938 return filemap_invalidate_pages(mapping, iocb->ki_pos, 2939 iocb->ki_pos + count - 1, 2940 iocb->ki_flags & IOCB_NOWAIT); 2941 } 2942 EXPORT_SYMBOL_GPL(kiocb_invalidate_pages); 2943 2944 /** 2945 * generic_file_read_iter - generic filesystem read routine 2946 * @iocb: kernel I/O control block 2947 * @iter: destination for the data read 2948 * 2949 * This is the "read_iter()" routine for all filesystems 2950 * that can use the page cache directly. 2951 * 2952 * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall 2953 * be returned when no data can be read without waiting for I/O requests 2954 * to complete; it doesn't prevent readahead. 2955 * 2956 * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O 2957 * requests shall be made for the read or for readahead. When no data 2958 * can be read, -EAGAIN shall be returned. When readahead would be 2959 * triggered, a partial, possibly empty read shall be returned. 2960 * 2961 * Return: 2962 * * number of bytes copied, even for partial reads 2963 * * negative error code (or 0 if IOCB_NOIO) if nothing was read 2964 */ 2965 ssize_t 2966 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter) 2967 { 2968 size_t count = iov_iter_count(iter); 2969 ssize_t retval = 0; 2970 2971 if (!count) 2972 return 0; /* skip atime */ 2973 2974 if (iocb->ki_flags & IOCB_DIRECT) { 2975 struct file *file = iocb->ki_filp; 2976 struct address_space *mapping = file->f_mapping; 2977 struct inode *inode = mapping->host; 2978 2979 retval = kiocb_write_and_wait(iocb, count); 2980 if (retval < 0) 2981 return retval; 2982 file_accessed(file); 2983 2984 retval = mapping->a_ops->direct_IO(iocb, iter); 2985 if (retval >= 0) { 2986 iocb->ki_pos += retval; 2987 count -= retval; 2988 } 2989 if (retval != -EIOCBQUEUED) 2990 iov_iter_revert(iter, count - iov_iter_count(iter)); 2991 2992 /* 2993 * Btrfs can have a short DIO read if we encounter 2994 * compressed extents, so if there was an error, or if 2995 * we've already read everything we wanted to, or if 2996 * there was a short read because we hit EOF, go ahead 2997 * and return. Otherwise fallthrough to buffered io for 2998 * the rest of the read. Buffered reads will not work for 2999 * DAX files, so don't bother trying. 3000 */ 3001 if (retval < 0 || !count || IS_DAX(inode)) 3002 return retval; 3003 if (iocb->ki_pos >= i_size_read(inode)) 3004 return retval; 3005 } 3006 3007 return filemap_read(iocb, iter, retval); 3008 } 3009 EXPORT_SYMBOL(generic_file_read_iter); 3010 3011 /* 3012 * Splice subpages from a folio into a pipe. 3013 */ 3014 size_t splice_folio_into_pipe(struct pipe_inode_info *pipe, 3015 struct folio *folio, loff_t fpos, size_t size) 3016 { 3017 struct page *page; 3018 size_t spliced = 0, offset = offset_in_folio(folio, fpos); 3019 3020 page = folio_page(folio, offset / PAGE_SIZE); 3021 size = min(size, folio_size(folio) - offset); 3022 offset %= PAGE_SIZE; 3023 3024 while (spliced < size && !pipe_is_full(pipe)) { 3025 struct pipe_buffer *buf = pipe_head_buf(pipe); 3026 size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced); 3027 3028 *buf = (struct pipe_buffer) { 3029 .ops = &page_cache_pipe_buf_ops, 3030 .page = page, 3031 .offset = offset, 3032 .len = part, 3033 }; 3034 folio_get(folio); 3035 pipe->head++; 3036 page++; 3037 spliced += part; 3038 offset = 0; 3039 } 3040 3041 return spliced; 3042 } 3043 3044 /** 3045 * filemap_splice_read - Splice data from a file's pagecache into a pipe 3046 * @in: The file to read from 3047 * @ppos: Pointer to the file position to read from 3048 * @pipe: The pipe to splice into 3049 * @len: The amount to splice 3050 * @flags: The SPLICE_F_* flags 3051 * 3052 * This function gets folios from a file's pagecache and splices them into the 3053 * pipe. Readahead will be called as necessary to fill more folios. This may 3054 * be used for blockdevs also. 3055 * 3056 * Return: On success, the number of bytes read will be returned and *@ppos 3057 * will be updated if appropriate; 0 will be returned if there is no more data 3058 * to be read; -EAGAIN will be returned if the pipe had no space, and some 3059 * other negative error code will be returned on error. A short read may occur 3060 * if the pipe has insufficient space, we reach the end of the data or we hit a 3061 * hole. 3062 */ 3063 ssize_t filemap_splice_read(struct file *in, loff_t *ppos, 3064 struct pipe_inode_info *pipe, 3065 size_t len, unsigned int flags) 3066 { 3067 struct folio_batch fbatch; 3068 struct kiocb iocb; 3069 size_t total_spliced = 0, used, npages; 3070 loff_t isize, end_offset; 3071 bool writably_mapped; 3072 int i, error = 0; 3073 3074 if (unlikely(*ppos >= in->f_mapping->host->i_sb->s_maxbytes)) 3075 return 0; 3076 3077 init_sync_kiocb(&iocb, in); 3078 iocb.ki_pos = *ppos; 3079 3080 /* Work out how much data we can actually add into the pipe */ 3081 used = pipe_buf_usage(pipe); 3082 npages = max_t(ssize_t, pipe->max_usage - used, 0); 3083 len = min_t(size_t, len, npages * PAGE_SIZE); 3084 3085 folio_batch_init(&fbatch); 3086 3087 do { 3088 cond_resched(); 3089 3090 if (*ppos >= i_size_read(in->f_mapping->host)) 3091 break; 3092 3093 iocb.ki_pos = *ppos; 3094 error = filemap_get_pages(&iocb, len, &fbatch, true); 3095 if (error < 0) 3096 break; 3097 3098 /* 3099 * i_size must be checked after we know the pages are Uptodate. 3100 * 3101 * Checking i_size after the check allows us to calculate 3102 * the correct value for "nr", which means the zero-filled 3103 * part of the page is not copied back to userspace (unless 3104 * another truncate extends the file - this is desired though). 3105 */ 3106 isize = i_size_read(in->f_mapping->host); 3107 if (unlikely(*ppos >= isize)) 3108 break; 3109 end_offset = min_t(loff_t, isize, *ppos + len); 3110 3111 /* 3112 * Once we start copying data, we don't want to be touching any 3113 * cachelines that might be contended: 3114 */ 3115 writably_mapped = mapping_writably_mapped(in->f_mapping); 3116 3117 for (i = 0; i < folio_batch_count(&fbatch); i++) { 3118 struct folio *folio = fbatch.folios[i]; 3119 size_t n; 3120 3121 if (folio_pos(folio) >= end_offset) 3122 goto out; 3123 folio_mark_accessed(folio); 3124 3125 /* 3126 * If users can be writing to this folio using arbitrary 3127 * virtual addresses, take care of potential aliasing 3128 * before reading the folio on the kernel side. 3129 */ 3130 if (writably_mapped) 3131 flush_dcache_folio(folio); 3132 3133 n = min_t(loff_t, len, isize - *ppos); 3134 n = splice_folio_into_pipe(pipe, folio, *ppos, n); 3135 if (!n) 3136 goto out; 3137 len -= n; 3138 total_spliced += n; 3139 *ppos += n; 3140 in->f_ra.prev_pos = *ppos; 3141 if (pipe_is_full(pipe)) 3142 goto out; 3143 } 3144 3145 folio_batch_release(&fbatch); 3146 } while (len); 3147 3148 out: 3149 folio_batch_release(&fbatch); 3150 file_accessed(in); 3151 3152 return total_spliced ? total_spliced : error; 3153 } 3154 EXPORT_SYMBOL(filemap_splice_read); 3155 3156 static inline loff_t folio_seek_hole_data(struct xa_state *xas, 3157 struct address_space *mapping, struct folio *folio, 3158 loff_t start, loff_t end, bool seek_data) 3159 { 3160 const struct address_space_operations *ops = mapping->a_ops; 3161 size_t offset, bsz = i_blocksize(mapping->host); 3162 3163 if (xa_is_value(folio) || folio_test_uptodate(folio)) 3164 return seek_data ? start : end; 3165 if (!ops->is_partially_uptodate) 3166 return seek_data ? end : start; 3167 3168 xas_pause(xas); 3169 rcu_read_unlock(); 3170 folio_lock(folio); 3171 if (unlikely(folio->mapping != mapping)) 3172 goto unlock; 3173 3174 offset = offset_in_folio(folio, start) & ~(bsz - 1); 3175 3176 do { 3177 if (ops->is_partially_uptodate(folio, offset, bsz) == 3178 seek_data) 3179 break; 3180 start = (start + bsz) & ~((u64)bsz - 1); 3181 offset += bsz; 3182 } while (offset < folio_size(folio)); 3183 unlock: 3184 folio_unlock(folio); 3185 rcu_read_lock(); 3186 return start; 3187 } 3188 3189 static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio) 3190 { 3191 if (xa_is_value(folio)) 3192 return PAGE_SIZE << xas_get_order(xas); 3193 return folio_size(folio); 3194 } 3195 3196 /** 3197 * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache. 3198 * @mapping: Address space to search. 3199 * @start: First byte to consider. 3200 * @end: Limit of search (exclusive). 3201 * @whence: Either SEEK_HOLE or SEEK_DATA. 3202 * 3203 * If the page cache knows which blocks contain holes and which blocks 3204 * contain data, your filesystem can use this function to implement 3205 * SEEK_HOLE and SEEK_DATA. This is useful for filesystems which are 3206 * entirely memory-based such as tmpfs, and filesystems which support 3207 * unwritten extents. 3208 * 3209 * Return: The requested offset on success, or -ENXIO if @whence specifies 3210 * SEEK_DATA and there is no data after @start. There is an implicit hole 3211 * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start 3212 * and @end contain data. 3213 */ 3214 loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start, 3215 loff_t end, int whence) 3216 { 3217 XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT); 3218 pgoff_t max = (end - 1) >> PAGE_SHIFT; 3219 bool seek_data = (whence == SEEK_DATA); 3220 struct folio *folio; 3221 3222 if (end <= start) 3223 return -ENXIO; 3224 3225 rcu_read_lock(); 3226 while ((folio = find_get_entry(&xas, max, XA_PRESENT))) { 3227 loff_t pos = (u64)xas.xa_index << PAGE_SHIFT; 3228 size_t seek_size; 3229 3230 if (start < pos) { 3231 if (!seek_data) 3232 goto unlock; 3233 start = pos; 3234 } 3235 3236 seek_size = seek_folio_size(&xas, folio); 3237 pos = round_up((u64)pos + 1, seek_size); 3238 start = folio_seek_hole_data(&xas, mapping, folio, start, pos, 3239 seek_data); 3240 if (start < pos) 3241 goto unlock; 3242 if (start >= end) 3243 break; 3244 if (seek_size > PAGE_SIZE) 3245 xas_set(&xas, pos >> PAGE_SHIFT); 3246 if (!xa_is_value(folio)) 3247 folio_put(folio); 3248 } 3249 if (seek_data) 3250 start = -ENXIO; 3251 unlock: 3252 rcu_read_unlock(); 3253 if (folio && !xa_is_value(folio)) 3254 folio_put(folio); 3255 if (start > end) 3256 return end; 3257 return start; 3258 } 3259 3260 #ifdef CONFIG_MMU 3261 #define MMAP_LOTSAMISS (100) 3262 /* 3263 * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock 3264 * @vmf - the vm_fault for this fault. 3265 * @folio - the folio to lock. 3266 * @fpin - the pointer to the file we may pin (or is already pinned). 3267 * 3268 * This works similar to lock_folio_or_retry in that it can drop the 3269 * mmap_lock. It differs in that it actually returns the folio locked 3270 * if it returns 1 and 0 if it couldn't lock the folio. If we did have 3271 * to drop the mmap_lock then fpin will point to the pinned file and 3272 * needs to be fput()'ed at a later point. 3273 */ 3274 static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio, 3275 struct file **fpin) 3276 { 3277 if (folio_trylock(folio)) 3278 return 1; 3279 3280 /* 3281 * NOTE! This will make us return with VM_FAULT_RETRY, but with 3282 * the fault lock still held. That's how FAULT_FLAG_RETRY_NOWAIT 3283 * is supposed to work. We have way too many special cases.. 3284 */ 3285 if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT) 3286 return 0; 3287 3288 *fpin = maybe_unlock_mmap_for_io(vmf, *fpin); 3289 if (vmf->flags & FAULT_FLAG_KILLABLE) { 3290 if (__folio_lock_killable(folio)) { 3291 /* 3292 * We didn't have the right flags to drop the 3293 * fault lock, but all fault_handlers only check 3294 * for fatal signals if we return VM_FAULT_RETRY, 3295 * so we need to drop the fault lock here and 3296 * return 0 if we don't have a fpin. 3297 */ 3298 if (*fpin == NULL) 3299 release_fault_lock(vmf); 3300 return 0; 3301 } 3302 } else 3303 __folio_lock(folio); 3304 3305 return 1; 3306 } 3307 3308 /* 3309 * Synchronous readahead happens when we don't even find a page in the page 3310 * cache at all. We don't want to perform IO under the mmap sem, so if we have 3311 * to drop the mmap sem we return the file that was pinned in order for us to do 3312 * that. If we didn't pin a file then we return NULL. The file that is 3313 * returned needs to be fput()'ed when we're done with it. 3314 */ 3315 static struct file *do_sync_mmap_readahead(struct vm_fault *vmf) 3316 { 3317 struct file *file = vmf->vma->vm_file; 3318 struct file_ra_state *ra = &file->f_ra; 3319 struct address_space *mapping = file->f_mapping; 3320 DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff); 3321 struct file *fpin = NULL; 3322 vm_flags_t vm_flags = vmf->vma->vm_flags; 3323 bool force_thp_readahead = false; 3324 unsigned int thp_order = 0; 3325 unsigned short mmap_miss; 3326 3327 ractl._max_index = vmf->vma->vm_pgoff + vma_pages(vmf->vma) - 1; 3328 3329 /* Use the readahead code, even if readahead is disabled */ 3330 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && (vm_flags & VM_HUGEPAGE)) { 3331 /* 3332 * Cap max THP order at 2MB: this is the common PMD-sized 3333 * hugepage size, and it avoids memory pressure from very 3334 * large forced readahead when mapping_max_folio_order() is 3335 * high (for example, 128MB with 64K base pages on arm64). 3336 */ 3337 if (mapping_large_folio_support(mapping)) { 3338 force_thp_readahead = true; 3339 thp_order = min_t(unsigned int, 3340 mapping_max_folio_order(mapping), 3341 get_order(SZ_2M)); 3342 } 3343 } 3344 3345 if (!force_thp_readahead) { 3346 /* 3347 * If we don't want any read-ahead, don't bother. 3348 * VM_EXEC case below is already intended for random access. 3349 */ 3350 if ((vm_flags & (VM_RAND_READ | VM_EXEC)) == VM_RAND_READ) 3351 return fpin; 3352 3353 if (!ra->ra_pages) 3354 return fpin; 3355 3356 if (vm_flags & VM_SEQ_READ) { 3357 fpin = maybe_unlock_mmap_for_io(vmf, fpin); 3358 page_cache_sync_ra(&ractl, ra->ra_pages); 3359 return fpin; 3360 } 3361 } 3362 3363 if (!(vm_flags & (VM_SEQ_READ | VM_EXEC))) { 3364 /* Avoid banging the cache line if not needed */ 3365 mmap_miss = READ_ONCE(ra->mmap_miss); 3366 if (mmap_miss < MMAP_LOTSAMISS * 10) 3367 WRITE_ONCE(ra->mmap_miss, ++mmap_miss); 3368 3369 /* 3370 * Do we miss much more than hit in this file? If so, 3371 * stop bothering with read-ahead. It will only hurt. 3372 */ 3373 if (mmap_miss > MMAP_LOTSAMISS) 3374 return fpin; 3375 } 3376 3377 if (force_thp_readahead) { 3378 unsigned long folio_nr_pages = 1UL << thp_order; 3379 3380 fpin = maybe_unlock_mmap_for_io(vmf, fpin); 3381 ractl._index &= ~(folio_nr_pages - 1); 3382 ra->size = folio_nr_pages; 3383 /* 3384 * Fetch two folios so we get the chance to actually 3385 * readahead, unless we've been told not to. 3386 */ 3387 if (!(vm_flags & VM_RAND_READ)) 3388 ra->size *= 2; 3389 ra->async_size = folio_nr_pages; 3390 ra->order = thp_order; 3391 page_cache_ra_order(&ractl, ra); 3392 return fpin; 3393 } 3394 3395 if (vm_flags & VM_EXEC) { 3396 /* 3397 * Allow arch to request a preferred minimum folio order for 3398 * executable memory. This can often be beneficial to 3399 * performance if (e.g.) arm64 can contpte-map the folio. 3400 * Executable memory rarely benefits from readahead, due to its 3401 * random access nature, so set async_size to 0. 3402 * 3403 * Limit to the boundaries of the VMA to avoid reading in any 3404 * pad that might exist between sections, which would be a waste 3405 * of memory. 3406 */ 3407 struct vm_area_struct *vma = vmf->vma; 3408 unsigned long start = vma->vm_pgoff; 3409 unsigned long end = start + vma_pages(vma); 3410 unsigned long ra_end; 3411 3412 ra->order = exec_folio_order(); 3413 ra->start = round_down(vmf->pgoff, 1UL << ra->order); 3414 ra->start = max(ra->start, start); 3415 ra_end = round_up(ra->start + ra->ra_pages, 1UL << ra->order); 3416 ra_end = min(ra_end, end); 3417 ra->size = ra_end - ra->start; 3418 ra->async_size = 0; 3419 } else { 3420 /* 3421 * mmap read-around 3422 */ 3423 ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2); 3424 ra->start = max(ra->start, vmf->vma->vm_pgoff); 3425 ra->size = ra->ra_pages; 3426 ra->async_size = ra->ra_pages / 4; 3427 ra->order = 0; 3428 } 3429 3430 fpin = maybe_unlock_mmap_for_io(vmf, fpin); 3431 ractl._index = ra->start; 3432 page_cache_ra_order(&ractl, ra); 3433 return fpin; 3434 } 3435 3436 /* 3437 * Asynchronous readahead happens when we find the page and PG_readahead, 3438 * so we want to possibly extend the readahead further. We return the file that 3439 * was pinned if we have to drop the mmap_lock in order to do IO. 3440 */ 3441 static struct file *do_async_mmap_readahead(struct vm_fault *vmf, 3442 struct folio *folio) 3443 { 3444 struct file *file = vmf->vma->vm_file; 3445 struct file_ra_state *ra = &file->f_ra; 3446 DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff); 3447 struct file *fpin = NULL; 3448 unsigned short mmap_miss; 3449 3450 /* If we don't want any read-ahead, don't bother */ 3451 if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages) 3452 return fpin; 3453 3454 /* 3455 * If the folio is locked, we're likely racing against another fault. 3456 * Don't touch the mmap_miss counter to avoid decreasing it multiple 3457 * times for a single folio and break the balance with mmap_miss 3458 * increase in do_sync_mmap_readahead(). 3459 * 3460 * VM_SEQ_READ and VM_EXEC mappings skip the mmap_miss increment in 3461 * do_sync_mmap_readahead(), so skip the decrement here as well to 3462 * keep the counter symmetric. 3463 */ 3464 if (likely(!folio_test_locked(folio)) && 3465 !(vmf->vma->vm_flags & (VM_SEQ_READ | VM_EXEC))) { 3466 mmap_miss = READ_ONCE(ra->mmap_miss); 3467 if (mmap_miss) 3468 WRITE_ONCE(ra->mmap_miss, --mmap_miss); 3469 } 3470 3471 if (folio_test_readahead(folio)) { 3472 ractl._max_index = vmf->vma->vm_pgoff + vma_pages(vmf->vma) - 1; 3473 fpin = maybe_unlock_mmap_for_io(vmf, fpin); 3474 page_cache_async_ra(&ractl, folio, ra->ra_pages); 3475 } 3476 return fpin; 3477 } 3478 3479 static vm_fault_t filemap_fault_recheck_pte_none(struct vm_fault *vmf) 3480 { 3481 struct vm_area_struct *vma = vmf->vma; 3482 vm_fault_t ret = 0; 3483 pte_t *ptep; 3484 3485 /* 3486 * We might have COW'ed a pagecache folio and might now have an mlocked 3487 * anon folio mapped. The original pagecache folio is not mlocked and 3488 * might have been evicted. During a read+clear/modify/write update of 3489 * the PTE, such as done in do_numa_page()/change_pte_range(), we 3490 * temporarily clear the PTE under PT lock and might detect it here as 3491 * "none" when not holding the PT lock. 3492 * 3493 * Not rechecking the PTE under PT lock could result in an unexpected 3494 * major fault in an mlock'ed region. Recheck only for this special 3495 * scenario while holding the PT lock, to not degrade non-mlocked 3496 * scenarios. Recheck the PTE without PT lock firstly, thereby reducing 3497 * the number of times we hold PT lock. 3498 */ 3499 if (!(vma->vm_flags & VM_LOCKED)) 3500 return 0; 3501 3502 if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)) 3503 return 0; 3504 3505 ptep = pte_offset_map_ro_nolock(vma->vm_mm, vmf->pmd, vmf->address, 3506 &vmf->ptl); 3507 if (unlikely(!ptep)) 3508 return VM_FAULT_NOPAGE; 3509 3510 if (unlikely(!pte_none(ptep_get_lockless(ptep)))) { 3511 ret = VM_FAULT_NOPAGE; 3512 } else { 3513 spin_lock(vmf->ptl); 3514 if (unlikely(!pte_none(ptep_get(ptep)))) 3515 ret = VM_FAULT_NOPAGE; 3516 spin_unlock(vmf->ptl); 3517 } 3518 pte_unmap(ptep); 3519 return ret; 3520 } 3521 3522 /** 3523 * filemap_fault - read in file data for page fault handling 3524 * @vmf: struct vm_fault containing details of the fault 3525 * 3526 * filemap_fault() is invoked via the vma operations vector for a 3527 * mapped memory region to read in file data during a page fault. 3528 * 3529 * The goto's are kind of ugly, but this streamlines the normal case of having 3530 * it in the page cache, and handles the special cases reasonably without 3531 * having a lot of duplicated code. 3532 * 3533 * vma->vm_mm->mmap_lock must be held on entry. 3534 * 3535 * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock 3536 * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap(). 3537 * 3538 * If our return value does not have VM_FAULT_RETRY set, the mmap_lock 3539 * has not been released. 3540 * 3541 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set. 3542 * 3543 * Return: bitwise-OR of %VM_FAULT_ codes. 3544 */ 3545 vm_fault_t filemap_fault(struct vm_fault *vmf) 3546 { 3547 int error; 3548 struct file *file = vmf->vma->vm_file; 3549 struct file *fpin = NULL; 3550 struct address_space *mapping = file->f_mapping; 3551 struct inode *inode = mapping->host; 3552 pgoff_t max_idx, index = vmf->pgoff; 3553 struct folio *folio; 3554 vm_fault_t ret = 0; 3555 bool mapping_locked = false; 3556 3557 max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE); 3558 if (unlikely(index >= max_idx)) 3559 return VM_FAULT_SIGBUS; 3560 3561 trace_mm_filemap_fault(mapping, index); 3562 3563 /* 3564 * Do we have something in the page cache already? 3565 */ 3566 folio = filemap_get_folio(mapping, index); 3567 if (likely(!IS_ERR(folio))) { 3568 /* 3569 * We found the page, so try async readahead before waiting for 3570 * the lock. 3571 */ 3572 if (!(vmf->flags & FAULT_FLAG_TRIED)) 3573 fpin = do_async_mmap_readahead(vmf, folio); 3574 if (unlikely(!folio_test_uptodate(folio))) { 3575 filemap_invalidate_lock_shared(mapping); 3576 mapping_locked = true; 3577 } 3578 } else { 3579 ret = filemap_fault_recheck_pte_none(vmf); 3580 if (unlikely(ret)) 3581 return ret; 3582 3583 /* No page in the page cache at all */ 3584 count_vm_event(PGMAJFAULT); 3585 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT); 3586 ret = VM_FAULT_MAJOR; 3587 fpin = do_sync_mmap_readahead(vmf); 3588 retry_find: 3589 /* 3590 * See comment in filemap_create_folio() why we need 3591 * invalidate_lock 3592 */ 3593 if (!mapping_locked) { 3594 filemap_invalidate_lock_shared(mapping); 3595 mapping_locked = true; 3596 } 3597 folio = __filemap_get_folio(mapping, index, 3598 FGP_CREAT|FGP_FOR_MMAP, 3599 vmf->gfp_mask); 3600 if (IS_ERR(folio)) { 3601 if (fpin) 3602 goto out_retry; 3603 filemap_invalidate_unlock_shared(mapping); 3604 return VM_FAULT_OOM; 3605 } 3606 } 3607 3608 if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin)) 3609 goto out_retry; 3610 3611 /* Did it get truncated? */ 3612 if (unlikely(folio->mapping != mapping)) { 3613 folio_unlock(folio); 3614 folio_put(folio); 3615 goto retry_find; 3616 } 3617 VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio); 3618 3619 /* 3620 * We have a locked folio in the page cache, now we need to check 3621 * that it's up-to-date. If not, it is going to be due to an error, 3622 * or because readahead was otherwise unable to retrieve it. 3623 */ 3624 if (unlikely(!folio_test_uptodate(folio))) { 3625 /* 3626 * If the invalidate lock is not held, the folio was in cache 3627 * and uptodate and now it is not. Strange but possible since we 3628 * didn't hold the page lock all the time. Let's drop 3629 * everything, get the invalidate lock and try again. 3630 */ 3631 if (!mapping_locked) { 3632 folio_unlock(folio); 3633 folio_put(folio); 3634 goto retry_find; 3635 } 3636 3637 /* 3638 * OK, the folio is really not uptodate. This can be because the 3639 * VMA has the VM_RAND_READ flag set, or because an error 3640 * arose. Let's read it in directly. 3641 */ 3642 goto page_not_uptodate; 3643 } 3644 3645 /* 3646 * We've made it this far and we had to drop our mmap_lock, now is the 3647 * time to return to the upper layer and have it re-find the vma and 3648 * redo the fault. 3649 */ 3650 if (fpin) { 3651 folio_unlock(folio); 3652 goto out_retry; 3653 } 3654 if (mapping_locked) 3655 filemap_invalidate_unlock_shared(mapping); 3656 3657 /* 3658 * Found the page and have a reference on it. 3659 * We must recheck i_size under page lock. 3660 */ 3661 max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE); 3662 if (unlikely(index >= max_idx)) { 3663 folio_unlock(folio); 3664 folio_put(folio); 3665 return VM_FAULT_SIGBUS; 3666 } 3667 3668 vmf->page = folio_file_page(folio, index); 3669 return ret | VM_FAULT_LOCKED; 3670 3671 page_not_uptodate: 3672 /* 3673 * Umm, take care of errors if the page isn't up-to-date. 3674 * Try to re-read it _once_. We do this synchronously, 3675 * because there really aren't any performance issues here 3676 * and we need to check for errors. 3677 */ 3678 fpin = maybe_unlock_mmap_for_io(vmf, fpin); 3679 error = filemap_read_folio(file, mapping->a_ops->read_folio, folio); 3680 if (fpin) 3681 goto out_retry; 3682 folio_put(folio); 3683 3684 if (!error || error == AOP_TRUNCATED_PAGE) 3685 goto retry_find; 3686 filemap_invalidate_unlock_shared(mapping); 3687 3688 return VM_FAULT_SIGBUS; 3689 3690 out_retry: 3691 /* 3692 * We dropped the mmap_lock, we need to return to the fault handler to 3693 * re-find the vma and come back and find our hopefully still populated 3694 * page. 3695 */ 3696 if (!IS_ERR(folio)) 3697 folio_put(folio); 3698 if (mapping_locked) 3699 filemap_invalidate_unlock_shared(mapping); 3700 if (fpin) 3701 fput(fpin); 3702 return ret | VM_FAULT_RETRY; 3703 } 3704 EXPORT_SYMBOL(filemap_fault); 3705 3706 static bool filemap_map_pmd(struct vm_fault *vmf, struct folio *folio, 3707 pgoff_t start) 3708 { 3709 struct mm_struct *mm = vmf->vma->vm_mm; 3710 3711 /* Huge page is mapped? No need to proceed. */ 3712 if (pmd_trans_huge(*vmf->pmd)) { 3713 folio_unlock(folio); 3714 folio_put(folio); 3715 return true; 3716 } 3717 3718 if (pmd_none(*vmf->pmd) && folio_test_pmd_mappable(folio)) { 3719 struct page *page = folio_file_page(folio, start); 3720 vm_fault_t ret = do_set_pmd(vmf, folio, page); 3721 if (!ret) { 3722 /* The page is mapped successfully, reference consumed. */ 3723 folio_unlock(folio); 3724 return true; 3725 } 3726 } 3727 3728 if (pmd_none(*vmf->pmd) && vmf->prealloc_pte) 3729 pmd_install(mm, vmf->pmd, &vmf->prealloc_pte); 3730 3731 return false; 3732 } 3733 3734 static struct folio *next_uptodate_folio(struct xa_state *xas, 3735 struct address_space *mapping, pgoff_t end_pgoff) 3736 { 3737 struct folio *folio = xas_next_entry(xas, end_pgoff); 3738 unsigned long max_idx; 3739 3740 do { 3741 if (!folio) 3742 return NULL; 3743 if (xas_retry(xas, folio)) 3744 continue; 3745 if (xa_is_value(folio)) 3746 continue; 3747 if (!folio_try_get(folio)) 3748 continue; 3749 if (folio_test_locked(folio)) 3750 goto skip; 3751 /* Has the page moved or been split? */ 3752 if (unlikely(folio != xas_reload(xas))) 3753 goto skip; 3754 if (!folio_test_uptodate(folio) || folio_test_readahead(folio)) 3755 goto skip; 3756 if (!folio_trylock(folio)) 3757 goto skip; 3758 if (folio->mapping != mapping) 3759 goto unlock; 3760 if (!folio_test_uptodate(folio)) 3761 goto unlock; 3762 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE); 3763 if (xas->xa_index >= max_idx) 3764 goto unlock; 3765 return folio; 3766 unlock: 3767 folio_unlock(folio); 3768 skip: 3769 folio_put(folio); 3770 } while ((folio = xas_next_entry(xas, end_pgoff)) != NULL); 3771 3772 return NULL; 3773 } 3774 3775 /* 3776 * Map page range [start_page, start_page + nr_pages) of folio. 3777 * start_page is gotten from start by folio_page(folio, start) 3778 */ 3779 static vm_fault_t filemap_map_folio_range(struct vm_fault *vmf, 3780 struct folio *folio, unsigned long start, 3781 unsigned long addr, unsigned int nr_pages, 3782 unsigned long *rss, pgoff_t file_end) 3783 { 3784 struct address_space *mapping = folio->mapping; 3785 unsigned int ref_from_caller = 1; 3786 vm_fault_t ret = 0; 3787 struct page *page = folio_page(folio, start); 3788 unsigned int count = 0; 3789 pte_t *old_ptep = vmf->pte; 3790 unsigned long addr0; 3791 3792 /* 3793 * Map the large folio fully where possible: 3794 * 3795 * - The folio is fully within size of the file or belong 3796 * to shmem/tmpfs; 3797 * - The folio doesn't cross VMA boundary; 3798 * - The folio doesn't cross page table boundary; 3799 */ 3800 addr0 = addr - start * PAGE_SIZE; 3801 if ((file_end >= folio_next_index(folio) || shmem_mapping(mapping)) && 3802 folio_within_vma(folio, vmf->vma) && 3803 (addr0 & PMD_MASK) == ((addr0 + folio_size(folio) - 1) & PMD_MASK)) { 3804 vmf->pte -= start; 3805 page -= start; 3806 addr = addr0; 3807 nr_pages = folio_nr_pages(folio); 3808 } 3809 3810 do { 3811 if (PageHWPoison(page + count)) 3812 goto skip; 3813 3814 /* 3815 * NOTE: If there're PTE markers, we'll leave them to be 3816 * handled in the specific fault path, and it'll prohibit the 3817 * fault-around logic. 3818 */ 3819 if (!pte_none(ptep_get(&vmf->pte[count]))) 3820 goto skip; 3821 3822 count++; 3823 continue; 3824 skip: 3825 if (count) { 3826 set_pte_range(vmf, folio, page, count, addr); 3827 *rss += count; 3828 folio_ref_add(folio, count - ref_from_caller); 3829 ref_from_caller = 0; 3830 if (in_range(vmf->address, addr, count * PAGE_SIZE)) 3831 ret = VM_FAULT_NOPAGE; 3832 } 3833 3834 count++; 3835 page += count; 3836 vmf->pte += count; 3837 addr += count * PAGE_SIZE; 3838 count = 0; 3839 } while (--nr_pages > 0); 3840 3841 if (count) { 3842 set_pte_range(vmf, folio, page, count, addr); 3843 *rss += count; 3844 folio_ref_add(folio, count - ref_from_caller); 3845 ref_from_caller = 0; 3846 if (in_range(vmf->address, addr, count * PAGE_SIZE)) 3847 ret = VM_FAULT_NOPAGE; 3848 } 3849 3850 vmf->pte = old_ptep; 3851 if (ref_from_caller) 3852 /* Locked folios cannot get truncated. */ 3853 folio_ref_dec(folio); 3854 3855 return ret; 3856 } 3857 3858 static vm_fault_t filemap_map_order0_folio(struct vm_fault *vmf, 3859 struct folio *folio, unsigned long addr, 3860 unsigned long *rss) 3861 { 3862 vm_fault_t ret = 0; 3863 struct page *page = &folio->page; 3864 3865 if (PageHWPoison(page)) 3866 goto out; 3867 3868 /* 3869 * NOTE: If there're PTE markers, we'll leave them to be 3870 * handled in the specific fault path, and it'll prohibit 3871 * the fault-around logic. 3872 */ 3873 if (!pte_none(ptep_get(vmf->pte))) 3874 goto out; 3875 3876 if (vmf->address == addr) 3877 ret = VM_FAULT_NOPAGE; 3878 3879 set_pte_range(vmf, folio, page, 1, addr); 3880 (*rss)++; 3881 return ret; 3882 3883 out: 3884 /* Locked folios cannot get truncated. */ 3885 folio_ref_dec(folio); 3886 return ret; 3887 } 3888 3889 vm_fault_t filemap_map_pages(struct vm_fault *vmf, 3890 pgoff_t start_pgoff, pgoff_t end_pgoff) 3891 { 3892 struct vm_area_struct *vma = vmf->vma; 3893 struct file *file = vma->vm_file; 3894 struct address_space *mapping = file->f_mapping; 3895 pgoff_t file_end, last_pgoff = start_pgoff; 3896 unsigned long addr; 3897 XA_STATE(xas, &mapping->i_pages, start_pgoff); 3898 struct folio *folio; 3899 vm_fault_t ret = 0; 3900 unsigned long rss = 0; 3901 unsigned int nr_pages = 0, folio_type; 3902 3903 /* 3904 * Recalculate end_pgoff based on file_end before calling 3905 * next_uptodate_folio() to avoid races with concurrent 3906 * truncation. 3907 */ 3908 file_end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE) - 1; 3909 end_pgoff = min(end_pgoff, file_end); 3910 3911 rcu_read_lock(); 3912 folio = next_uptodate_folio(&xas, mapping, end_pgoff); 3913 if (!folio) 3914 goto out; 3915 3916 /* 3917 * Do not allow to map with PMD across i_size to preserve 3918 * SIGBUS semantics. 3919 * 3920 * Make an exception for shmem/tmpfs that for long time 3921 * intentionally mapped with PMDs across i_size. 3922 */ 3923 if ((file_end >= folio_next_index(folio) || shmem_mapping(mapping)) && 3924 filemap_map_pmd(vmf, folio, start_pgoff)) { 3925 ret = VM_FAULT_NOPAGE; 3926 goto out; 3927 } 3928 3929 addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT); 3930 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl); 3931 if (!vmf->pte) { 3932 folio_unlock(folio); 3933 folio_put(folio); 3934 goto out; 3935 } 3936 3937 folio_type = mm_counter_file(folio); 3938 do { 3939 unsigned long end; 3940 vm_fault_t map_ret; 3941 3942 addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT; 3943 vmf->pte += xas.xa_index - last_pgoff; 3944 last_pgoff = xas.xa_index; 3945 end = folio_next_index(folio) - 1; 3946 nr_pages = min(end, end_pgoff) - xas.xa_index + 1; 3947 3948 if (!folio_test_large(folio)) { 3949 map_ret = filemap_map_order0_folio(vmf, folio, addr, 3950 &rss); 3951 } else { 3952 unsigned long start = xas.xa_index - folio->index; 3953 3954 map_ret = filemap_map_folio_range(vmf, folio, start, 3955 addr, nr_pages, &rss, 3956 file_end); 3957 } 3958 ret |= map_ret; 3959 3960 /* 3961 * If there are too many folios that are recently evicted 3962 * in a file, they will probably continue to be evicted. 3963 * In such situation, read-ahead is only a waste of IO. 3964 * Don't decrease mmap_miss in this scenario to make sure 3965 * we can stop read-ahead. 3966 * 3967 * VM_SEQ_READ and VM_EXEC mappings skip the mmap_miss 3968 * increment in do_sync_mmap_readahead(), so skip the 3969 * decrement here as well to keep the counter symmetric. 3970 */ 3971 if ((map_ret & VM_FAULT_NOPAGE) && 3972 !(vmf->flags & FAULT_FLAG_TRIED) && 3973 !folio_test_workingset(folio) && 3974 !(vma->vm_flags & (VM_SEQ_READ | VM_EXEC))) { 3975 unsigned short mmap_miss; 3976 3977 mmap_miss = READ_ONCE(file->f_ra.mmap_miss); 3978 if (mmap_miss) 3979 WRITE_ONCE(file->f_ra.mmap_miss, 3980 mmap_miss - 1); 3981 } 3982 3983 folio_unlock(folio); 3984 } while ((folio = next_uptodate_folio(&xas, mapping, end_pgoff)) != NULL); 3985 add_mm_counter(vma->vm_mm, folio_type, rss); 3986 pte_unmap_unlock(vmf->pte, vmf->ptl); 3987 trace_mm_filemap_map_pages(mapping, start_pgoff, end_pgoff); 3988 out: 3989 rcu_read_unlock(); 3990 3991 return ret; 3992 } 3993 EXPORT_SYMBOL(filemap_map_pages); 3994 3995 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf) 3996 { 3997 struct address_space *mapping = vmf->vma->vm_file->f_mapping; 3998 struct folio *folio = page_folio(vmf->page); 3999 vm_fault_t ret = VM_FAULT_LOCKED; 4000 4001 sb_start_pagefault(mapping->host->i_sb); 4002 file_update_time(vmf->vma->vm_file); 4003 folio_lock(folio); 4004 if (folio->mapping != mapping) { 4005 folio_unlock(folio); 4006 ret = VM_FAULT_NOPAGE; 4007 goto out; 4008 } 4009 /* 4010 * We mark the folio dirty already here so that when freeze is in 4011 * progress, we are guaranteed that writeback during freezing will 4012 * see the dirty folio and writeprotect it again. 4013 */ 4014 folio_mark_dirty(folio); 4015 folio_wait_stable(folio); 4016 out: 4017 sb_end_pagefault(mapping->host->i_sb); 4018 return ret; 4019 } 4020 4021 const struct vm_operations_struct generic_file_vm_ops = { 4022 .fault = filemap_fault, 4023 .map_pages = filemap_map_pages, 4024 .page_mkwrite = filemap_page_mkwrite, 4025 }; 4026 4027 /* This is used for a general mmap of a disk file */ 4028 4029 int generic_file_mmap(struct file *file, struct vm_area_struct *vma) 4030 { 4031 struct address_space *mapping = file->f_mapping; 4032 4033 if (!mapping->a_ops->read_folio) 4034 return -ENOEXEC; 4035 file_accessed(file); 4036 vma->vm_ops = &generic_file_vm_ops; 4037 return 0; 4038 } 4039 4040 int generic_file_mmap_prepare(struct vm_area_desc *desc) 4041 { 4042 struct file *file = desc->file; 4043 struct address_space *mapping = file->f_mapping; 4044 4045 if (!mapping->a_ops->read_folio) 4046 return -ENOEXEC; 4047 file_accessed(file); 4048 desc->vm_ops = &generic_file_vm_ops; 4049 return 0; 4050 } 4051 4052 /* 4053 * This is for filesystems which do not implement ->writepage. 4054 */ 4055 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma) 4056 { 4057 if (vma_is_shared_maywrite(vma)) 4058 return -EINVAL; 4059 return generic_file_mmap(file, vma); 4060 } 4061 4062 int generic_file_readonly_mmap_prepare(struct vm_area_desc *desc) 4063 { 4064 if (is_shared_maywrite(&desc->vma_flags)) 4065 return -EINVAL; 4066 return generic_file_mmap_prepare(desc); 4067 } 4068 #else 4069 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf) 4070 { 4071 return VM_FAULT_SIGBUS; 4072 } 4073 int generic_file_mmap(struct file *file, struct vm_area_struct *vma) 4074 { 4075 return -ENOSYS; 4076 } 4077 int generic_file_mmap_prepare(struct vm_area_desc *desc) 4078 { 4079 return -ENOSYS; 4080 } 4081 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma) 4082 { 4083 return -ENOSYS; 4084 } 4085 int generic_file_readonly_mmap_prepare(struct vm_area_desc *desc) 4086 { 4087 return -ENOSYS; 4088 } 4089 #endif /* CONFIG_MMU */ 4090 4091 EXPORT_SYMBOL(filemap_page_mkwrite); 4092 EXPORT_SYMBOL(generic_file_mmap); 4093 EXPORT_SYMBOL(generic_file_mmap_prepare); 4094 EXPORT_SYMBOL(generic_file_readonly_mmap); 4095 EXPORT_SYMBOL(generic_file_readonly_mmap_prepare); 4096 4097 static struct folio *do_read_cache_folio(struct address_space *mapping, 4098 pgoff_t index, filler_t filler, struct file *file, gfp_t gfp) 4099 { 4100 struct folio *folio; 4101 int err; 4102 4103 if (!filler) 4104 filler = mapping->a_ops->read_folio; 4105 repeat: 4106 folio = filemap_get_folio(mapping, index); 4107 if (IS_ERR(folio)) { 4108 folio = filemap_alloc_folio(gfp, mapping_min_folio_order(mapping), NULL); 4109 if (!folio) 4110 return ERR_PTR(-ENOMEM); 4111 index = mapping_align_index(mapping, index); 4112 err = filemap_add_folio(mapping, folio, index, gfp); 4113 if (unlikely(err)) { 4114 folio_put(folio); 4115 if (err == -EEXIST) 4116 goto repeat; 4117 /* Presumably ENOMEM for xarray node */ 4118 return ERR_PTR(err); 4119 } 4120 4121 goto filler; 4122 } 4123 if (folio_test_uptodate(folio)) 4124 goto out; 4125 4126 if (!folio_trylock(folio)) { 4127 folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE); 4128 goto repeat; 4129 } 4130 4131 /* Folio was truncated from mapping */ 4132 if (!folio->mapping) { 4133 folio_unlock(folio); 4134 folio_put(folio); 4135 goto repeat; 4136 } 4137 4138 /* Someone else locked and filled the page in a very small window */ 4139 if (folio_test_uptodate(folio)) { 4140 folio_unlock(folio); 4141 goto out; 4142 } 4143 4144 filler: 4145 err = filemap_read_folio(file, filler, folio); 4146 if (err) { 4147 folio_put(folio); 4148 if (err == AOP_TRUNCATED_PAGE) 4149 goto repeat; 4150 return ERR_PTR(err); 4151 } 4152 4153 out: 4154 folio_mark_accessed(folio); 4155 return folio; 4156 } 4157 4158 /** 4159 * read_cache_folio - Read into page cache, fill it if needed. 4160 * @mapping: The address_space to read from. 4161 * @index: The index to read. 4162 * @filler: Function to perform the read, or NULL to use aops->read_folio(). 4163 * @file: Passed to filler function, may be NULL if not required. 4164 * 4165 * Read one page into the page cache. If it succeeds, the folio returned 4166 * will contain @index, but it may not be the first page of the folio. 4167 * 4168 * If the filler function returns an error, it will be returned to the 4169 * caller. 4170 * 4171 * Context: May sleep. Expects mapping->invalidate_lock to be held. 4172 * Return: An uptodate folio on success, ERR_PTR() on failure. 4173 */ 4174 struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index, 4175 filler_t filler, struct file *file) 4176 { 4177 return do_read_cache_folio(mapping, index, filler, file, 4178 mapping_gfp_mask(mapping)); 4179 } 4180 EXPORT_SYMBOL(read_cache_folio); 4181 4182 /** 4183 * mapping_read_folio_gfp - Read into page cache, using specified allocation flags. 4184 * @mapping: The address_space for the folio. 4185 * @index: The index that the allocated folio will contain. 4186 * @gfp: The page allocator flags to use if allocating. 4187 * 4188 * This is the same as "read_cache_folio(mapping, index, NULL, NULL)", but with 4189 * any new memory allocations done using the specified allocation flags. 4190 * 4191 * The most likely error from this function is EIO, but ENOMEM is 4192 * possible and so is EINTR. If ->read_folio returns another error, 4193 * that will be returned to the caller. 4194 * 4195 * The function expects mapping->invalidate_lock to be already held. 4196 * 4197 * Return: Uptodate folio on success, ERR_PTR() on failure. 4198 */ 4199 struct folio *mapping_read_folio_gfp(struct address_space *mapping, 4200 pgoff_t index, gfp_t gfp) 4201 { 4202 return do_read_cache_folio(mapping, index, NULL, NULL, gfp); 4203 } 4204 EXPORT_SYMBOL(mapping_read_folio_gfp); 4205 4206 static struct page *do_read_cache_page(struct address_space *mapping, 4207 pgoff_t index, filler_t *filler, struct file *file, gfp_t gfp) 4208 { 4209 struct folio *folio; 4210 4211 folio = do_read_cache_folio(mapping, index, filler, file, gfp); 4212 if (IS_ERR(folio)) 4213 return &folio->page; 4214 return folio_file_page(folio, index); 4215 } 4216 4217 struct page *read_cache_page(struct address_space *mapping, 4218 pgoff_t index, filler_t *filler, struct file *file) 4219 { 4220 return do_read_cache_page(mapping, index, filler, file, 4221 mapping_gfp_mask(mapping)); 4222 } 4223 EXPORT_SYMBOL(read_cache_page); 4224 4225 /** 4226 * read_cache_page_gfp - read into page cache, using specified page allocation flags. 4227 * @mapping: the page's address_space 4228 * @index: the page index 4229 * @gfp: the page allocator flags to use if allocating 4230 * 4231 * This is the same as "read_mapping_page(mapping, index, NULL)", but with 4232 * any new page allocations done using the specified allocation flags. 4233 * 4234 * If the page does not get brought uptodate, return -EIO. 4235 * 4236 * The function expects mapping->invalidate_lock to be already held. 4237 * 4238 * Return: up to date page on success, ERR_PTR() on failure. 4239 */ 4240 struct page *read_cache_page_gfp(struct address_space *mapping, 4241 pgoff_t index, 4242 gfp_t gfp) 4243 { 4244 return do_read_cache_page(mapping, index, NULL, NULL, gfp); 4245 } 4246 EXPORT_SYMBOL(read_cache_page_gfp); 4247 4248 /* 4249 * Warn about a page cache invalidation failure during a direct I/O write. 4250 */ 4251 static void dio_warn_stale_pagecache(struct file *filp) 4252 { 4253 static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST); 4254 char pathname[128]; 4255 char *path; 4256 4257 errseq_set(&filp->f_mapping->wb_err, -EIO); 4258 if (__ratelimit(&_rs)) { 4259 path = file_path(filp, pathname, sizeof(pathname)); 4260 if (IS_ERR(path)) 4261 path = "(unknown)"; 4262 pr_crit("Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!\n"); 4263 pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid, 4264 current->comm); 4265 } 4266 } 4267 4268 void kiocb_invalidate_post_direct_write(struct kiocb *iocb, size_t count) 4269 { 4270 struct address_space *mapping = iocb->ki_filp->f_mapping; 4271 4272 if (mapping->nrpages && 4273 invalidate_inode_pages2_range(mapping, 4274 iocb->ki_pos >> PAGE_SHIFT, 4275 (iocb->ki_pos + count - 1) >> PAGE_SHIFT)) 4276 dio_warn_stale_pagecache(iocb->ki_filp); 4277 } 4278 4279 ssize_t 4280 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from) 4281 { 4282 struct address_space *mapping = iocb->ki_filp->f_mapping; 4283 size_t write_len = iov_iter_count(from); 4284 ssize_t written; 4285 4286 /* 4287 * If a page can not be invalidated, return 0 to fall back 4288 * to buffered write. 4289 */ 4290 written = kiocb_invalidate_pages(iocb, write_len); 4291 if (written) { 4292 if (written == -EBUSY) 4293 return 0; 4294 return written; 4295 } 4296 4297 written = mapping->a_ops->direct_IO(iocb, from); 4298 4299 /* 4300 * Finally, try again to invalidate clean pages which might have been 4301 * cached by non-direct readahead, or faulted in by get_user_pages() 4302 * if the source of the write was an mmap'ed region of the file 4303 * we're writing. Either one is a pretty crazy thing to do, 4304 * so we don't support it 100%. If this invalidation 4305 * fails, tough, the write still worked... 4306 * 4307 * Most of the time we do not need this since dio_complete() will do 4308 * the invalidation for us. However there are some file systems that 4309 * do not end up with dio_complete() being called, so let's not break 4310 * them by removing it completely. 4311 * 4312 * Noticeable example is a blkdev_direct_IO(). 4313 * 4314 * Skip invalidation for async writes or if mapping has no pages. 4315 */ 4316 if (written > 0) { 4317 struct inode *inode = mapping->host; 4318 loff_t pos = iocb->ki_pos; 4319 4320 kiocb_invalidate_post_direct_write(iocb, written); 4321 pos += written; 4322 write_len -= written; 4323 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) { 4324 i_size_write(inode, pos); 4325 mark_inode_dirty(inode); 4326 } 4327 iocb->ki_pos = pos; 4328 } 4329 if (written != -EIOCBQUEUED) 4330 iov_iter_revert(from, write_len - iov_iter_count(from)); 4331 return written; 4332 } 4333 EXPORT_SYMBOL(generic_file_direct_write); 4334 4335 ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i) 4336 { 4337 struct file *file = iocb->ki_filp; 4338 loff_t pos = iocb->ki_pos; 4339 struct address_space *mapping = file->f_mapping; 4340 const struct address_space_operations *a_ops = mapping->a_ops; 4341 size_t chunk = mapping_max_folio_size(mapping); 4342 long status = 0; 4343 ssize_t written = 0; 4344 4345 do { 4346 struct folio *folio; 4347 size_t offset; /* Offset into folio */ 4348 size_t bytes; /* Bytes to write to folio */ 4349 size_t copied; /* Bytes copied from user */ 4350 void *fsdata = NULL; 4351 4352 bytes = iov_iter_count(i); 4353 retry: 4354 offset = pos & (chunk - 1); 4355 bytes = min(chunk - offset, bytes); 4356 balance_dirty_pages_ratelimited(mapping); 4357 4358 if (fatal_signal_pending(current)) { 4359 status = -EINTR; 4360 break; 4361 } 4362 4363 status = a_ops->write_begin(iocb, mapping, pos, bytes, 4364 &folio, &fsdata); 4365 if (unlikely(status < 0)) 4366 break; 4367 4368 offset = offset_in_folio(folio, pos); 4369 if (bytes > folio_size(folio) - offset) 4370 bytes = folio_size(folio) - offset; 4371 4372 if (mapping_writably_mapped(mapping)) 4373 flush_dcache_folio(folio); 4374 4375 /* 4376 * Faults here on mmap()s can recurse into arbitrary 4377 * filesystem code. Lots of locks are held that can 4378 * deadlock. Use an atomic copy to avoid deadlocking 4379 * in page fault handling. 4380 */ 4381 copied = copy_folio_from_iter_atomic(folio, offset, bytes, i); 4382 flush_dcache_folio(folio); 4383 4384 status = a_ops->write_end(iocb, mapping, pos, bytes, copied, 4385 folio, fsdata); 4386 if (unlikely(status != copied)) { 4387 iov_iter_revert(i, copied - max(status, 0L)); 4388 if (unlikely(status < 0)) 4389 break; 4390 } 4391 cond_resched(); 4392 4393 if (unlikely(status == 0)) { 4394 /* 4395 * A short copy made ->write_end() reject the 4396 * thing entirely. Might be memory poisoning 4397 * halfway through, might be a race with munmap, 4398 * might be severe memory pressure. 4399 */ 4400 if (chunk > PAGE_SIZE) 4401 chunk /= 2; 4402 if (copied) { 4403 bytes = copied; 4404 goto retry; 4405 } 4406 4407 /* 4408 * 'folio' is now unlocked and faults on it can be 4409 * handled. Ensure forward progress by trying to 4410 * fault it in now. 4411 */ 4412 if (fault_in_iov_iter_readable(i, bytes) == bytes) { 4413 status = -EFAULT; 4414 break; 4415 } 4416 } else { 4417 pos += status; 4418 written += status; 4419 } 4420 } while (iov_iter_count(i)); 4421 4422 if (!written) 4423 return status; 4424 iocb->ki_pos += written; 4425 return written; 4426 } 4427 EXPORT_SYMBOL(generic_perform_write); 4428 4429 /** 4430 * __generic_file_write_iter - write data to a file 4431 * @iocb: IO state structure (file, offset, etc.) 4432 * @from: iov_iter with data to write 4433 * 4434 * This function does all the work needed for actually writing data to a 4435 * file. It does all basic checks, removes SUID from the file, updates 4436 * modification times and calls proper subroutines depending on whether we 4437 * do direct IO or a standard buffered write. 4438 * 4439 * It expects i_rwsem to be grabbed unless we work on a block device or similar 4440 * object which does not need locking at all. 4441 * 4442 * This function does *not* take care of syncing data in case of O_SYNC write. 4443 * A caller has to handle it. This is mainly due to the fact that we want to 4444 * avoid syncing under i_rwsem. 4445 * 4446 * Return: 4447 * * number of bytes written, even for truncated writes 4448 * * negative error code if no data has been written at all 4449 */ 4450 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from) 4451 { 4452 struct file *file = iocb->ki_filp; 4453 struct address_space *mapping = file->f_mapping; 4454 struct inode *inode = mapping->host; 4455 ssize_t ret; 4456 4457 ret = file_remove_privs(file); 4458 if (ret) 4459 return ret; 4460 4461 ret = file_update_time(file); 4462 if (ret) 4463 return ret; 4464 4465 if (iocb->ki_flags & IOCB_DIRECT) { 4466 ret = generic_file_direct_write(iocb, from); 4467 /* 4468 * If the write stopped short of completing, fall back to 4469 * buffered writes. Some filesystems do this for writes to 4470 * holes, for example. For DAX files, a buffered write will 4471 * not succeed (even if it did, DAX does not handle dirty 4472 * page-cache pages correctly). 4473 */ 4474 if (ret < 0 || !iov_iter_count(from) || IS_DAX(inode)) 4475 return ret; 4476 return direct_write_fallback(iocb, from, ret, 4477 generic_perform_write(iocb, from)); 4478 } 4479 4480 return generic_perform_write(iocb, from); 4481 } 4482 EXPORT_SYMBOL(__generic_file_write_iter); 4483 4484 /** 4485 * generic_file_write_iter - write data to a file 4486 * @iocb: IO state structure 4487 * @from: iov_iter with data to write 4488 * 4489 * This is a wrapper around __generic_file_write_iter() to be used by most 4490 * filesystems. It takes care of syncing the file in case of O_SYNC file 4491 * and acquires i_rwsem as needed. 4492 * Return: 4493 * * negative error code if no data has been written at all of 4494 * vfs_fsync_range() failed for a synchronous write 4495 * * number of bytes written, even for truncated writes 4496 */ 4497 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from) 4498 { 4499 struct file *file = iocb->ki_filp; 4500 struct inode *inode = file->f_mapping->host; 4501 ssize_t ret; 4502 4503 inode_lock(inode); 4504 ret = generic_write_checks(iocb, from); 4505 if (ret > 0) 4506 ret = __generic_file_write_iter(iocb, from); 4507 inode_unlock(inode); 4508 4509 if (ret > 0) 4510 ret = generic_write_sync(iocb, ret); 4511 return ret; 4512 } 4513 EXPORT_SYMBOL(generic_file_write_iter); 4514 4515 /** 4516 * filemap_release_folio() - Release fs-specific metadata on a folio. 4517 * @folio: The folio which the kernel is trying to free. 4518 * @gfp: Memory allocation flags (and I/O mode). 4519 * 4520 * The address_space is trying to release any data attached to a folio 4521 * (presumably at folio->private). 4522 * 4523 * This will also be called if the private_2 flag is set on a page, 4524 * indicating that the folio has other metadata associated with it. 4525 * 4526 * The @gfp argument specifies whether I/O may be performed to release 4527 * this page (__GFP_IO), and whether the call may block 4528 * (__GFP_RECLAIM & __GFP_FS). 4529 * 4530 * Return: %true if the release was successful, otherwise %false. 4531 */ 4532 bool filemap_release_folio(struct folio *folio, gfp_t gfp) 4533 { 4534 struct address_space * const mapping = folio->mapping; 4535 4536 BUG_ON(!folio_test_locked(folio)); 4537 if (!folio_needs_release(folio)) 4538 return true; 4539 if (folio_test_writeback(folio)) 4540 return false; 4541 4542 if (mapping && mapping->a_ops->release_folio) 4543 return mapping->a_ops->release_folio(folio, gfp); 4544 return try_to_free_buffers(folio); 4545 } 4546 EXPORT_SYMBOL(filemap_release_folio); 4547 4548 /** 4549 * filemap_invalidate_inode - Invalidate/forcibly write back a range of an inode's pagecache 4550 * @inode: The inode to flush 4551 * @flush: Set to write back rather than simply invalidate. 4552 * @start: First byte to in range. 4553 * @end: Last byte in range (inclusive), or LLONG_MAX for everything from start 4554 * onwards. 4555 * 4556 * Invalidate all the folios on an inode that contribute to the specified 4557 * range, possibly writing them back first. Whilst the operation is 4558 * undertaken, the invalidate lock is held to prevent new folios from being 4559 * installed. 4560 */ 4561 int filemap_invalidate_inode(struct inode *inode, bool flush, 4562 loff_t start, loff_t end) 4563 { 4564 struct address_space *mapping = inode->i_mapping; 4565 pgoff_t first = start >> PAGE_SHIFT; 4566 pgoff_t last = end >> PAGE_SHIFT; 4567 pgoff_t nr = end == LLONG_MAX ? ULONG_MAX : last - first + 1; 4568 4569 if (!mapping || !mapping->nrpages || end < start) 4570 goto out; 4571 4572 /* Prevent new folios from being added to the inode. */ 4573 filemap_invalidate_lock(mapping); 4574 4575 if (!mapping->nrpages) 4576 goto unlock; 4577 4578 unmap_mapping_pages(mapping, first, nr, false); 4579 4580 /* Write back the data if we're asked to. */ 4581 if (flush) 4582 filemap_fdatawrite_range(mapping, start, end); 4583 4584 /* Wait for writeback to complete on all folios and discard. */ 4585 invalidate_inode_pages2_range(mapping, start / PAGE_SIZE, end / PAGE_SIZE); 4586 4587 unlock: 4588 filemap_invalidate_unlock(mapping); 4589 out: 4590 return filemap_check_errors(mapping); 4591 } 4592 EXPORT_SYMBOL_GPL(filemap_invalidate_inode); 4593 4594 #ifdef CONFIG_CACHESTAT_SYSCALL 4595 /** 4596 * filemap_cachestat() - compute the page cache statistics of a mapping 4597 * @mapping: The mapping to compute the statistics for. 4598 * @first_index: The starting page cache index. 4599 * @last_index: The final page index (inclusive). 4600 * @cs: the cachestat struct to write the result to. 4601 * 4602 * This will query the page cache statistics of a mapping in the 4603 * page range of [first_index, last_index] (inclusive). The statistics 4604 * queried include: number of dirty pages, number of pages marked for 4605 * writeback, and the number of (recently) evicted pages. 4606 */ 4607 static void filemap_cachestat(struct address_space *mapping, 4608 pgoff_t first_index, pgoff_t last_index, struct cachestat *cs) 4609 { 4610 XA_STATE(xas, &mapping->i_pages, first_index); 4611 struct folio *folio; 4612 4613 /* Flush stats (and potentially sleep) outside the RCU read section. */ 4614 mem_cgroup_flush_stats_ratelimited(NULL); 4615 4616 rcu_read_lock(); 4617 xas_for_each(&xas, folio, last_index) { 4618 int order; 4619 unsigned long nr_pages; 4620 pgoff_t folio_first_index, folio_last_index; 4621 4622 /* 4623 * Don't deref the folio. It is not pinned, and might 4624 * get freed (and reused) underneath us. 4625 * 4626 * We *could* pin it, but that would be expensive for 4627 * what should be a fast and lightweight syscall. 4628 * 4629 * Instead, derive all information of interest from 4630 * the rcu-protected xarray. 4631 */ 4632 4633 if (xas_retry(&xas, folio)) 4634 continue; 4635 4636 order = xas_get_order(&xas); 4637 nr_pages = 1 << order; 4638 folio_first_index = round_down(xas.xa_index, 1 << order); 4639 folio_last_index = folio_first_index + nr_pages - 1; 4640 4641 /* Folios might straddle the range boundaries, only count covered pages */ 4642 if (folio_first_index < first_index) 4643 nr_pages -= first_index - folio_first_index; 4644 4645 if (folio_last_index > last_index) 4646 nr_pages -= folio_last_index - last_index; 4647 4648 if (xa_is_value(folio)) { 4649 /* page is evicted */ 4650 void *shadow = (void *)folio; 4651 bool workingset; /* not used */ 4652 4653 cs->nr_evicted += nr_pages; 4654 4655 #ifdef CONFIG_SWAP /* implies CONFIG_MMU */ 4656 if (shmem_mapping(mapping)) { 4657 /* shmem file - in swap cache */ 4658 swp_entry_t swp = radix_to_swp_entry(folio); 4659 4660 /* swapin error results in poisoned entry */ 4661 if (!softleaf_is_swap(swp)) 4662 goto resched; 4663 4664 /* 4665 * Getting a swap entry from the shmem 4666 * inode means we beat 4667 * shmem_unuse(). rcu_read_lock() 4668 * ensures swapoff waits for us before 4669 * freeing the swapper space. However, 4670 * we can race with swapping and 4671 * invalidation, so there might not be 4672 * a shadow in the swapcache (yet). 4673 */ 4674 shadow = swap_cache_get_shadow(swp); 4675 if (!shadow) 4676 goto resched; 4677 } 4678 #endif 4679 if (workingset_test_recent(shadow, true, &workingset, false)) 4680 cs->nr_recently_evicted += nr_pages; 4681 4682 goto resched; 4683 } 4684 4685 /* page is in cache */ 4686 cs->nr_cache += nr_pages; 4687 4688 if (xas_get_mark(&xas, PAGECACHE_TAG_DIRTY)) 4689 cs->nr_dirty += nr_pages; 4690 4691 if (xas_get_mark(&xas, PAGECACHE_TAG_WRITEBACK)) 4692 cs->nr_writeback += nr_pages; 4693 4694 resched: 4695 if (need_resched()) { 4696 xas_pause(&xas); 4697 cond_resched_rcu(); 4698 } 4699 } 4700 rcu_read_unlock(); 4701 } 4702 4703 /* 4704 * See mincore: reveal pagecache information only for files 4705 * that the calling process has write access to, or could (if 4706 * tried) open for writing. 4707 */ 4708 static inline bool can_do_cachestat(struct file *f) 4709 { 4710 if (f->f_mode & FMODE_WRITE) 4711 return true; 4712 if (inode_owner_or_capable(file_mnt_idmap(f), file_inode(f))) 4713 return true; 4714 return file_permission(f, MAY_WRITE) == 0; 4715 } 4716 4717 /* 4718 * The cachestat(2) system call. 4719 * 4720 * cachestat() returns the page cache statistics of a file in the 4721 * bytes range specified by `off` and `len`: number of cached pages, 4722 * number of dirty pages, number of pages marked for writeback, 4723 * number of evicted pages, and number of recently evicted pages. 4724 * 4725 * An evicted page is a page that is previously in the page cache 4726 * but has been evicted since. A page is recently evicted if its last 4727 * eviction was recent enough that its reentry to the cache would 4728 * indicate that it is actively being used by the system, and that 4729 * there is memory pressure on the system. 4730 * 4731 * `off` and `len` must be non-negative integers. If `len` > 0, 4732 * the queried range is [`off`, `off` + `len`]. If `len` == 0, 4733 * we will query in the range from `off` to the end of the file. 4734 * 4735 * The `flags` argument is unused for now, but is included for future 4736 * extensibility. User should pass 0 (i.e no flag specified). 4737 * 4738 * Currently, hugetlbfs is not supported. 4739 * 4740 * Because the status of a page can change after cachestat() checks it 4741 * but before it returns to the application, the returned values may 4742 * contain stale information. 4743 * 4744 * return values: 4745 * zero - success 4746 * -EFAULT - cstat or cstat_range points to an illegal address 4747 * -EINVAL - invalid flags 4748 * -EBADF - invalid file descriptor 4749 * -EOPNOTSUPP - file descriptor is of a hugetlbfs file 4750 */ 4751 SYSCALL_DEFINE4(cachestat, unsigned int, fd, 4752 struct cachestat_range __user *, cstat_range, 4753 struct cachestat __user *, cstat, unsigned int, flags) 4754 { 4755 CLASS(fd, f)(fd); 4756 struct address_space *mapping; 4757 struct cachestat_range csr; 4758 struct cachestat cs; 4759 pgoff_t first_index, last_index; 4760 4761 if (fd_empty(f)) 4762 return -EBADF; 4763 4764 if (copy_from_user(&csr, cstat_range, 4765 sizeof(struct cachestat_range))) 4766 return -EFAULT; 4767 4768 /* hugetlbfs is not supported */ 4769 if (is_file_hugepages(fd_file(f))) 4770 return -EOPNOTSUPP; 4771 4772 if (!can_do_cachestat(fd_file(f))) 4773 return -EPERM; 4774 4775 if (flags != 0) 4776 return -EINVAL; 4777 4778 first_index = csr.off >> PAGE_SHIFT; 4779 last_index = 4780 csr.len == 0 ? ULONG_MAX : (csr.off + csr.len - 1) >> PAGE_SHIFT; 4781 memset(&cs, 0, sizeof(struct cachestat)); 4782 mapping = fd_file(f)->f_mapping; 4783 filemap_cachestat(mapping, first_index, last_index, &cs); 4784 4785 if (copy_to_user(cstat, &cs, sizeof(struct cachestat))) 4786 return -EFAULT; 4787 4788 return 0; 4789 } 4790 #endif /* CONFIG_CACHESTAT_SYSCALL */ 4791