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