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