1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Copyright (C) 2008, 2009 Intel Corporation 4 * Authors: Andi Kleen, Fengguang Wu 5 * 6 * High level machine check handler. Handles pages reported by the 7 * hardware as being corrupted usually due to a multi-bit ECC memory or cache 8 * failure. 9 * 10 * In addition there is a "soft offline" entry point that allows stop using 11 * not-yet-corrupted-by-suspicious pages without killing anything. 12 * 13 * Handles page cache pages in various states. The tricky part 14 * here is that we can access any page asynchronously in respect to 15 * other VM users, because memory failures could happen anytime and 16 * anywhere. This could violate some of their assumptions. This is why 17 * this code has to be extremely careful. Generally it tries to use 18 * normal locking rules, as in get the standard locks, even if that means 19 * the error handling takes potentially a long time. 20 * 21 * It can be very tempting to add handling for obscure cases here. 22 * In general any code for handling new cases should only be added iff: 23 * - You know how to test it. 24 * - You have a test that can be added to mce-test 25 * https://git.kernel.org/cgit/utils/cpu/mce/mce-test.git/ 26 * - The case actually shows up as a frequent (top 10) page state in 27 * tools/mm/page-types when running a real workload. 28 * 29 * There are several operations here with exponential complexity because 30 * of unsuitable VM data structures. For example the operation to map back 31 * from RMAP chains to processes has to walk the complete process list and 32 * has non linear complexity with the number. But since memory corruptions 33 * are rare we hope to get away with this. This avoids impacting the core 34 * VM. 35 */ 36 37 #define pr_fmt(fmt) "Memory failure: " fmt 38 39 #include <linux/kernel.h> 40 #include <linux/mm.h> 41 #include <linux/memory-failure.h> 42 #include <linux/page-flags.h> 43 #include <linux/sched/signal.h> 44 #include <linux/sched/task.h> 45 #include <linux/dax.h> 46 #include <linux/ksm.h> 47 #include <linux/rmap.h> 48 #include <linux/export.h> 49 #include <linux/pagemap.h> 50 #include <linux/swap.h> 51 #include <linux/backing-dev.h> 52 #include <linux/migrate.h> 53 #include <linux/slab.h> 54 #include <linux/leafops.h> 55 #include <linux/hugetlb.h> 56 #include <linux/memory_hotplug.h> 57 #include <linux/mm_inline.h> 58 #include <linux/memremap.h> 59 #include <linux/kfifo.h> 60 #include <linux/ratelimit.h> 61 #include <linux/pagewalk.h> 62 #include <linux/shmem_fs.h> 63 #include <linux/sysctl.h> 64 65 #define CREATE_TRACE_POINTS 66 #include <trace/events/memory-failure.h> 67 68 #include "swap.h" 69 #include "page_alloc.h" 70 #include "internal.h" 71 72 static int sysctl_memory_failure_early_kill __read_mostly; 73 74 static int sysctl_memory_failure_recovery __read_mostly = 1; 75 76 static int sysctl_enable_soft_offline __read_mostly = 1; 77 78 static int sysctl_panic_on_unrecoverable_mf __read_mostly; 79 80 atomic_long_t num_poisoned_pages __read_mostly = ATOMIC_LONG_INIT(0); 81 82 static bool hw_memory_failure __read_mostly; 83 84 static DEFINE_MUTEX(mf_mutex); 85 86 void num_poisoned_pages_inc(unsigned long pfn) 87 { 88 atomic_long_inc(&num_poisoned_pages); 89 memblk_nr_poison_inc(pfn); 90 } 91 92 void num_poisoned_pages_sub(unsigned long pfn, long i) 93 { 94 atomic_long_sub(i, &num_poisoned_pages); 95 if (pfn != -1UL) 96 memblk_nr_poison_sub(pfn, i); 97 } 98 99 /* 100 * Return the first or the last hardware-poisoned online page in [start, 101 * start + size), or PHYS_ADDR_MAX if the range is clean. 102 */ 103 static phys_addr_t range_hwpoison(phys_addr_t start, unsigned long size, 104 bool first) 105 { 106 phys_addr_t poison = PHYS_ADDR_MAX; 107 unsigned long pfn, end_pfn; 108 109 if (!size || !atomic_long_read(&num_poisoned_pages)) 110 return poison; 111 112 end_pfn = PHYS_PFN(start + size - 1); 113 for (pfn = PHYS_PFN(start); pfn <= end_pfn; pfn++) { 114 struct page *page = pfn_to_online_page(pfn); 115 116 if (page && is_page_hwpoison(page)) { 117 if (first) 118 return PFN_PHYS(pfn); 119 120 poison = PFN_PHYS(pfn); 121 } 122 123 cond_resched(); 124 } 125 126 return poison; 127 } 128 129 phys_addr_t range_first_hwpoison(phys_addr_t start, unsigned long size) 130 { 131 return range_hwpoison(start, size, true); 132 } 133 134 phys_addr_t range_last_hwpoison(phys_addr_t start, unsigned long size) 135 { 136 return range_hwpoison(start, size, false); 137 } 138 139 /** 140 * MF_ATTR_RO - Create sysfs entry for each memory failure statistics. 141 * @_name: name of the file in the per NUMA sysfs directory. 142 */ 143 #define MF_ATTR_RO(_name) \ 144 static ssize_t _name##_show(struct device *dev, \ 145 struct device_attribute *attr, \ 146 char *buf) \ 147 { \ 148 struct memory_failure_stats *mf_stats = \ 149 &NODE_DATA(dev->id)->mf_stats; \ 150 return sysfs_emit(buf, "%lu\n", mf_stats->_name); \ 151 } \ 152 static DEVICE_ATTR_RO(_name) 153 154 MF_ATTR_RO(total); 155 MF_ATTR_RO(ignored); 156 MF_ATTR_RO(failed); 157 MF_ATTR_RO(delayed); 158 MF_ATTR_RO(recovered); 159 160 static struct attribute *memory_failure_attr[] = { 161 &dev_attr_total.attr, 162 &dev_attr_ignored.attr, 163 &dev_attr_failed.attr, 164 &dev_attr_delayed.attr, 165 &dev_attr_recovered.attr, 166 NULL, 167 }; 168 169 const struct attribute_group memory_failure_attr_group = { 170 .name = "memory_failure", 171 .attrs = memory_failure_attr, 172 }; 173 174 static const struct ctl_table memory_failure_table[] = { 175 { 176 .procname = "memory_failure_early_kill", 177 .data = &sysctl_memory_failure_early_kill, 178 .maxlen = sizeof(sysctl_memory_failure_early_kill), 179 .mode = 0644, 180 .proc_handler = proc_dointvec_minmax, 181 .extra1 = SYSCTL_ZERO, 182 .extra2 = SYSCTL_ONE, 183 }, 184 { 185 .procname = "memory_failure_recovery", 186 .data = &sysctl_memory_failure_recovery, 187 .maxlen = sizeof(sysctl_memory_failure_recovery), 188 .mode = 0644, 189 .proc_handler = proc_dointvec_minmax, 190 .extra1 = SYSCTL_ZERO, 191 .extra2 = SYSCTL_ONE, 192 }, 193 { 194 .procname = "enable_soft_offline", 195 .data = &sysctl_enable_soft_offline, 196 .maxlen = sizeof(sysctl_enable_soft_offline), 197 .mode = 0644, 198 .proc_handler = proc_dointvec_minmax, 199 .extra1 = SYSCTL_ZERO, 200 .extra2 = SYSCTL_ONE, 201 }, 202 { 203 .procname = "panic_on_unrecoverable_memory_failure", 204 .data = &sysctl_panic_on_unrecoverable_mf, 205 .maxlen = sizeof(sysctl_panic_on_unrecoverable_mf), 206 .mode = 0644, 207 .proc_handler = proc_dointvec_minmax, 208 .extra1 = SYSCTL_ZERO, 209 .extra2 = SYSCTL_ONE, 210 } 211 }; 212 213 static struct rb_root_cached pfn_space_itree = RB_ROOT_CACHED; 214 215 static DEFINE_MUTEX(pfn_space_lock); 216 217 /* 218 * Return values: 219 * 1: the page is dissolved (if needed) and taken off from buddy, 220 * 0: the page is dissolved (if needed) and not taken off from buddy, 221 * < 0: failed to dissolve. 222 */ 223 static int __page_handle_poison(struct page *page) 224 { 225 int ret; 226 227 zone_pcp_disable(page_zone(page)); 228 ret = dissolve_free_hugetlb_folio(page_folio(page)); 229 if (!ret) 230 ret = take_page_off_buddy(page); 231 zone_pcp_enable(page_zone(page)); 232 233 return ret; 234 } 235 236 static bool page_handle_poison(struct page *page, bool hugepage_or_freepage, bool release) 237 { 238 if (hugepage_or_freepage) { 239 /* 240 * Doing this check for free pages is also fine since 241 * dissolve_free_hugetlb_folio() returns 0 for non-hugetlb folios as well. 242 */ 243 if (__page_handle_poison(page) <= 0) 244 /* 245 * We could fail to take off the target page from buddy 246 * for example due to racy page allocation, but that's 247 * acceptable because soft-offlined page is not broken 248 * and if someone really want to use it, they should 249 * take it. 250 */ 251 return false; 252 } 253 254 SetPageHWPoison(page); 255 if (release) 256 put_page(page); 257 page_ref_inc(page); 258 num_poisoned_pages_inc(page_to_pfn(page)); 259 260 return true; 261 } 262 263 static hwpoison_filter_func_t __rcu *hwpoison_filter_func __read_mostly; 264 265 void hwpoison_filter_register(hwpoison_filter_func_t *filter) 266 { 267 rcu_assign_pointer(hwpoison_filter_func, filter); 268 } 269 EXPORT_SYMBOL_GPL(hwpoison_filter_register); 270 271 void hwpoison_filter_unregister(void) 272 { 273 RCU_INIT_POINTER(hwpoison_filter_func, NULL); 274 synchronize_rcu(); 275 } 276 EXPORT_SYMBOL_GPL(hwpoison_filter_unregister); 277 278 static int hwpoison_filter(struct page *p) 279 { 280 int ret = 0; 281 hwpoison_filter_func_t *filter; 282 283 rcu_read_lock(); 284 filter = rcu_dereference(hwpoison_filter_func); 285 if (filter) 286 ret = filter(p); 287 rcu_read_unlock(); 288 289 return ret; 290 } 291 292 /* 293 * Kill all processes that have a poisoned page mapped and then isolate 294 * the page. 295 * 296 * General strategy: 297 * Find all processes having the page mapped and kill them. 298 * But we keep a page reference around so that the page is not 299 * actually freed yet. 300 * Then stash the page away 301 * 302 * There's no convenient way to get back to mapped processes 303 * from the VMAs. So do a brute-force search over all 304 * running processes. 305 * 306 * Remember that machine checks are not common (or rather 307 * if they are common you have other problems), so this shouldn't 308 * be a performance issue. 309 * 310 * Also there are some races possible while we get from the 311 * error detection to actually handle it. 312 */ 313 314 struct to_kill { 315 struct list_head nd; 316 struct task_struct *tsk; 317 unsigned long addr; 318 short size_shift; 319 }; 320 321 /* 322 * Send all the processes who have the page mapped a signal. 323 * ``action optional'' if they are not immediately affected by the error 324 * ``action required'' if error happened in current execution context 325 */ 326 static int kill_proc(struct to_kill *tk, unsigned long pfn, int flags) 327 { 328 struct task_struct *t = tk->tsk; 329 short addr_lsb = tk->size_shift; 330 int ret = 0; 331 332 pr_err("%#lx: Sending SIGBUS to %s:%d due to hardware memory corruption\n", 333 pfn, t->comm, task_pid_nr(t)); 334 335 if ((flags & MF_ACTION_REQUIRED) && (t == current)) 336 ret = force_sig_mceerr(BUS_MCEERR_AR, 337 (void __user *)tk->addr, addr_lsb); 338 else 339 /* 340 * Signal other processes sharing the page if they have 341 * PF_MCE_EARLY set. 342 * Don't use force here, it's convenient if the signal 343 * can be temporarily blocked. 344 */ 345 ret = send_sig_mceerr(BUS_MCEERR_AO, (void __user *)tk->addr, 346 addr_lsb, t); 347 if (ret < 0) 348 pr_info("Error sending signal to %s:%d: %d\n", 349 t->comm, task_pid_nr(t), ret); 350 return ret; 351 } 352 353 /* 354 * Unknown page type encountered. Try to check whether it can turn PageLRU by 355 * lru_add_drain_all. 356 */ 357 void shake_folio(struct folio *folio) 358 { 359 if (folio_test_hugetlb(folio)) 360 return; 361 /* 362 * TODO: Could shrink slab caches here if a lightweight range-based 363 * shrinker will be available. 364 */ 365 if (folio_test_slab(folio)) 366 return; 367 368 lru_add_drain_all(); 369 } 370 EXPORT_SYMBOL_GPL(shake_folio); 371 372 static void shake_page(struct page *page) 373 { 374 shake_folio(page_folio(page)); 375 } 376 377 static unsigned long dev_pagemap_mapping_shift(struct vm_area_struct *vma, 378 unsigned long address) 379 { 380 unsigned long ret = 0; 381 pgd_t *pgd; 382 p4d_t *p4d; 383 pud_t *pud; 384 pmd_t *pmd; 385 pte_t *pte; 386 pte_t ptent; 387 388 VM_BUG_ON_VMA(address == -EFAULT, vma); 389 pgd = pgd_offset(vma->vm_mm, address); 390 if (!pgd_present(*pgd)) 391 return 0; 392 p4d = p4d_offset(pgd, address); 393 if (!p4d_present(*p4d)) 394 return 0; 395 pud = pud_offset(p4d, address); 396 if (!pud_present(*pud)) 397 return 0; 398 if (pud_trans_huge(*pud)) 399 return PUD_SHIFT; 400 pmd = pmd_offset(pud, address); 401 if (!pmd_present(*pmd)) 402 return 0; 403 if (pmd_trans_huge(*pmd)) 404 return PMD_SHIFT; 405 pte = pte_offset_map(pmd, address); 406 if (!pte) 407 return 0; 408 ptent = ptep_get(pte); 409 if (pte_present(ptent)) 410 ret = PAGE_SHIFT; 411 pte_unmap(pte); 412 return ret; 413 } 414 415 /* 416 * Failure handling: if we can't find or can't kill a process there's 417 * not much we can do. We just print a message and ignore otherwise. 418 */ 419 420 /* 421 * Schedule a process for later kill. 422 * Uses GFP_ATOMIC allocations to avoid potential recursions in the VM. 423 */ 424 static void __add_to_kill(struct task_struct *tsk, const struct page *p, 425 struct vm_area_struct *vma, struct list_head *to_kill, 426 unsigned long addr) 427 { 428 struct to_kill *tk; 429 430 tk = kmalloc_obj(struct to_kill, GFP_ATOMIC); 431 if (!tk) { 432 pr_err("Out of memory while machine check handling\n"); 433 return; 434 } 435 436 tk->addr = addr; 437 if (is_zone_device_page(p)) 438 tk->size_shift = dev_pagemap_mapping_shift(vma, tk->addr); 439 else 440 tk->size_shift = folio_shift(page_folio(p)); 441 442 /* 443 * Send SIGKILL if "tk->addr == -EFAULT". Also, as 444 * "tk->size_shift" is always non-zero for !is_zone_device_page(), 445 * so "tk->size_shift == 0" effectively checks no mapping on 446 * ZONE_DEVICE. Indeed, when a devdax page is mmapped N times 447 * to a process' address space, it's possible not all N VMAs 448 * contain mappings for the page, but at least one VMA does. 449 * Only deliver SIGBUS with payload derived from the VMA that 450 * has a mapping for the page. 451 */ 452 if (tk->addr == -EFAULT) { 453 pr_info("Unable to find user space address %lx in %s\n", 454 page_to_pfn(p), tsk->comm); 455 } else if (tk->size_shift == 0) { 456 kfree(tk); 457 return; 458 } 459 460 get_task_struct(tsk); 461 tk->tsk = tsk; 462 list_add_tail(&tk->nd, to_kill); 463 } 464 465 static void add_to_kill_anon_file(struct task_struct *tsk, const struct page *p, 466 struct vm_area_struct *vma, struct list_head *to_kill, 467 unsigned long addr) 468 { 469 if (addr == -EFAULT) 470 return; 471 __add_to_kill(tsk, p, vma, to_kill, addr); 472 } 473 474 #ifdef CONFIG_KSM 475 static bool task_in_to_kill_list(struct list_head *to_kill, 476 struct task_struct *tsk) 477 { 478 struct to_kill *tk, *next; 479 480 list_for_each_entry_safe(tk, next, to_kill, nd) { 481 if (tk->tsk == tsk) 482 return true; 483 } 484 485 return false; 486 } 487 488 void add_to_kill_ksm(struct task_struct *tsk, const struct page *p, 489 struct vm_area_struct *vma, struct list_head *to_kill, 490 unsigned long addr) 491 { 492 if (!task_in_to_kill_list(to_kill, tsk)) 493 __add_to_kill(tsk, p, vma, to_kill, addr); 494 } 495 #endif 496 /* 497 * Kill the processes that have been collected earlier. 498 * 499 * Only do anything when FORCEKILL is set, otherwise just free the 500 * list (this is used for clean pages which do not need killing) 501 */ 502 static void kill_procs(struct list_head *to_kill, bool forcekill, 503 unsigned long pfn, int flags) 504 { 505 struct to_kill *tk, *next; 506 507 list_for_each_entry_safe(tk, next, to_kill, nd) { 508 if (forcekill) { 509 if (tk->addr == -EFAULT) { 510 pr_err("%#lx: forcibly killing %s:%d because of failure to unmap corrupted page\n", 511 pfn, tk->tsk->comm, task_pid_nr(tk->tsk)); 512 do_send_sig_info(SIGKILL, SEND_SIG_PRIV, 513 tk->tsk, PIDTYPE_PID); 514 } 515 516 /* 517 * In theory the process could have mapped 518 * something else on the address in-between. We could 519 * check for that, but we need to tell the 520 * process anyways. 521 */ 522 else if (kill_proc(tk, pfn, flags) < 0) 523 pr_err("%#lx: Cannot send advisory machine check signal to %s:%d\n", 524 pfn, tk->tsk->comm, task_pid_nr(tk->tsk)); 525 } 526 list_del(&tk->nd); 527 put_task_struct(tk->tsk); 528 kfree(tk); 529 } 530 } 531 532 /* 533 * Find a dedicated thread which is supposed to handle SIGBUS(BUS_MCEERR_AO) 534 * on behalf of the thread group. Return task_struct of the (first found) 535 * dedicated thread if found, and return NULL otherwise. 536 * 537 * We already hold rcu lock in the caller, so we don't have to call 538 * rcu_read_lock/unlock() in this function. 539 */ 540 static struct task_struct *find_early_kill_thread(struct task_struct *tsk) 541 { 542 struct task_struct *t; 543 544 for_each_thread(tsk, t) { 545 if (t->flags & PF_MCE_PROCESS) { 546 if (t->flags & PF_MCE_EARLY) 547 return t; 548 } else { 549 if (sysctl_memory_failure_early_kill) 550 return t; 551 } 552 } 553 return NULL; 554 } 555 556 /* 557 * Determine whether a given process is "early kill" process which expects 558 * to be signaled when some page under the process is hwpoisoned. 559 * Return task_struct of the dedicated thread (main thread unless explicitly 560 * specified) if the process is "early kill" and otherwise returns NULL. 561 * 562 * Note that the above is true for Action Optional case. For Action Required 563 * case, it's only meaningful to the current thread which need to be signaled 564 * with SIGBUS, this error is Action Optional for other non current 565 * processes sharing the same error page,if the process is "early kill", the 566 * task_struct of the dedicated thread will also be returned. 567 */ 568 struct task_struct *task_early_kill(struct task_struct *tsk, int force_early) 569 { 570 if (!tsk->mm) 571 return NULL; 572 /* 573 * Comparing ->mm here because current task might represent 574 * a subthread, while tsk always points to the main thread. 575 */ 576 if (force_early && tsk->mm == current->mm) 577 return current; 578 579 return find_early_kill_thread(tsk); 580 } 581 582 /* 583 * Collect processes when the error hit an anonymous page. 584 */ 585 static void collect_procs_anon(const struct folio *folio, 586 const struct page *page, struct list_head *to_kill, 587 int force_early) 588 { 589 struct task_struct *tsk; 590 struct anon_vma *av; 591 pgoff_t pgoff; 592 593 av = folio_lock_anon_vma_read(folio, NULL); 594 if (av == NULL) /* Not actually mapped anymore */ 595 return; 596 597 pgoff = page_pgoff(folio, page); 598 rcu_read_lock(); 599 for_each_process(tsk) { 600 struct vm_area_struct *vma; 601 struct anon_vma_chain *vmac; 602 struct task_struct *t = task_early_kill(tsk, force_early); 603 unsigned long addr; 604 605 if (!t) 606 continue; 607 anon_rmap_tree_foreach(vmac, av, pgoff, pgoff) { 608 vma = vmac->vma; 609 if (vma->vm_mm != t->mm) 610 continue; 611 addr = page_mapped_in_vma(page, vma); 612 add_to_kill_anon_file(t, page, vma, to_kill, addr); 613 } 614 } 615 rcu_read_unlock(); 616 anon_vma_unlock_read(av); 617 } 618 619 /* 620 * Collect processes when the error hit a file mapped page. 621 */ 622 static void collect_procs_file(const struct folio *folio, 623 const struct page *page, struct list_head *to_kill, 624 int force_early) 625 { 626 struct vm_area_struct *vma; 627 struct task_struct *tsk; 628 struct address_space *mapping = folio->mapping; 629 pgoff_t pgoff; 630 631 i_mmap_lock_read(mapping); 632 rcu_read_lock(); 633 pgoff = page_pgoff(folio, page); 634 for_each_process(tsk) { 635 struct task_struct *t = task_early_kill(tsk, force_early); 636 unsigned long addr; 637 638 if (!t) 639 continue; 640 mapping_rmap_tree_foreach(vma, mapping, pgoff, pgoff) { 641 /* 642 * Send early kill signal to tasks where a vma covers 643 * the page but the corrupted page is not necessarily 644 * mapped in its pte. 645 * Assume applications who requested early kill want 646 * to be informed of all such data corruptions. 647 */ 648 if (vma->vm_mm != t->mm) 649 continue; 650 addr = page_address_in_vma(folio, page, vma); 651 add_to_kill_anon_file(t, page, vma, to_kill, addr); 652 } 653 } 654 rcu_read_unlock(); 655 i_mmap_unlock_read(mapping); 656 } 657 658 #ifdef CONFIG_FS_DAX 659 static void add_to_kill_fsdax(struct task_struct *tsk, const struct page *p, 660 struct vm_area_struct *vma, 661 struct list_head *to_kill, pgoff_t pgoff) 662 { 663 unsigned long addr = vma_filebacked_address(vma, pgoff, 1); 664 __add_to_kill(tsk, p, vma, to_kill, addr); 665 } 666 667 /* 668 * Collect processes when the error hit a fsdax page. 669 */ 670 static void collect_procs_fsdax(const struct page *page, 671 struct address_space *mapping, pgoff_t pgoff, 672 struct list_head *to_kill, bool pre_remove) 673 { 674 struct vm_area_struct *vma; 675 struct task_struct *tsk; 676 677 i_mmap_lock_read(mapping); 678 rcu_read_lock(); 679 for_each_process(tsk) { 680 struct task_struct *t = tsk; 681 682 /* 683 * Search for all tasks while MF_MEM_PRE_REMOVE is set, because 684 * the current may not be the one accessing the fsdax page. 685 * Otherwise, search for the current task. 686 */ 687 if (!pre_remove) 688 t = task_early_kill(tsk, true); 689 if (!t) 690 continue; 691 mapping_rmap_tree_foreach(vma, mapping, pgoff, pgoff) { 692 if (vma->vm_mm == t->mm) 693 add_to_kill_fsdax(t, page, vma, to_kill, pgoff); 694 } 695 } 696 rcu_read_unlock(); 697 i_mmap_unlock_read(mapping); 698 } 699 #endif /* CONFIG_FS_DAX */ 700 701 /* 702 * Collect the processes who have the corrupted page mapped to kill. 703 */ 704 static void collect_procs(const struct folio *folio, const struct page *page, 705 struct list_head *tokill, int force_early) 706 { 707 if (!folio->mapping) 708 return; 709 if (unlikely(folio_test_ksm(folio))) 710 collect_procs_ksm(folio, page, tokill, force_early); 711 else if (folio_test_anon(folio)) 712 collect_procs_anon(folio, page, tokill, force_early); 713 else 714 collect_procs_file(folio, page, tokill, force_early); 715 } 716 717 struct hwpoison_walk { 718 struct to_kill tk; 719 unsigned long pfn; 720 int flags; 721 }; 722 723 static void set_to_kill(struct to_kill *tk, unsigned long addr, short shift) 724 { 725 tk->addr = addr; 726 tk->size_shift = shift; 727 } 728 729 static int check_hwpoisoned_entry(pte_t pte, unsigned long addr, short shift, 730 unsigned long poisoned_pfn, struct to_kill *tk) 731 { 732 unsigned long pfn = 0; 733 unsigned long hwpoison_vaddr; 734 unsigned long mask; 735 736 if (pte_present(pte)) { 737 pfn = pte_pfn(pte); 738 } else { 739 const softleaf_t entry = softleaf_from_pte(pte); 740 741 if (softleaf_is_hwpoison(entry)) 742 pfn = softleaf_to_pfn(entry); 743 } 744 745 mask = ~((1UL << (shift - PAGE_SHIFT)) - 1); 746 if (!pfn || pfn != (poisoned_pfn & mask)) 747 return 0; 748 749 hwpoison_vaddr = addr + ((poisoned_pfn - pfn) << PAGE_SHIFT); 750 set_to_kill(tk, hwpoison_vaddr, shift); 751 return 1; 752 } 753 754 #ifdef CONFIG_TRANSPARENT_HUGEPAGE 755 static int check_hwpoisoned_pmd_entry(pmd_t *pmdp, unsigned long addr, 756 struct hwpoison_walk *hwp) 757 { 758 pmd_t pmd = *pmdp; 759 unsigned long pfn; 760 unsigned long hwpoison_vaddr; 761 762 if (!pmd_present(pmd)) 763 return 0; 764 pfn = pmd_pfn(pmd); 765 if (pfn <= hwp->pfn && hwp->pfn < pfn + HPAGE_PMD_NR) { 766 hwpoison_vaddr = addr + ((hwp->pfn - pfn) << PAGE_SHIFT); 767 set_to_kill(&hwp->tk, hwpoison_vaddr, PAGE_SHIFT); 768 return 1; 769 } 770 return 0; 771 } 772 #else 773 static int check_hwpoisoned_pmd_entry(pmd_t *pmdp, unsigned long addr, 774 struct hwpoison_walk *hwp) 775 { 776 return 0; 777 } 778 #endif 779 780 static int hwpoison_pte_range(pmd_t *pmdp, unsigned long addr, 781 unsigned long end, struct mm_walk *walk) 782 { 783 struct hwpoison_walk *hwp = walk->private; 784 int ret = 0; 785 pte_t *ptep, *mapped_pte; 786 spinlock_t *ptl; 787 788 ptl = pmd_trans_huge_lock(pmdp, walk->vma); 789 if (ptl) { 790 ret = check_hwpoisoned_pmd_entry(pmdp, addr, hwp); 791 spin_unlock(ptl); 792 goto out; 793 } 794 795 mapped_pte = ptep = pte_offset_map_lock(walk->vma->vm_mm, pmdp, 796 addr, &ptl); 797 if (!ptep) 798 goto out; 799 800 for (; addr != end; ptep++, addr += PAGE_SIZE) { 801 ret = check_hwpoisoned_entry(ptep_get(ptep), addr, PAGE_SHIFT, 802 hwp->pfn, &hwp->tk); 803 if (ret == 1) 804 break; 805 } 806 pte_unmap_unlock(mapped_pte, ptl); 807 out: 808 cond_resched(); 809 return ret; 810 } 811 812 #ifdef CONFIG_HUGETLB_PAGE 813 static int hwpoison_hugetlb_range(pte_t *ptep, unsigned long hmask, 814 unsigned long addr, unsigned long end, 815 struct mm_walk *walk) 816 { 817 struct hwpoison_walk *hwp = walk->private; 818 struct hstate *h = hstate_vma(walk->vma); 819 spinlock_t *ptl; 820 pte_t pte; 821 int ret; 822 823 ptl = huge_pte_lock(h, walk->mm, ptep); 824 pte = huge_ptep_get(walk->mm, addr, ptep); 825 ret = check_hwpoisoned_entry(pte, addr, huge_page_shift(h), 826 hwp->pfn, &hwp->tk); 827 spin_unlock(ptl); 828 return ret; 829 } 830 #else 831 #define hwpoison_hugetlb_range NULL 832 #endif 833 834 static int hwpoison_test_walk(unsigned long start, unsigned long end, 835 struct mm_walk *walk) 836 { 837 /* We also want to consider pages mapped into VM_PFNMAP. */ 838 return 0; 839 } 840 841 static const struct mm_walk_ops hwpoison_walk_ops = { 842 .pmd_entry = hwpoison_pte_range, 843 .hugetlb_entry = hwpoison_hugetlb_range, 844 .test_walk = hwpoison_test_walk, 845 .walk_lock = PGWALK_RDLOCK, 846 }; 847 848 /* 849 * Sends SIGBUS to the current process with error info. 850 * 851 * This function is intended to handle "Action Required" MCEs on already 852 * hardware poisoned pages. They could happen, for example, when 853 * memory_failure() failed to unmap the error page at the first call, or 854 * when multiple local machine checks happened on different CPUs. 855 * 856 * MCE handler currently has no easy access to the error virtual address, 857 * so this function walks page table to find it. The returned virtual address 858 * is proper in most cases, but it could be wrong when the application 859 * process has multiple entries mapping the error page. 860 */ 861 static int kill_accessing_process(struct task_struct *p, unsigned long pfn, 862 int flags) 863 { 864 int ret; 865 struct hwpoison_walk priv = { 866 .pfn = pfn, 867 }; 868 priv.tk.tsk = p; 869 870 if (!p->mm) 871 return -EFAULT; 872 873 mmap_read_lock(p->mm); 874 ret = walk_page_range(p->mm, 0, TASK_SIZE, &hwpoison_walk_ops, 875 (void *)&priv); 876 /* 877 * ret = 1 when CMCI wins, regardless of whether try_to_unmap() 878 * succeeds or fails, then kill the process with SIGBUS. 879 * ret = 0 when poison page is a clean page and it's dropped, no 880 * SIGBUS is needed. 881 */ 882 if (ret == 1 && priv.tk.addr) 883 kill_proc(&priv.tk, pfn, flags); 884 mmap_read_unlock(p->mm); 885 886 return ret > 0 ? -EHWPOISON : 0; 887 } 888 889 /* 890 * MF_IGNORED - The m-f() handler marks the page as PG_hwpoison'ed. 891 * But it could not do more to isolate the page from being accessed again, 892 * nor does it kill the process. This is extremely rare and one of the 893 * potential causes is that the page state has been changed due to 894 * underlying race condition. This is the most severe outcomes. 895 * 896 * MF_FAILED - The m-f() handler marks the page as PG_hwpoison'ed. 897 * It should have killed the process, but it can't isolate the page, 898 * due to conditions such as extra pin, unmap failure, etc. Accessing 899 * the page again may trigger another MCE and the process will be killed 900 * by the m-f() handler immediately. 901 * 902 * MF_DELAYED - The m-f() handler marks the page as PG_hwpoison'ed. 903 * It means the page was unmapped and partially isolated (e.g. removed from 904 * file mapping or the LRU) but full cleanup is deferred (e.g. the metadata 905 * for the memory, as in struct page/folio, is still referenced). Any 906 * further access to the page will result in the process being killed. 907 * 908 * MF_RECOVERED - The m-f() handler marks the page as PG_hwpoison'ed. 909 * The page has been completely isolated, that is, unmapped, taken out of 910 * the buddy system, or hole-punched out of the file mapping. 911 */ 912 static const char *action_name[] = { 913 [MF_IGNORED] = "Ignored", 914 [MF_FAILED] = "Failed", 915 [MF_DELAYED] = "Delayed", 916 [MF_RECOVERED] = "Recovered", 917 }; 918 919 static const char * const action_page_types[] = { 920 [MF_MSG_KERNEL] = "reserved kernel page", 921 [MF_MSG_KERNEL_HIGH_ORDER] = "high-order kernel page", 922 [MF_MSG_HUGE] = "huge page", 923 [MF_MSG_FREE_HUGE] = "free huge page", 924 [MF_MSG_GET_HWPOISON] = "get hwpoison page", 925 [MF_MSG_UNMAP_FAILED] = "unmapping failed page", 926 [MF_MSG_DIRTY_SWAPCACHE] = "dirty swapcache page", 927 [MF_MSG_CLEAN_SWAPCACHE] = "clean swapcache page", 928 [MF_MSG_DIRTY_MLOCKED_LRU] = "dirty mlocked LRU page", 929 [MF_MSG_CLEAN_MLOCKED_LRU] = "clean mlocked LRU page", 930 [MF_MSG_DIRTY_UNEVICTABLE_LRU] = "dirty unevictable LRU page", 931 [MF_MSG_CLEAN_UNEVICTABLE_LRU] = "clean unevictable LRU page", 932 [MF_MSG_DIRTY_LRU] = "dirty LRU page", 933 [MF_MSG_CLEAN_LRU] = "clean LRU page", 934 [MF_MSG_TRUNCATED_LRU] = "already truncated LRU page", 935 [MF_MSG_BUDDY] = "free buddy page", 936 [MF_MSG_DAX] = "dax page", 937 [MF_MSG_UNSPLIT_THP] = "unsplit thp", 938 [MF_MSG_ALREADY_POISONED] = "already poisoned page", 939 [MF_MSG_PFN_MAP] = "non struct page pfn", 940 [MF_MSG_UNKNOWN] = "unknown page", 941 }; 942 943 /* 944 * XXX: It is possible that a page is isolated from LRU cache, 945 * and then kept in swap cache or failed to remove from page cache. 946 * The page count will stop it from being freed by unpoison. 947 * Stress tests should be aware of this memory leak problem. 948 */ 949 static int delete_from_lru_cache(struct folio *folio) 950 { 951 if (folio_isolate_lru(folio)) { 952 /* 953 * Clear sensible page flags, so that the buddy system won't 954 * complain when the folio is unpoison-and-freed. 955 */ 956 folio_clear_active(folio); 957 folio_clear_unevictable(folio); 958 959 /* 960 * Poisoned page might never drop its ref count to 0 so we have 961 * to uncharge it manually from its memcg. 962 */ 963 mem_cgroup_uncharge(folio); 964 965 /* 966 * drop the refcount elevated by folio_isolate_lru() 967 */ 968 folio_put(folio); 969 return 0; 970 } 971 return -EIO; 972 } 973 974 static int truncate_error_folio(struct folio *folio, unsigned long pfn, 975 struct address_space *mapping) 976 { 977 int ret = MF_FAILED; 978 979 if (mapping->a_ops->error_remove_folio) { 980 int err = mapping->a_ops->error_remove_folio(mapping, folio); 981 982 if (err == MF_DELAYED) 983 ret = err; 984 else if (err != 0) 985 pr_info("%#lx: Failed to punch page: %d\n", pfn, err); 986 else if (!filemap_release_folio(folio, GFP_NOIO)) 987 pr_info("%#lx: Failed to release buffers\n", pfn); 988 else 989 ret = MF_RECOVERED; 990 } else { 991 /* 992 * If the file system doesn't support it just invalidate 993 * This fails on dirty or anything with private pages 994 */ 995 if (mapping_evict_folio(mapping, folio)) 996 ret = MF_RECOVERED; 997 else 998 pr_info("%#lx: Failed to invalidate\n", pfn); 999 } 1000 1001 return ret; 1002 } 1003 1004 struct page_state { 1005 unsigned long mask; 1006 unsigned long res; 1007 enum mf_action_page_type type; 1008 1009 /* Callback ->action() has to unlock the relevant page inside it. */ 1010 int (*action)(struct page_state *ps, struct page *p); 1011 }; 1012 1013 /* 1014 * Return true if page is still referenced by others, otherwise return 1015 * false. 1016 * 1017 * The extra_pins is true when one extra refcount is expected. 1018 */ 1019 static bool has_extra_refcount(struct page_state *ps, struct page *p, 1020 bool extra_pins) 1021 { 1022 int count = page_count(p) - 1; 1023 1024 if (extra_pins) 1025 count -= folio_nr_pages(page_folio(p)); 1026 1027 if (count > 0) { 1028 pr_err("%#lx: %s still referenced by %d users\n", 1029 page_to_pfn(p), action_page_types[ps->type], count); 1030 return true; 1031 } 1032 1033 return false; 1034 } 1035 1036 /* 1037 * Page in unknown state. Do nothing. 1038 * This is a catch-all in case we fail to make sense of the page state. 1039 */ 1040 static int me_unknown(struct page_state *ps, struct page *p) 1041 { 1042 pr_err("%#lx: Unknown page state\n", page_to_pfn(p)); 1043 unlock_page(p); 1044 return MF_IGNORED; 1045 } 1046 1047 /* 1048 * Clean (or cleaned) page cache page. 1049 */ 1050 static int me_pagecache_clean(struct page_state *ps, struct page *p) 1051 { 1052 struct folio *folio = page_folio(p); 1053 int ret; 1054 struct address_space *mapping; 1055 bool extra_pins; 1056 1057 delete_from_lru_cache(folio); 1058 1059 /* 1060 * For anonymous folios the only reference left 1061 * should be the one m_f() holds. 1062 */ 1063 if (folio_test_anon(folio)) { 1064 ret = MF_RECOVERED; 1065 goto out; 1066 } 1067 1068 /* 1069 * Now truncate the page in the page cache. This is really 1070 * more like a "temporary hole punch" 1071 * Don't do this for block devices when someone else 1072 * has a reference, because it could be file system metadata 1073 * and that's not safe to truncate. 1074 */ 1075 mapping = folio_mapping(folio); 1076 if (!mapping) { 1077 /* Folio has been torn down in the meantime */ 1078 ret = MF_FAILED; 1079 goto out; 1080 } 1081 1082 /* 1083 * Truncation is a bit tricky. Enable it per file system for now. 1084 * 1085 * Open: to take i_rwsem or not for this? Right now we don't. 1086 */ 1087 ret = truncate_error_folio(folio, page_to_pfn(p), mapping); 1088 1089 extra_pins = ret == MF_DELAYED; 1090 if (has_extra_refcount(ps, p, extra_pins)) 1091 ret = MF_FAILED; 1092 1093 out: 1094 folio_unlock(folio); 1095 1096 return ret; 1097 } 1098 1099 /* 1100 * Dirty pagecache page 1101 * Issues: when the error hit a hole page the error is not properly 1102 * propagated. 1103 */ 1104 static int me_pagecache_dirty(struct page_state *ps, struct page *p) 1105 { 1106 struct folio *folio = page_folio(p); 1107 struct address_space *mapping = folio_mapping(folio); 1108 1109 /* TBD: print more information about the file. */ 1110 if (mapping) { 1111 /* 1112 * IO error will be reported by write(), fsync(), etc. 1113 * who check the mapping. 1114 * This way the application knows that something went 1115 * wrong with its dirty file data. 1116 */ 1117 mapping_set_error(mapping, -EIO); 1118 } 1119 1120 return me_pagecache_clean(ps, p); 1121 } 1122 1123 /* 1124 * Clean and dirty swap cache. 1125 * 1126 * Dirty swap cache page is tricky to handle. The page could live both in page 1127 * table and swap cache(ie. page is freshly swapped in). So it could be 1128 * referenced concurrently by 2 types of PTEs: 1129 * normal PTEs and swap PTEs. We try to handle them consistently by calling 1130 * try_to_unmap(!TTU_HWPOISON) to convert the normal PTEs to swap PTEs, 1131 * and then 1132 * - clear dirty bit to prevent IO 1133 * - remove from LRU 1134 * - but keep in the swap cache, so that when we return to it on 1135 * a later page fault, we know the application is accessing 1136 * corrupted data and shall be killed (we installed simple 1137 * interception code in do_swap_page to catch it). 1138 * 1139 * Clean swap cache pages can be directly isolated. A later page fault will 1140 * bring in the known good data from disk. 1141 */ 1142 static int me_swapcache_dirty(struct page_state *ps, struct page *p) 1143 { 1144 struct folio *folio = page_folio(p); 1145 int ret; 1146 bool extra_pins = false; 1147 1148 folio_clear_dirty(folio); 1149 /* Trigger EIO in shmem: */ 1150 folio_clear_uptodate(folio); 1151 1152 ret = delete_from_lru_cache(folio) ? MF_FAILED : MF_DELAYED; 1153 folio_unlock(folio); 1154 1155 if (ret == MF_DELAYED) 1156 extra_pins = true; 1157 1158 if (has_extra_refcount(ps, p, extra_pins)) 1159 ret = MF_FAILED; 1160 1161 return ret; 1162 } 1163 1164 static int me_swapcache_clean(struct page_state *ps, struct page *p) 1165 { 1166 struct folio *folio = page_folio(p); 1167 int ret; 1168 1169 swap_cache_del_folio(folio); 1170 1171 ret = delete_from_lru_cache(folio) ? MF_FAILED : MF_RECOVERED; 1172 folio_unlock(folio); 1173 1174 if (has_extra_refcount(ps, p, false)) 1175 ret = MF_FAILED; 1176 1177 return ret; 1178 } 1179 1180 /* 1181 * Huge pages. Needs work. 1182 * Issues: 1183 * - Error on hugepage is contained in hugepage unit (not in raw page unit.) 1184 * To narrow down kill region to one page, we need to break up pmd. 1185 */ 1186 static int me_huge_page(struct page_state *ps, struct page *p) 1187 { 1188 struct folio *folio = page_folio(p); 1189 int res; 1190 struct address_space *mapping; 1191 bool extra_pins = false; 1192 1193 mapping = folio_mapping(folio); 1194 if (mapping) { 1195 res = truncate_error_folio(folio, page_to_pfn(p), mapping); 1196 /* The page is kept in page cache. */ 1197 extra_pins = true; 1198 folio_unlock(folio); 1199 } else { 1200 folio_unlock(folio); 1201 /* 1202 * migration entry prevents later access on error hugepage, 1203 * so we can free and dissolve it into buddy to save healthy 1204 * subpages. 1205 */ 1206 folio_put(folio); 1207 if (__page_handle_poison(p) > 0) { 1208 page_ref_inc(p); 1209 res = MF_RECOVERED; 1210 } else { 1211 res = MF_FAILED; 1212 } 1213 } 1214 1215 if (has_extra_refcount(ps, p, extra_pins)) 1216 res = MF_FAILED; 1217 1218 return res; 1219 } 1220 1221 /* 1222 * Various page states we can handle. 1223 * 1224 * A page state is defined by its current page->flags bits. 1225 * The table matches them in order and calls the right handler. 1226 * 1227 * This is quite tricky because we can access page at any time 1228 * in its live cycle, so all accesses have to be extremely careful. 1229 * 1230 * This is not complete. More states could be added. 1231 * For any missing state don't attempt recovery. 1232 */ 1233 1234 #define dirty (1UL << PG_dirty) 1235 #define sc ((1UL << PG_swapcache) | (1UL << PG_swapbacked)) 1236 #define unevict (1UL << PG_unevictable) 1237 #define mlock (1UL << PG_mlocked) 1238 #define lru (1UL << PG_lru) 1239 #define head (1UL << PG_head) 1240 1241 static struct page_state error_states[] = { 1242 /* 1243 * free pages are specially detected outside this table: 1244 * PG_buddy pages only make a small fraction of all free pages. 1245 */ 1246 1247 { head, head, MF_MSG_HUGE, me_huge_page }, 1248 1249 { sc|dirty, sc|dirty, MF_MSG_DIRTY_SWAPCACHE, me_swapcache_dirty }, 1250 { sc|dirty, sc, MF_MSG_CLEAN_SWAPCACHE, me_swapcache_clean }, 1251 1252 { mlock|dirty, mlock|dirty, MF_MSG_DIRTY_MLOCKED_LRU, me_pagecache_dirty }, 1253 { mlock|dirty, mlock, MF_MSG_CLEAN_MLOCKED_LRU, me_pagecache_clean }, 1254 1255 { unevict|dirty, unevict|dirty, MF_MSG_DIRTY_UNEVICTABLE_LRU, me_pagecache_dirty }, 1256 { unevict|dirty, unevict, MF_MSG_CLEAN_UNEVICTABLE_LRU, me_pagecache_clean }, 1257 1258 { lru|dirty, lru|dirty, MF_MSG_DIRTY_LRU, me_pagecache_dirty }, 1259 { lru|dirty, lru, MF_MSG_CLEAN_LRU, me_pagecache_clean }, 1260 1261 /* 1262 * Catchall entry: must be at end. 1263 */ 1264 { 0, 0, MF_MSG_UNKNOWN, me_unknown }, 1265 }; 1266 1267 #undef dirty 1268 #undef sc 1269 #undef unevict 1270 #undef mlock 1271 #undef lru 1272 #undef head 1273 1274 static void update_per_node_mf_stats(unsigned long pfn, 1275 enum mf_result result) 1276 { 1277 int nid = MAX_NUMNODES; 1278 struct memory_failure_stats *mf_stats = NULL; 1279 1280 nid = pfn_to_nid(pfn); 1281 if (unlikely(nid < 0 || nid >= MAX_NUMNODES)) { 1282 WARN_ONCE(1, "Memory failure: pfn=%#lx, invalid nid=%d", pfn, nid); 1283 return; 1284 } 1285 1286 mf_stats = &NODE_DATA(nid)->mf_stats; 1287 switch (result) { 1288 case MF_IGNORED: 1289 ++mf_stats->ignored; 1290 break; 1291 case MF_FAILED: 1292 ++mf_stats->failed; 1293 break; 1294 case MF_DELAYED: 1295 ++mf_stats->delayed; 1296 break; 1297 case MF_RECOVERED: 1298 ++mf_stats->recovered; 1299 break; 1300 default: 1301 WARN_ONCE(1, "Memory failure: mf_result=%d is not properly handled", result); 1302 break; 1303 } 1304 ++mf_stats->total; 1305 } 1306 1307 static bool panic_on_unrecoverable_mf(enum mf_action_page_type type, 1308 enum mf_result result) 1309 { 1310 if (!sysctl_panic_on_unrecoverable_mf) 1311 return false; 1312 1313 return type == MF_MSG_KERNEL && result == MF_IGNORED; 1314 } 1315 1316 /* 1317 * "Dirty/Clean" indication is not 100% accurate due to the possibility of 1318 * setting PG_dirty outside page lock. See also comment above set_page_dirty(). 1319 */ 1320 static int action_result(unsigned long pfn, enum mf_action_page_type type, 1321 enum mf_result result) 1322 { 1323 trace_memory_failure_event(pfn, type, result); 1324 1325 if (type != MF_MSG_ALREADY_POISONED && type != MF_MSG_PFN_MAP) { 1326 num_poisoned_pages_inc(pfn); 1327 update_per_node_mf_stats(pfn, result); 1328 } 1329 1330 pr_err("%#lx: recovery action for %s: %s\n", 1331 pfn, action_page_types[type], action_name[result]); 1332 1333 if (panic_on_unrecoverable_mf(type, result)) 1334 panic("Memory failure: %#lx: unrecoverable page", pfn); 1335 1336 return (result == MF_RECOVERED || result == MF_DELAYED) ? 0 : -EBUSY; 1337 } 1338 1339 static int page_action(struct page_state *ps, struct page *p, 1340 unsigned long pfn) 1341 { 1342 int result; 1343 1344 /* page p should be unlocked after returning from ps->action(). */ 1345 result = ps->action(ps, p); 1346 1347 /* Could do more checks here if page looks ok */ 1348 /* 1349 * Could adjust zone counters here to correct for the missing page. 1350 */ 1351 1352 return action_result(pfn, ps->type, result); 1353 } 1354 1355 static inline bool PageHWPoisonTakenOff(struct page *page) 1356 { 1357 return PageHWPoison(page) && page_private(page) == MAGIC_HWPOISON; 1358 } 1359 1360 void SetPageHWPoisonTakenOff(struct page *page) 1361 { 1362 set_page_private(page, MAGIC_HWPOISON); 1363 } 1364 1365 void ClearPageHWPoisonTakenOff(struct page *page) 1366 { 1367 if (PageHWPoison(page)) 1368 set_page_private(page, 0); 1369 } 1370 1371 /* 1372 * Return true if a page type of a given page is supported by hwpoison 1373 * mechanism (while handling could fail), otherwise false. This function 1374 * does not return true for hugetlb or device memory pages, so it's assumed 1375 * to be called only in the context where we never have such pages. 1376 */ 1377 static inline bool HWPoisonHandlable(struct page *page, unsigned long flags) 1378 { 1379 if (PageSlab(page)) 1380 return false; 1381 1382 /* Soft offline could migrate movable_ops pages */ 1383 if ((flags & MF_SOFT_OFFLINE) && page_has_movable_ops(page)) 1384 return true; 1385 1386 return PageLRU(page) || is_free_buddy_page(page); 1387 } 1388 1389 /* 1390 * Positive identification of pages the hwpoison handler cannot recover: 1391 * pages owned by kernel internals with no userspace mapping to unmap, no 1392 * file mapping to invalidate, and no migration target. 1393 */ 1394 static inline bool is_kernel_owned_page(struct page *page) 1395 { 1396 struct page *head; 1397 bool kernel_owned; 1398 1399 /* PG_reserved is a per-page flag, never set on a compound page. */ 1400 if (PageReserved(page)) 1401 return true; 1402 1403 /* 1404 * Page-type bits live only on the head page, so resolve any tail 1405 * first. The check takes no refcount; recheck the head afterwards 1406 * so a concurrent split or compound free cannot leave us trusting 1407 * a stale view. A residual free->alloc->free cannot be closed here 1408 * (frozen slab and large-kmalloc pages cannot be pinned), but is 1409 * harmless: where a wrong verdict could panic, memory_failure() has 1410 * already set PageHWPoison, which bars the page from the allocator. 1411 */ 1412 retry: 1413 head = compound_head(page); 1414 kernel_owned = PageSlab(head) || PageTable(head) || 1415 PageLargeKmalloc(head); 1416 if (head != compound_head(page)) 1417 goto retry; 1418 return kernel_owned; 1419 } 1420 1421 static int __get_hwpoison_page(struct page *page, unsigned long flags) 1422 { 1423 struct folio *folio = page_folio(page); 1424 int ret = 0; 1425 bool hugetlb = false; 1426 1427 ret = get_hwpoison_hugetlb_folio(folio, &hugetlb, false); 1428 if (hugetlb) { 1429 /* Make sure hugetlb demotion did not happen from under us. */ 1430 if (folio == page_folio(page)) 1431 return ret; 1432 if (ret > 0) { 1433 folio_put(folio); 1434 folio = page_folio(page); 1435 } 1436 } 1437 1438 /* 1439 * This check prevents from calling folio_try_get() for any 1440 * unsupported type of folio in order to reduce the risk of unexpected 1441 * races caused by taking a folio refcount. 1442 */ 1443 if (!HWPoisonHandlable(&folio->page, flags)) 1444 return -EBUSY; 1445 1446 if (folio_try_get(folio)) { 1447 if (folio == page_folio(page)) 1448 return 1; 1449 1450 pr_info("%#lx cannot catch tail\n", page_to_pfn(page)); 1451 folio_put(folio); 1452 } 1453 1454 return 0; 1455 } 1456 1457 #define GET_PAGE_MAX_RETRY_NUM 3 1458 1459 static int get_any_page(struct page *p, unsigned long flags) 1460 { 1461 int ret = 0, pass = 0; 1462 bool count_increased = false; 1463 1464 if (flags & MF_COUNT_INCREASED) 1465 count_increased = true; 1466 1467 /* 1468 * Page types we know are kernel-owned and cannot be recovered. 1469 * Short-circuit before the shake_page() / retry loop, which 1470 * cannot turn any of these into something HWPoisonHandlable(). 1471 * Drop the caller's reference if MF_COUNT_INCREASED took one. 1472 */ 1473 if (is_kernel_owned_page(p)) { 1474 if (count_increased) 1475 put_page(p); 1476 ret = -ENOTRECOVERABLE; 1477 goto out; 1478 } 1479 1480 try_again: 1481 if (!count_increased) { 1482 ret = __get_hwpoison_page(p, flags); 1483 if (!ret) { 1484 if (page_count(p)) { 1485 /* We raced with an allocation, retry. */ 1486 if (pass++ < GET_PAGE_MAX_RETRY_NUM) 1487 goto try_again; 1488 ret = -EBUSY; 1489 } else if (!PageHuge(p) && !is_free_buddy_page(p)) { 1490 /* We raced with put_page, retry. */ 1491 if (pass++ < GET_PAGE_MAX_RETRY_NUM) 1492 goto try_again; 1493 ret = -EIO; 1494 } 1495 goto out; 1496 } else if (ret == -EBUSY) { 1497 /* 1498 * We raced with (possibly temporary) unhandlable 1499 * page, retry. 1500 */ 1501 if (pass++ < GET_PAGE_MAX_RETRY_NUM) { 1502 shake_page(p); 1503 goto try_again; 1504 } 1505 ret = -EIO; 1506 goto out; 1507 } 1508 } 1509 1510 if (PageHuge(p) || HWPoisonHandlable(p, flags)) { 1511 ret = 1; 1512 } else { 1513 /* 1514 * A page we cannot handle. Check whether we can turn 1515 * it into something we can handle. 1516 */ 1517 if (pass++ < GET_PAGE_MAX_RETRY_NUM) { 1518 put_page(p); 1519 shake_page(p); 1520 count_increased = false; 1521 goto try_again; 1522 } 1523 put_page(p); 1524 ret = -EIO; 1525 } 1526 out: 1527 if (ret == -EIO || ret == -ENOTRECOVERABLE) 1528 pr_err("%#lx: unhandlable page.\n", page_to_pfn(p)); 1529 1530 return ret; 1531 } 1532 1533 static int __get_unpoison_page(struct page *page) 1534 { 1535 struct folio *folio = page_folio(page); 1536 int ret = 0; 1537 bool hugetlb = false; 1538 1539 ret = get_hwpoison_hugetlb_folio(folio, &hugetlb, true); 1540 if (hugetlb) { 1541 /* Make sure hugetlb demotion did not happen from under us. */ 1542 if (folio == page_folio(page)) 1543 return ret; 1544 if (ret > 0) 1545 folio_put(folio); 1546 } 1547 1548 /* 1549 * PageHWPoisonTakenOff pages are not only marked as PG_hwpoison, 1550 * but also isolated from buddy freelist, so need to identify the 1551 * state and have to cancel both operations to unpoison. 1552 */ 1553 if (PageHWPoisonTakenOff(page)) 1554 return -EHWPOISON; 1555 1556 return get_page_unless_zero(page) ? 1 : 0; 1557 } 1558 1559 /** 1560 * get_hwpoison_page() - Get refcount for memory error handling 1561 * @p: Raw error page (hit by memory error) 1562 * @flags: Flags controlling behavior of error handling 1563 * 1564 * get_hwpoison_page() takes a page refcount of an error page to handle memory 1565 * error on it, after checking that the error page is in a well-defined state 1566 * (defined as a page-type we can successfully handle the memory error on it, 1567 * such as LRU page and hugetlb page). 1568 * 1569 * Memory error handling could be triggered at any time on any type of page, 1570 * so it's prone to race with typical memory management lifecycle (like 1571 * allocation and free). So to avoid such races, get_hwpoison_page() takes 1572 * extra care for the error page's state (as done in __get_hwpoison_page()), 1573 * and has some retry logic in get_any_page(). 1574 * 1575 * When called from unpoison_memory(), the caller should already ensure that 1576 * the given page has PG_hwpoison. So it's never reused for other page 1577 * allocations, and __get_unpoison_page() never races with them. 1578 * 1579 * Return: 0 on failure or free buddy (hugetlb) page, 1580 * 1 on success for in-use pages in a well-defined state, 1581 * -EIO for pages on which we can not handle memory errors, 1582 * -EBUSY when get_hwpoison_page() has raced with page lifecycle 1583 * operations like allocation and free, 1584 * -EHWPOISON when the page is hwpoisoned and taken off from buddy, 1585 * -ENOTRECOVERABLE for kernel-owned pages identified by 1586 * is_kernel_owned_page() (PG_reserved, slab, 1587 * page-table, large-kmalloc) that the handler cannot recover. 1588 */ 1589 static int get_hwpoison_page(struct page *p, unsigned long flags) 1590 { 1591 int ret; 1592 1593 zone_pcp_disable(page_zone(p)); 1594 if (flags & MF_UNPOISON) 1595 ret = __get_unpoison_page(p); 1596 else 1597 ret = get_any_page(p, flags); 1598 zone_pcp_enable(page_zone(p)); 1599 1600 return ret; 1601 } 1602 1603 /* 1604 * The caller must guarantee the folio isn't large folio, except hugetlb. 1605 * try_to_unmap() can't handle it. 1606 */ 1607 int unmap_poisoned_folio(struct folio *folio, unsigned long pfn, bool must_kill) 1608 { 1609 enum ttu_flags ttu = TTU_IGNORE_MLOCK | TTU_SYNC | TTU_HWPOISON; 1610 struct address_space *mapping; 1611 1612 if (folio_test_swapcache(folio)) { 1613 pr_err("%#lx: keeping poisoned page in swap cache\n", pfn); 1614 ttu &= ~TTU_HWPOISON; 1615 } 1616 1617 /* 1618 * Propagate the dirty bit from PTEs to struct page first, because we 1619 * need this to decide if we should kill or just drop the page. 1620 * XXX: the dirty test could be racy: set_page_dirty() may not always 1621 * be called inside page lock (it's recommended but not enforced). 1622 */ 1623 mapping = folio_mapping(folio); 1624 if (!must_kill && !folio_test_dirty(folio) && mapping && 1625 mapping_can_writeback(mapping)) { 1626 if (folio_mkclean(folio)) { 1627 folio_set_dirty(folio); 1628 } else { 1629 ttu &= ~TTU_HWPOISON; 1630 pr_info("%#lx: corrupted page was clean: dropped without side effects\n", 1631 pfn); 1632 } 1633 } 1634 1635 if (folio_test_hugetlb(folio) && !folio_test_anon(folio)) { 1636 /* 1637 * For hugetlb folios in shared mappings, try_to_unmap 1638 * could potentially call huge_pmd_unshare. Because of 1639 * this, take semaphore in write mode here and set 1640 * TTU_RMAP_LOCKED to indicate we have taken the lock 1641 * at this higher level. 1642 */ 1643 mapping = hugetlb_folio_mapping_lock_write(folio); 1644 if (!mapping) { 1645 pr_info("%#lx: could not lock mapping for mapped hugetlb folio\n", 1646 folio_pfn(folio)); 1647 return -EBUSY; 1648 } 1649 1650 try_to_unmap(folio, ttu|TTU_RMAP_LOCKED); 1651 i_mmap_unlock_write(mapping); 1652 } else { 1653 try_to_unmap(folio, ttu); 1654 } 1655 1656 return folio_mapped(folio) ? -EBUSY : 0; 1657 } 1658 1659 /* 1660 * Do all that is necessary to remove user space mappings. Unmap 1661 * the pages and send SIGBUS to the processes if the data was dirty. 1662 */ 1663 static bool hwpoison_user_mappings(struct folio *folio, struct page *p, 1664 unsigned long pfn, int flags) 1665 { 1666 LIST_HEAD(tokill); 1667 bool unmap_success; 1668 bool forcekill; 1669 bool mlocked = folio_test_mlocked(folio); 1670 1671 /* 1672 * Here we are interested only in user-mapped pages, so skip any 1673 * other types of pages. 1674 */ 1675 if (folio_test_reserved(folio) || folio_test_slab(folio) || 1676 folio_test_pgtable(folio) || folio_test_offline(folio)) 1677 return true; 1678 if (!(folio_test_lru(folio) || folio_test_hugetlb(folio))) 1679 return true; 1680 1681 /* 1682 * This check implies we don't kill processes if their pages 1683 * are in the swap cache early. Those are always late kills. 1684 */ 1685 if (!folio_mapped(folio)) 1686 return true; 1687 1688 /* 1689 * First collect all the processes that have the page 1690 * mapped in dirty form. This has to be done before try_to_unmap, 1691 * because ttu takes the rmap data structures down. 1692 */ 1693 collect_procs(folio, p, &tokill, flags & MF_ACTION_REQUIRED); 1694 1695 unmap_success = !unmap_poisoned_folio(folio, pfn, flags & MF_MUST_KILL); 1696 if (!unmap_success) 1697 pr_err("%#lx: failed to unmap page (folio mapcount=%d)\n", 1698 pfn, folio_mapcount(folio)); 1699 1700 /* 1701 * try_to_unmap() might put mlocked page in lru cache, so call 1702 * shake_page() again to ensure that it's flushed. 1703 */ 1704 if (mlocked) 1705 shake_folio(folio); 1706 1707 /* 1708 * Now that the dirty bit has been propagated to the 1709 * struct page and all unmaps done we can decide if 1710 * killing is needed or not. Only kill when the page 1711 * was dirty or the process is not restartable, 1712 * otherwise the tokill list is merely 1713 * freed. When there was a problem unmapping earlier 1714 * use a more force-full uncatchable kill to prevent 1715 * any accesses to the poisoned memory. 1716 */ 1717 forcekill = folio_test_dirty(folio) || (flags & MF_MUST_KILL) || 1718 !unmap_success; 1719 kill_procs(&tokill, forcekill, pfn, flags); 1720 1721 return unmap_success; 1722 } 1723 1724 static int identify_page_state(unsigned long pfn, struct page *p, 1725 unsigned long page_flags) 1726 { 1727 struct page_state *ps; 1728 1729 /* 1730 * The first check uses the current page flags which may not have any 1731 * relevant information. The second check with the saved page flags is 1732 * carried out only if the first check can't determine the page status. 1733 */ 1734 for (ps = error_states;; ps++) 1735 if ((p->flags.f & ps->mask) == ps->res) 1736 break; 1737 1738 page_flags |= (p->flags.f & (1UL << PG_dirty)); 1739 1740 if (!ps->mask) 1741 for (ps = error_states;; ps++) 1742 if ((page_flags & ps->mask) == ps->res) 1743 break; 1744 return page_action(ps, p, pfn); 1745 } 1746 1747 /* 1748 * When 'release' is 'false', it means that if thp split has failed, 1749 * there is still more to do, hence the page refcount we took earlier 1750 * is still needed. 1751 */ 1752 static int try_to_split_thp_page(struct page *page, unsigned int new_order, 1753 bool release) 1754 { 1755 int ret; 1756 1757 lock_page(page); 1758 ret = split_huge_page_to_order(page, new_order); 1759 unlock_page(page); 1760 1761 if (ret && release) 1762 put_page(page); 1763 1764 return ret; 1765 } 1766 1767 static void unmap_and_kill(struct list_head *to_kill, unsigned long pfn, 1768 struct address_space *mapping, pgoff_t index, int flags) 1769 { 1770 struct to_kill *tk; 1771 unsigned long size = 0; 1772 1773 list_for_each_entry(tk, to_kill, nd) 1774 if (tk->size_shift) 1775 size = max(size, 1UL << tk->size_shift); 1776 1777 if (size) { 1778 /* 1779 * Unmap the largest mapping to avoid breaking up device-dax 1780 * mappings which are constant size. The actual size of the 1781 * mapping being torn down is communicated in siginfo, see 1782 * kill_proc() 1783 */ 1784 loff_t start = ((loff_t)index << PAGE_SHIFT) & ~(size - 1); 1785 1786 unmap_mapping_range(mapping, start, size, 0); 1787 } 1788 1789 kill_procs(to_kill, !!(flags & MF_MUST_KILL), pfn, flags); 1790 } 1791 1792 /* 1793 * Only dev_pagemap pages get here, such as fsdax when the filesystem 1794 * either do not claim or fails to claim a hwpoison event, or devdax. 1795 * The fsdax pages are initialized per base page, and the devdax pages 1796 * could be initialized either as base pages, or as compound pages with 1797 * vmemmap optimization enabled. Devdax is simplistic in its dealing with 1798 * hwpoison, such that, if a subpage of a compound page is poisoned, 1799 * simply mark the compound head page is by far sufficient. 1800 */ 1801 static int mf_generic_kill_procs(unsigned long long pfn, int flags, 1802 struct dev_pagemap *pgmap) 1803 { 1804 struct folio *folio = pfn_folio(pfn); 1805 LIST_HEAD(to_kill); 1806 dax_entry_t cookie; 1807 int rc = 0; 1808 1809 /* 1810 * Prevent the inode from being freed while we are interrogating 1811 * the address_space, typically this would be handled by 1812 * lock_page(), but dax pages do not use the page lock. This 1813 * also prevents changes to the mapping of this pfn until 1814 * poison signaling is complete. 1815 */ 1816 cookie = dax_lock_folio(folio); 1817 if (!cookie) 1818 return -EBUSY; 1819 1820 if (hwpoison_filter(&folio->page)) { 1821 rc = -EOPNOTSUPP; 1822 goto unlock; 1823 } 1824 1825 switch (pgmap->type) { 1826 case MEMORY_DEVICE_PRIVATE: 1827 case MEMORY_DEVICE_COHERENT: 1828 /* 1829 * TODO: Handle device pages which may need coordination 1830 * with device-side memory. 1831 */ 1832 rc = -ENXIO; 1833 goto unlock; 1834 default: 1835 break; 1836 } 1837 1838 /* 1839 * Use this flag as an indication that the dax page has been 1840 * remapped UC to prevent speculative consumption of poison. 1841 */ 1842 SetPageHWPoison(&folio->page); 1843 1844 /* 1845 * Unlike System-RAM there is no possibility to swap in a 1846 * different physical page at a given virtual address, so all 1847 * userspace consumption of ZONE_DEVICE memory necessitates 1848 * SIGBUS (i.e. MF_MUST_KILL) 1849 */ 1850 flags |= MF_ACTION_REQUIRED | MF_MUST_KILL; 1851 collect_procs(folio, &folio->page, &to_kill, true); 1852 1853 unmap_and_kill(&to_kill, pfn, folio->mapping, folio->index, flags); 1854 unlock: 1855 dax_unlock_folio(folio, cookie); 1856 return rc; 1857 } 1858 1859 #ifdef CONFIG_FS_DAX 1860 /** 1861 * mf_dax_kill_procs - Collect and kill processes who are using this file range 1862 * @mapping: address_space of the file in use 1863 * @index: start pgoff of the range within the file 1864 * @count: length of the range, in unit of PAGE_SIZE 1865 * @mf_flags: memory failure flags 1866 */ 1867 int mf_dax_kill_procs(struct address_space *mapping, pgoff_t index, 1868 unsigned long count, int mf_flags) 1869 { 1870 LIST_HEAD(to_kill); 1871 dax_entry_t cookie; 1872 struct page *page; 1873 size_t end = index + count; 1874 bool pre_remove = mf_flags & MF_MEM_PRE_REMOVE; 1875 1876 mf_flags |= MF_ACTION_REQUIRED | MF_MUST_KILL; 1877 1878 for (; index < end; index++) { 1879 page = NULL; 1880 cookie = dax_lock_mapping_entry(mapping, index, &page); 1881 if (!cookie) 1882 return -EBUSY; 1883 if (!page) 1884 goto unlock; 1885 1886 if (!pre_remove) 1887 SetPageHWPoison(page); 1888 1889 /* 1890 * The pre_remove case is revoking access, the memory is still 1891 * good and could theoretically be put back into service. 1892 */ 1893 collect_procs_fsdax(page, mapping, index, &to_kill, pre_remove); 1894 unmap_and_kill(&to_kill, page_to_pfn(page), mapping, 1895 index, mf_flags); 1896 unlock: 1897 dax_unlock_mapping_entry(mapping, index, cookie); 1898 } 1899 return 0; 1900 } 1901 EXPORT_SYMBOL_GPL(mf_dax_kill_procs); 1902 #endif /* CONFIG_FS_DAX */ 1903 1904 #ifdef CONFIG_HUGETLB_PAGE 1905 1906 /* 1907 * Struct raw_hwp_page represents information about "raw error page", 1908 * constructing singly linked list from ->_hugetlb_hwpoison field of folio. 1909 */ 1910 struct raw_hwp_page { 1911 struct llist_node node; 1912 struct page *page; 1913 }; 1914 1915 static inline struct llist_head *raw_hwp_list_head(struct folio *folio) 1916 { 1917 return (struct llist_head *)&folio->_hugetlb_hwpoison; 1918 } 1919 1920 bool is_raw_hwpoison_page_in_hugepage(struct page *page) 1921 { 1922 struct llist_head *raw_hwp_head; 1923 struct raw_hwp_page *p; 1924 struct folio *folio = page_folio(page); 1925 bool ret = false; 1926 1927 if (!folio_test_hwpoison(folio)) 1928 return false; 1929 1930 if (!folio_test_hugetlb(folio)) 1931 return PageHWPoison(page); 1932 1933 /* 1934 * When RawHwpUnreliable is set, kernel lost track of which subpages 1935 * are HWPOISON. So return as if ALL subpages are HWPOISONed. 1936 */ 1937 if (folio_test_hugetlb_raw_hwp_unreliable(folio)) 1938 return true; 1939 1940 mutex_lock(&mf_mutex); 1941 1942 raw_hwp_head = raw_hwp_list_head(folio); 1943 llist_for_each_entry(p, raw_hwp_head->first, node) { 1944 if (page == p->page) { 1945 ret = true; 1946 break; 1947 } 1948 } 1949 1950 mutex_unlock(&mf_mutex); 1951 1952 return ret; 1953 } 1954 1955 static unsigned long __folio_free_raw_hwp(struct folio *folio, bool move_flag) 1956 { 1957 struct llist_node *head; 1958 struct raw_hwp_page *p, *next; 1959 unsigned long count = 0; 1960 1961 head = llist_del_all(raw_hwp_list_head(folio)); 1962 llist_for_each_entry_safe(p, next, head, node) { 1963 if (move_flag) 1964 SetPageHWPoison(p->page); 1965 else 1966 num_poisoned_pages_sub(page_to_pfn(p->page), 1); 1967 kfree(p); 1968 count++; 1969 } 1970 return count; 1971 } 1972 1973 #define MF_HUGETLB_FREED 0 /* freed hugepage */ 1974 #define MF_HUGETLB_IN_USED 1 /* in-use hugepage */ 1975 #define MF_HUGETLB_NON_HUGEPAGE 2 /* not a hugepage */ 1976 #define MF_HUGETLB_FOLIO_PRE_POISONED 3 /* folio already poisoned */ 1977 #define MF_HUGETLB_PAGE_PRE_POISONED 4 /* exact page already poisoned */ 1978 #define MF_HUGETLB_RETRY 5 /* hugepage is busy, retry */ 1979 /* 1980 * Set hugetlb folio as hwpoisoned, update folio private raw hwpoison list 1981 * to keep track of the poisoned pages. 1982 */ 1983 static int hugetlb_update_hwpoison(struct folio *folio, struct page *page) 1984 { 1985 struct llist_head *head; 1986 struct raw_hwp_page *raw_hwp; 1987 struct raw_hwp_page *p; 1988 int ret = folio_test_set_hwpoison(folio) ? MF_HUGETLB_FOLIO_PRE_POISONED : 0; 1989 1990 /* 1991 * Once the hwpoison hugepage has lost reliable raw error info, 1992 * there is little meaning to keep additional error info precisely, 1993 * so skip to add additional raw error info. 1994 */ 1995 if (folio_test_hugetlb_raw_hwp_unreliable(folio)) 1996 return MF_HUGETLB_FOLIO_PRE_POISONED; 1997 head = raw_hwp_list_head(folio); 1998 llist_for_each_entry(p, head->first, node) { 1999 if (p->page == page) 2000 return MF_HUGETLB_PAGE_PRE_POISONED; 2001 } 2002 2003 raw_hwp = kmalloc_obj(struct raw_hwp_page, GFP_ATOMIC); 2004 if (raw_hwp) { 2005 raw_hwp->page = page; 2006 llist_add(&raw_hwp->node, head); 2007 } else { 2008 /* 2009 * Failed to save raw error info. We no longer trace all 2010 * hwpoisoned subpages, and we need refuse to free/dissolve 2011 * this hwpoisoned hugepage. 2012 */ 2013 folio_set_hugetlb_raw_hwp_unreliable(folio); 2014 /* 2015 * Once hugetlb_raw_hwp_unreliable is set, raw_hwp_page is not 2016 * used any more, so free it. 2017 */ 2018 __folio_free_raw_hwp(folio, false); 2019 } 2020 return ret; 2021 } 2022 2023 static unsigned long folio_free_raw_hwp(struct folio *folio, bool move_flag) 2024 { 2025 /* 2026 * hugetlb_vmemmap_optimized hugepages can't be freed because struct 2027 * pages for tail pages are required but they don't exist. 2028 */ 2029 if (move_flag && folio_test_hugetlb_vmemmap_optimized(folio)) 2030 return 0; 2031 2032 /* 2033 * hugetlb_raw_hwp_unreliable hugepages shouldn't be unpoisoned by 2034 * definition. 2035 */ 2036 if (folio_test_hugetlb_raw_hwp_unreliable(folio)) 2037 return 0; 2038 2039 return __folio_free_raw_hwp(folio, move_flag); 2040 } 2041 2042 void folio_clear_hugetlb_hwpoison(struct folio *folio) 2043 { 2044 if (folio_test_hugetlb_raw_hwp_unreliable(folio)) 2045 return; 2046 if (folio_test_hugetlb_vmemmap_optimized(folio)) 2047 return; 2048 folio_clear_hwpoison(folio); 2049 folio_free_raw_hwp(folio, true); 2050 } 2051 2052 static int get_huge_page_for_hwpoison(unsigned long pfn, int flags, 2053 bool *migratable_cleared) 2054 { 2055 struct page *page = pfn_to_page(pfn); 2056 struct folio *folio; 2057 bool count_increased = false; 2058 int ret, rc; 2059 2060 spin_lock_irq(&hugetlb_lock); 2061 folio = page_folio(page); 2062 if (!folio_test_hugetlb(folio)) { 2063 ret = MF_HUGETLB_NON_HUGEPAGE; 2064 goto out_unlock; 2065 } else if (flags & MF_COUNT_INCREASED) { 2066 ret = MF_HUGETLB_IN_USED; 2067 count_increased = true; 2068 } else if (folio_test_hugetlb_freed(folio)) { 2069 ret = MF_HUGETLB_FREED; 2070 } else if (folio_test_hugetlb_migratable(folio)) { 2071 if (folio_try_get(folio)) { 2072 ret = MF_HUGETLB_IN_USED; 2073 count_increased = true; 2074 } else { 2075 ret = MF_HUGETLB_FREED; 2076 } 2077 } else { 2078 ret = MF_HUGETLB_RETRY; 2079 if (!(flags & MF_NO_RETRY)) 2080 goto out_unlock; 2081 } 2082 2083 rc = hugetlb_update_hwpoison(folio, page); 2084 if (rc >= MF_HUGETLB_FOLIO_PRE_POISONED) { 2085 ret = rc; 2086 goto out_unlock; 2087 } 2088 2089 /* 2090 * Clearing hugetlb_migratable for hwpoisoned hugepages to prevent them 2091 * from being migrated by memory hotremove. 2092 */ 2093 if (count_increased && folio_test_hugetlb_migratable(folio)) { 2094 folio_clear_hugetlb_migratable(folio); 2095 *migratable_cleared = true; 2096 } 2097 2098 spin_unlock_irq(&hugetlb_lock); 2099 return ret; 2100 out_unlock: 2101 spin_unlock_irq(&hugetlb_lock); 2102 if (count_increased) 2103 folio_put(folio); 2104 return ret; 2105 } 2106 2107 /* 2108 * Taking refcount of hugetlb pages needs extra care about race conditions 2109 * with basic operations like hugepage allocation/free/demotion. 2110 * So some of prechecks for hwpoison (pinning, and testing/setting 2111 * PageHWPoison) should be done in single hugetlb_lock range. 2112 * Returns: 2113 * 0 - recovered 2114 * -ENOENT - no hugetlb page 2115 * -EBUSY - not recovered 2116 * -EOPNOTSUPP - hwpoison_filter'ed 2117 * -EHWPOISON - folio or exact page already poisoned 2118 * -EFAULT - kill_accessing_process finds current->mm null 2119 */ 2120 static int try_memory_failure_hugetlb(unsigned long pfn, int flags) 2121 { 2122 int res, rv; 2123 struct page *p = pfn_to_page(pfn); 2124 struct folio *folio; 2125 unsigned long page_flags; 2126 bool migratable_cleared = false; 2127 2128 retry: 2129 res = get_huge_page_for_hwpoison(pfn, flags, &migratable_cleared); 2130 switch (res) { 2131 case MF_HUGETLB_NON_HUGEPAGE: /* fallback to normal page handling */ 2132 return -ENOENT; 2133 case MF_HUGETLB_RETRY: 2134 if (!(flags & MF_NO_RETRY)) { 2135 flags |= MF_NO_RETRY; 2136 goto retry; 2137 } 2138 return action_result(pfn, MF_MSG_GET_HWPOISON, MF_IGNORED); 2139 case MF_HUGETLB_FOLIO_PRE_POISONED: 2140 case MF_HUGETLB_PAGE_PRE_POISONED: 2141 rv = -EHWPOISON; 2142 if (flags & MF_ACTION_REQUIRED) 2143 rv = kill_accessing_process(current, pfn, flags); 2144 if (res == MF_HUGETLB_PAGE_PRE_POISONED) 2145 action_result(pfn, MF_MSG_ALREADY_POISONED, MF_FAILED); 2146 else 2147 action_result(pfn, MF_MSG_HUGE, MF_FAILED); 2148 return rv; 2149 default: 2150 WARN_ON((res != MF_HUGETLB_FREED) && (res != MF_HUGETLB_IN_USED)); 2151 break; 2152 } 2153 2154 folio = page_folio(p); 2155 folio_lock(folio); 2156 2157 if (hwpoison_filter(p)) { 2158 folio_clear_hugetlb_hwpoison(folio); 2159 if (migratable_cleared) 2160 folio_set_hugetlb_migratable(folio); 2161 folio_unlock(folio); 2162 if (res == MF_HUGETLB_IN_USED) 2163 folio_put(folio); 2164 return -EOPNOTSUPP; 2165 } 2166 2167 /* 2168 * Handling free hugepage. The possible race with hugepage allocation 2169 * or demotion can be prevented by PageHWPoison flag. 2170 */ 2171 if (res == MF_HUGETLB_FREED) { 2172 folio_unlock(folio); 2173 if (__page_handle_poison(p) > 0) { 2174 page_ref_inc(p); 2175 res = MF_RECOVERED; 2176 } else { 2177 res = MF_FAILED; 2178 } 2179 return action_result(pfn, MF_MSG_FREE_HUGE, res); 2180 } 2181 2182 page_flags = folio->flags.f; 2183 2184 if (!hwpoison_user_mappings(folio, p, pfn, flags)) { 2185 folio_unlock(folio); 2186 return action_result(pfn, MF_MSG_UNMAP_FAILED, MF_FAILED); 2187 } 2188 2189 return identify_page_state(pfn, p, page_flags); 2190 } 2191 2192 #else 2193 static inline int try_memory_failure_hugetlb(unsigned long pfn, int flags) 2194 { 2195 return -ENOENT; 2196 } 2197 2198 static inline unsigned long folio_free_raw_hwp(struct folio *folio, bool flag) 2199 { 2200 return 0; 2201 } 2202 #endif /* CONFIG_HUGETLB_PAGE */ 2203 2204 /* Drop the extra refcount in case we come from madvise() */ 2205 static void put_ref_page(unsigned long pfn, int flags) 2206 { 2207 if (!(flags & MF_COUNT_INCREASED)) 2208 return; 2209 2210 put_page(pfn_to_page(pfn)); 2211 } 2212 2213 static int memory_failure_dev_pagemap(unsigned long pfn, int flags, 2214 struct dev_pagemap *pgmap) 2215 { 2216 int rc = -ENXIO; 2217 2218 /* device metadata space is not recoverable */ 2219 if (!pgmap_pfn_valid(pgmap, pfn)) 2220 goto out; 2221 2222 /* 2223 * Call driver's implementation to handle the memory failure, otherwise 2224 * fall back to generic handler. 2225 */ 2226 if (pgmap_has_memory_failure(pgmap)) { 2227 rc = pgmap->ops->memory_failure(pgmap, pfn, 1, flags); 2228 /* 2229 * Fall back to generic handler too if operation is not 2230 * supported inside the driver/device/filesystem. 2231 */ 2232 if (rc != -EOPNOTSUPP) 2233 goto out; 2234 } 2235 2236 rc = mf_generic_kill_procs(pfn, flags, pgmap); 2237 out: 2238 /* drop pgmap ref acquired in caller */ 2239 put_dev_pagemap(pgmap); 2240 if (rc != -EOPNOTSUPP) 2241 action_result(pfn, MF_MSG_DAX, rc ? MF_FAILED : MF_RECOVERED); 2242 return rc; 2243 } 2244 2245 /* 2246 * The calling condition is as such: thp split failed, page might have 2247 * been RDMA pinned, not much can be done for recovery. 2248 * But a SIGBUS should be delivered with vaddr provided so that the user 2249 * application has a chance to recover. Also, application processes' 2250 * election for MCE early killed will be honored. 2251 */ 2252 static void kill_procs_now(struct page *p, unsigned long pfn, int flags, 2253 struct folio *folio) 2254 { 2255 LIST_HEAD(tokill); 2256 2257 folio_lock(folio); 2258 collect_procs(folio, p, &tokill, flags & MF_ACTION_REQUIRED); 2259 folio_unlock(folio); 2260 2261 kill_procs(&tokill, true, pfn, flags); 2262 } 2263 2264 int register_pfn_address_space(struct pfn_address_space *pfn_space) 2265 { 2266 guard(mutex)(&pfn_space_lock); 2267 2268 if (!pfn_space->pfn_to_vma_pgoff) 2269 return -EINVAL; 2270 2271 if (interval_tree_iter_first(&pfn_space_itree, 2272 pfn_space->node.start, 2273 pfn_space->node.last)) 2274 return -EBUSY; 2275 2276 interval_tree_insert(&pfn_space->node, &pfn_space_itree); 2277 2278 return 0; 2279 } 2280 EXPORT_SYMBOL_GPL(register_pfn_address_space); 2281 2282 void unregister_pfn_address_space(struct pfn_address_space *pfn_space) 2283 { 2284 guard(mutex)(&pfn_space_lock); 2285 2286 if (interval_tree_iter_first(&pfn_space_itree, 2287 pfn_space->node.start, 2288 pfn_space->node.last)) 2289 interval_tree_remove(&pfn_space->node, &pfn_space_itree); 2290 } 2291 EXPORT_SYMBOL_GPL(unregister_pfn_address_space); 2292 2293 static void add_to_kill_pgoff(struct task_struct *tsk, 2294 struct vm_area_struct *vma, 2295 struct list_head *to_kill, 2296 pgoff_t pgoff) 2297 { 2298 struct to_kill *tk; 2299 2300 tk = kmalloc_obj(*tk, GFP_ATOMIC); 2301 if (!tk) { 2302 pr_info("Unable to kill proc %d\n", tsk->pid); 2303 return; 2304 } 2305 2306 /* Check for pgoff not backed by struct page */ 2307 tk->addr = vma_filebacked_address(vma, pgoff, 1); 2308 tk->size_shift = PAGE_SHIFT; 2309 2310 if (tk->addr == -EFAULT) 2311 pr_info("Unable to find address %lx in %s\n", 2312 pgoff, tsk->comm); 2313 2314 get_task_struct(tsk); 2315 tk->tsk = tsk; 2316 list_add_tail(&tk->nd, to_kill); 2317 } 2318 2319 /* 2320 * Collect processes when the error hit a PFN not backed by struct page. 2321 */ 2322 static void collect_procs_pfn(struct pfn_address_space *pfn_space, 2323 unsigned long pfn, struct list_head *to_kill) 2324 { 2325 struct vm_area_struct *vma; 2326 struct task_struct *tsk; 2327 struct address_space *mapping = pfn_space->mapping; 2328 2329 i_mmap_lock_read(mapping); 2330 rcu_read_lock(); 2331 for_each_process(tsk) { 2332 struct task_struct *t = tsk; 2333 2334 t = task_early_kill(tsk, true); 2335 if (!t) 2336 continue; 2337 mapping_rmap_tree_foreach(vma, mapping, 0, ULONG_MAX) { 2338 pgoff_t pgoff; 2339 2340 if (vma->vm_mm == t->mm && 2341 !pfn_space->pfn_to_vma_pgoff(vma, pfn, &pgoff)) 2342 add_to_kill_pgoff(t, vma, to_kill, pgoff); 2343 } 2344 } 2345 rcu_read_unlock(); 2346 i_mmap_unlock_read(mapping); 2347 } 2348 2349 /** 2350 * memory_failure_pfn - Handle memory failure on a page not backed by 2351 * struct page. 2352 * @pfn: Page Number of the corrupted page 2353 * @flags: fine tune action taken 2354 * 2355 * Return: 2356 * 0 - success, 2357 * -EBUSY - Page PFN does not belong to any address space mapping. 2358 */ 2359 static int memory_failure_pfn(unsigned long pfn, int flags) 2360 { 2361 struct interval_tree_node *node; 2362 LIST_HEAD(tokill); 2363 2364 scoped_guard(mutex, &pfn_space_lock) { 2365 bool mf_handled = false; 2366 2367 /* 2368 * Modules registers with MM the address space mapping to 2369 * the device memory they manage. Iterate to identify 2370 * exactly which address space has mapped to this failing 2371 * PFN. 2372 */ 2373 for (node = interval_tree_iter_first(&pfn_space_itree, pfn, pfn); node; 2374 node = interval_tree_iter_next(node, pfn, pfn)) { 2375 struct pfn_address_space *pfn_space = 2376 container_of(node, struct pfn_address_space, node); 2377 2378 collect_procs_pfn(pfn_space, pfn, &tokill); 2379 2380 mf_handled = true; 2381 } 2382 2383 if (!mf_handled) 2384 return action_result(pfn, MF_MSG_PFN_MAP, MF_IGNORED); 2385 } 2386 2387 /* 2388 * Unlike System-RAM there is no possibility to swap in a different 2389 * physical page at a given virtual address, so all userspace 2390 * consumption of direct PFN memory necessitates SIGBUS (i.e. 2391 * MF_MUST_KILL) 2392 */ 2393 flags |= MF_ACTION_REQUIRED | MF_MUST_KILL; 2394 2395 kill_procs(&tokill, true, pfn, flags); 2396 2397 return action_result(pfn, MF_MSG_PFN_MAP, MF_RECOVERED); 2398 } 2399 2400 /** 2401 * memory_failure - Handle memory failure of a page. 2402 * @pfn: Page Number of the corrupted page 2403 * @flags: fine tune action taken 2404 * 2405 * This function is called by the low level machine check code 2406 * of an architecture when it detects hardware memory corruption 2407 * of a page. It tries its best to recover, which includes 2408 * dropping pages, killing processes etc. 2409 * 2410 * The function is primarily of use for corruptions that 2411 * happen outside the current execution context (e.g. when 2412 * detected by a background scrubber) 2413 * 2414 * Must run in process context (e.g. a work queue) with interrupts 2415 * enabled and no spinlocks held. 2416 * 2417 * Return: 2418 * 0 - success, 2419 * -ENXIO - memory not managed by the kernel 2420 * -EOPNOTSUPP - hwpoison_filter() filtered the error event, 2421 * -EHWPOISON - the page was already poisoned, potentially 2422 * kill process, 2423 * other negative values - failure. 2424 */ 2425 int memory_failure(unsigned long pfn, int flags) 2426 { 2427 struct page *p; 2428 struct folio *folio; 2429 struct dev_pagemap *pgmap; 2430 int res = 0; 2431 unsigned long page_flags; 2432 bool retry = true; 2433 2434 if (!sysctl_memory_failure_recovery) 2435 panic("Memory failure on page %lx", pfn); 2436 2437 mutex_lock(&mf_mutex); 2438 2439 if (!(flags & MF_SW_SIMULATED)) 2440 hw_memory_failure = true; 2441 2442 p = pfn_to_online_page(pfn); 2443 if (!p) { 2444 res = arch_memory_failure(pfn, flags); 2445 if (res == 0) 2446 goto unlock_mutex; 2447 2448 if (!pfn_valid(pfn) && !arch_is_platform_page(PFN_PHYS(pfn))) { 2449 /* 2450 * The PFN is not backed by struct page. 2451 */ 2452 res = memory_failure_pfn(pfn, flags); 2453 goto unlock_mutex; 2454 } 2455 2456 if (pfn_valid(pfn)) { 2457 pgmap = get_dev_pagemap(pfn); 2458 put_ref_page(pfn, flags); 2459 if (pgmap) { 2460 res = memory_failure_dev_pagemap(pfn, flags, 2461 pgmap); 2462 goto unlock_mutex; 2463 } 2464 } 2465 pr_err("%#lx: memory outside kernel control\n", pfn); 2466 res = -ENXIO; 2467 goto unlock_mutex; 2468 } 2469 2470 try_again: 2471 res = try_memory_failure_hugetlb(pfn, flags); 2472 /* 2473 * -ENOENT means the page we found is not hugetlb, so proceed with normal page handling 2474 */ 2475 if (res != -ENOENT) 2476 goto unlock_mutex; 2477 2478 if (TestSetPageHWPoison(p)) { 2479 res = -EHWPOISON; 2480 if (flags & MF_ACTION_REQUIRED) 2481 res = kill_accessing_process(current, pfn, flags); 2482 if (flags & MF_COUNT_INCREASED) 2483 put_page(p); 2484 action_result(pfn, MF_MSG_ALREADY_POISONED, MF_FAILED); 2485 goto unlock_mutex; 2486 } 2487 2488 /* 2489 * We need/can do nothing about count=0 pages. 2490 * 1) it's a free page, and therefore in safe hand: 2491 * check_new_page() will be the gate keeper. 2492 * 2) it's part of a non-compound high order page. 2493 * Implies some kernel user: cannot stop them from 2494 * R/W the page; let's pray that the page has been 2495 * used and will be freed some time later. 2496 * In fact it's dangerous to directly bump up page count from 0, 2497 * that may make page_ref_freeze()/page_ref_unfreeze() mismatch. 2498 */ 2499 res = get_hwpoison_page(p, flags); 2500 switch (res) { 2501 case 0: 2502 if (is_free_buddy_page(p)) { 2503 if (take_page_off_buddy(p)) { 2504 page_ref_inc(p); 2505 res = MF_RECOVERED; 2506 } else { 2507 /* We lost the race, try again */ 2508 if (retry) { 2509 ClearPageHWPoison(p); 2510 retry = false; 2511 goto try_again; 2512 } 2513 res = MF_FAILED; 2514 } 2515 res = action_result(pfn, MF_MSG_BUDDY, res); 2516 } else { 2517 res = action_result(pfn, MF_MSG_KERNEL_HIGH_ORDER, MF_IGNORED); 2518 } 2519 goto unlock_mutex; 2520 case 1: 2521 /* Got a refcount on a handlable page. */ 2522 break; 2523 case -ENOTRECOVERABLE: 2524 /* 2525 * Stable unhandlable kernel-owned page (PG_reserved, 2526 * slab, page tables, large-kmalloc). 2527 * No recovery possible. 2528 */ 2529 res = action_result(pfn, MF_MSG_KERNEL, MF_IGNORED); 2530 goto unlock_mutex; 2531 default: 2532 /* Transient lifecycle race with the page allocator. */ 2533 res = action_result(pfn, MF_MSG_GET_HWPOISON, MF_IGNORED); 2534 goto unlock_mutex; 2535 } 2536 2537 folio = page_folio(p); 2538 2539 /* filter pages that are protected from hwpoison test by users */ 2540 folio_lock(folio); 2541 if (hwpoison_filter(p)) { 2542 ClearPageHWPoison(p); 2543 folio_unlock(folio); 2544 folio_put(folio); 2545 res = -EOPNOTSUPP; 2546 goto unlock_mutex; 2547 } 2548 folio_unlock(folio); 2549 2550 if (folio_test_large(folio)) { 2551 const int new_order = min_order_for_split(folio); 2552 int err; 2553 2554 /* 2555 * The flag must be set after the refcount is bumped 2556 * otherwise it may race with THP split. 2557 * And the flag can't be set in get_hwpoison_page() since 2558 * it is called by soft offline too and it is just called 2559 * for !MF_COUNT_INCREASED. So here seems to be the best 2560 * place. 2561 * 2562 * Don't need care about the above error handling paths for 2563 * get_hwpoison_page() since they handle either free page 2564 * or unhandlable page. The refcount is bumped iff the 2565 * page is a valid handlable page. 2566 */ 2567 folio_set_has_hwpoisoned(folio); 2568 err = try_to_split_thp_page(p, new_order, /* release= */ false); 2569 /* 2570 * If splitting a folio to order-0 fails, kill the process. 2571 * Split the folio regardless to minimize unusable pages. 2572 * Because the memory failure code cannot handle large 2573 * folios, this split is always treated as if it failed. 2574 */ 2575 if (err || new_order) { 2576 /* get folio again in case the original one is split */ 2577 folio = page_folio(p); 2578 res = -EHWPOISON; 2579 kill_procs_now(p, pfn, flags, folio); 2580 put_page(p); 2581 action_result(pfn, MF_MSG_UNSPLIT_THP, MF_FAILED); 2582 goto unlock_mutex; 2583 } 2584 VM_BUG_ON_PAGE(!page_count(p), p); 2585 folio = page_folio(p); 2586 } 2587 2588 /* 2589 * We ignore non-LRU pages for good reasons. 2590 * - PG_locked is only well defined for LRU pages and a few others 2591 * - to avoid races with __SetPageLocked() 2592 * - to avoid races with __SetPageSlab*() (and more non-atomic ops) 2593 * The check (unnecessarily) ignores LRU pages being isolated and 2594 * walked by the page reclaim code, however that's not a big loss. 2595 */ 2596 shake_folio(folio); 2597 2598 folio_lock(folio); 2599 2600 /* 2601 * We're only intended to deal with the non-Compound page here. 2602 * The page cannot become compound pages again as folio has been 2603 * splited and extra refcnt is held. 2604 */ 2605 WARN_ON(folio_test_large(folio)); 2606 2607 /* 2608 * We use page flags to determine what action should be taken, but 2609 * the flags can be modified by the error containment action. One 2610 * example is an mlocked page, where PG_mlocked is cleared by 2611 * folio_remove_rmap_*() in try_to_unmap_one(). So to determine page 2612 * status correctly, we save a copy of the page flags at this time. 2613 */ 2614 page_flags = folio->flags.f; 2615 2616 /* 2617 * __munlock_folio() may clear a writeback folio's LRU flag without 2618 * the folio lock. We need to wait for writeback completion for this 2619 * folio or it may trigger a vfs BUG while evicting inode. 2620 */ 2621 if (!folio_test_lru(folio) && !folio_test_writeback(folio)) 2622 goto identify_page_state; 2623 2624 /* 2625 * It's very difficult to mess with pages currently under IO 2626 * and in many cases impossible, so we just avoid it here. 2627 */ 2628 folio_wait_writeback(folio); 2629 2630 /* 2631 * Now take care of user space mappings. 2632 * Abort on fail: __filemap_remove_folio() assumes unmapped page. 2633 */ 2634 if (!hwpoison_user_mappings(folio, p, pfn, flags)) { 2635 res = action_result(pfn, MF_MSG_UNMAP_FAILED, MF_FAILED); 2636 goto unlock_page; 2637 } 2638 2639 /* 2640 * Torn down by someone else? 2641 */ 2642 if (folio_test_lru(folio) && !folio_test_swapcache(folio) && 2643 folio->mapping == NULL) { 2644 res = action_result(pfn, MF_MSG_TRUNCATED_LRU, MF_IGNORED); 2645 goto unlock_page; 2646 } 2647 2648 identify_page_state: 2649 res = identify_page_state(pfn, p, page_flags); 2650 mutex_unlock(&mf_mutex); 2651 return res; 2652 unlock_page: 2653 folio_unlock(folio); 2654 unlock_mutex: 2655 mutex_unlock(&mf_mutex); 2656 return res; 2657 } 2658 EXPORT_SYMBOL_GPL(memory_failure); 2659 2660 #define MEMORY_FAILURE_FIFO_ORDER 4 2661 #define MEMORY_FAILURE_FIFO_SIZE (1 << MEMORY_FAILURE_FIFO_ORDER) 2662 2663 struct memory_failure_entry { 2664 unsigned long pfn; 2665 int flags; 2666 }; 2667 2668 struct memory_failure_cpu { 2669 DECLARE_KFIFO(fifo, struct memory_failure_entry, 2670 MEMORY_FAILURE_FIFO_SIZE); 2671 raw_spinlock_t lock; 2672 struct work_struct work; 2673 }; 2674 2675 static DEFINE_PER_CPU(struct memory_failure_cpu, memory_failure_cpu); 2676 2677 /** 2678 * memory_failure_queue - Schedule handling memory failure of a page. 2679 * @pfn: Page Number of the corrupted page 2680 * @flags: Flags for memory failure handling 2681 * 2682 * This function is called by the low level hardware error handler 2683 * when it detects hardware memory corruption of a page. It schedules 2684 * the recovering of error page, including dropping pages, killing 2685 * processes etc. 2686 * 2687 * The function is primarily of use for corruptions that 2688 * happen outside the current execution context (e.g. when 2689 * detected by a background scrubber) 2690 * 2691 * Can run in IRQ context. 2692 */ 2693 void memory_failure_queue(unsigned long pfn, int flags) 2694 { 2695 struct memory_failure_cpu *mf_cpu; 2696 unsigned long proc_flags; 2697 bool buffer_overflow; 2698 struct memory_failure_entry entry = { 2699 .pfn = pfn, 2700 .flags = flags, 2701 }; 2702 2703 mf_cpu = &get_cpu_var(memory_failure_cpu); 2704 raw_spin_lock_irqsave(&mf_cpu->lock, proc_flags); 2705 buffer_overflow = !kfifo_put(&mf_cpu->fifo, entry); 2706 if (!buffer_overflow) 2707 schedule_work_on(smp_processor_id(), &mf_cpu->work); 2708 raw_spin_unlock_irqrestore(&mf_cpu->lock, proc_flags); 2709 put_cpu_var(memory_failure_cpu); 2710 if (buffer_overflow) 2711 pr_err("buffer overflow when queuing memory failure at %#lx\n", 2712 pfn); 2713 } 2714 EXPORT_SYMBOL_GPL(memory_failure_queue); 2715 2716 static void memory_failure_work_func(struct work_struct *work) 2717 { 2718 struct memory_failure_cpu *mf_cpu; 2719 struct memory_failure_entry entry = { 0, }; 2720 unsigned long proc_flags; 2721 int gotten; 2722 2723 mf_cpu = container_of(work, struct memory_failure_cpu, work); 2724 for (;;) { 2725 raw_spin_lock_irqsave(&mf_cpu->lock, proc_flags); 2726 gotten = kfifo_get(&mf_cpu->fifo, &entry); 2727 raw_spin_unlock_irqrestore(&mf_cpu->lock, proc_flags); 2728 if (!gotten) 2729 break; 2730 if (entry.flags & MF_SOFT_OFFLINE) 2731 soft_offline_page(entry.pfn, entry.flags); 2732 else 2733 memory_failure(entry.pfn, entry.flags); 2734 } 2735 } 2736 2737 static int __init memory_failure_init(void) 2738 { 2739 struct memory_failure_cpu *mf_cpu; 2740 int cpu; 2741 2742 for_each_possible_cpu(cpu) { 2743 mf_cpu = &per_cpu(memory_failure_cpu, cpu); 2744 raw_spin_lock_init(&mf_cpu->lock); 2745 INIT_KFIFO(mf_cpu->fifo); 2746 INIT_WORK(&mf_cpu->work, memory_failure_work_func); 2747 } 2748 2749 register_sysctl_init("vm", memory_failure_table); 2750 2751 return 0; 2752 } 2753 core_initcall(memory_failure_init); 2754 2755 #undef pr_fmt 2756 #define pr_fmt(fmt) "Unpoison: " fmt 2757 #define unpoison_pr_info(fmt, pfn, rs) \ 2758 ({ \ 2759 if (__ratelimit(rs)) \ 2760 pr_info(fmt, pfn); \ 2761 }) 2762 2763 /** 2764 * unpoison_memory - Unpoison a previously poisoned page 2765 * @pfn: Page number of the to be unpoisoned page 2766 * 2767 * Software-unpoison a page that has been poisoned by 2768 * memory_failure() earlier. 2769 * 2770 * This is only done on the software-level, so it only works 2771 * for linux injected failures, not real hardware failures 2772 * 2773 * Returns 0 for success, otherwise -errno. 2774 */ 2775 int unpoison_memory(unsigned long pfn) 2776 { 2777 struct folio *folio; 2778 struct page *p; 2779 int ret = -EBUSY, ghp; 2780 unsigned long count; 2781 bool huge = false; 2782 static DEFINE_RATELIMIT_STATE(unpoison_rs, DEFAULT_RATELIMIT_INTERVAL, 2783 DEFAULT_RATELIMIT_BURST); 2784 2785 p = pfn_to_online_page(pfn); 2786 if (!p) 2787 return -EIO; 2788 folio = page_folio(p); 2789 2790 mutex_lock(&mf_mutex); 2791 2792 if (hw_memory_failure) { 2793 unpoison_pr_info("%#lx: disabled after HW memory failure\n", 2794 pfn, &unpoison_rs); 2795 ret = -EOPNOTSUPP; 2796 goto unlock_mutex; 2797 } 2798 2799 if (is_huge_zero_folio(folio)) { 2800 unpoison_pr_info("%#lx: huge zero page is not supported\n", 2801 pfn, &unpoison_rs); 2802 ret = -EOPNOTSUPP; 2803 goto unlock_mutex; 2804 } 2805 2806 if (!PageHWPoison(p)) { 2807 unpoison_pr_info("%#lx: page was already unpoisoned\n", 2808 pfn, &unpoison_rs); 2809 goto unlock_mutex; 2810 } 2811 2812 if (folio_ref_count(folio) > 1) { 2813 unpoison_pr_info("%#lx: someone grabs the hwpoison page\n", 2814 pfn, &unpoison_rs); 2815 goto unlock_mutex; 2816 } 2817 2818 if (folio_test_slab(folio) || folio_test_pgtable(folio) || 2819 folio_test_reserved(folio) || folio_test_offline(folio)) 2820 goto unlock_mutex; 2821 2822 if (folio_mapped(folio)) { 2823 unpoison_pr_info("%#lx: someone maps the hwpoison page\n", 2824 pfn, &unpoison_rs); 2825 goto unlock_mutex; 2826 } 2827 2828 if (folio_mapping(folio)) { 2829 unpoison_pr_info("%#lx: the hwpoison page has non-NULL mapping\n", 2830 pfn, &unpoison_rs); 2831 goto unlock_mutex; 2832 } 2833 2834 ghp = get_hwpoison_page(p, MF_UNPOISON); 2835 if (!ghp) { 2836 if (folio_test_hugetlb(folio)) { 2837 huge = true; 2838 count = folio_free_raw_hwp(folio, false); 2839 if (count == 0) 2840 goto unlock_mutex; 2841 } 2842 ret = folio_test_clear_hwpoison(folio) ? 0 : -EBUSY; 2843 } else if (ghp < 0) { 2844 if (ghp == -EHWPOISON) { 2845 ret = put_page_back_buddy(p) ? 0 : -EBUSY; 2846 } else { 2847 ret = ghp; 2848 unpoison_pr_info("%#lx: failed to grab page\n", 2849 pfn, &unpoison_rs); 2850 } 2851 } else { 2852 if (folio_test_hugetlb(folio)) { 2853 huge = true; 2854 count = folio_free_raw_hwp(folio, false); 2855 if (count == 0) { 2856 folio_put(folio); 2857 goto unlock_mutex; 2858 } 2859 } 2860 2861 folio_put(folio); 2862 if (TestClearPageHWPoison(p)) { 2863 folio_put(folio); 2864 ret = 0; 2865 } 2866 } 2867 2868 unlock_mutex: 2869 mutex_unlock(&mf_mutex); 2870 if (!ret) { 2871 if (!huge) 2872 num_poisoned_pages_sub(pfn, 1); 2873 unpoison_pr_info("%#lx: software-unpoisoned page\n", 2874 page_to_pfn(p), &unpoison_rs); 2875 } 2876 return ret; 2877 } 2878 EXPORT_SYMBOL(unpoison_memory); 2879 2880 #undef pr_fmt 2881 #define pr_fmt(fmt) "Soft offline: " fmt 2882 2883 /* 2884 * soft_offline_in_use_page handles hugetlb-pages and non-hugetlb pages. 2885 * If the page is a non-dirty unmapped page-cache page, it simply invalidates. 2886 * If the page is mapped, it migrates the contents over. 2887 */ 2888 static int soft_offline_in_use_page(struct page *page) 2889 { 2890 long ret = 0; 2891 unsigned long pfn = page_to_pfn(page); 2892 struct folio *folio = page_folio(page); 2893 char const *msg_page[] = {"page", "hugepage"}; 2894 bool huge = folio_test_hugetlb(folio); 2895 bool isolated; 2896 LIST_HEAD(pagelist); 2897 struct migration_target_control mtc = { 2898 .nid = NUMA_NO_NODE, 2899 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL, 2900 .reason = MR_MEMORY_FAILURE, 2901 }; 2902 2903 if (!huge && folio_test_large(folio)) { 2904 const int new_order = min_order_for_split(folio); 2905 2906 /* 2907 * If new_order (target split order) is not 0, do not split the 2908 * folio at all to retain the still accessible large folio. 2909 * NOTE: if minimizing the number of soft offline pages is 2910 * preferred, split it to non-zero new_order like it is done in 2911 * memory_failure(). 2912 */ 2913 if (new_order || try_to_split_thp_page(page, /* new_order= */ 0, 2914 /* release= */ true)) { 2915 pr_info("%#lx: thp split failed\n", pfn); 2916 return -EBUSY; 2917 } 2918 folio = page_folio(page); 2919 } 2920 2921 folio_lock(folio); 2922 if (!huge) 2923 folio_wait_writeback(folio); 2924 if (PageHWPoison(page)) { 2925 folio_unlock(folio); 2926 folio_put(folio); 2927 pr_info("%#lx: page already poisoned\n", pfn); 2928 return 0; 2929 } 2930 2931 if (!huge && folio_test_lru(folio) && !folio_test_swapcache(folio)) 2932 /* 2933 * Try to invalidate first. This should work for 2934 * non dirty unmapped page cache pages. 2935 */ 2936 ret = mapping_evict_folio(folio_mapping(folio), folio); 2937 folio_unlock(folio); 2938 2939 if (ret) { 2940 pr_info("%#lx: invalidated\n", pfn); 2941 page_handle_poison(page, false, true); 2942 return 0; 2943 } 2944 2945 isolated = isolate_folio_to_list(folio, &pagelist); 2946 2947 /* 2948 * If we succeed to isolate the folio, we grabbed another refcount on 2949 * the folio, so we can safely drop the one we got from get_any_page(). 2950 * If we failed to isolate the folio, it means that we cannot go further 2951 * and we will return an error, so drop the reference we got from 2952 * get_any_page() as well. 2953 */ 2954 folio_put(folio); 2955 2956 if (isolated) { 2957 ret = migrate_pages(&pagelist, alloc_migration_target, NULL, 2958 (unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_FAILURE, NULL); 2959 if (!ret) { 2960 bool release = !huge; 2961 2962 if (!page_handle_poison(page, huge, release)) 2963 ret = -EBUSY; 2964 } else { 2965 if (!list_empty(&pagelist)) 2966 putback_movable_pages(&pagelist); 2967 2968 pr_info("%#lx: %s migration failed %ld, type %pGp\n", 2969 pfn, msg_page[huge], ret, &page->flags.f); 2970 if (ret > 0) 2971 ret = -EBUSY; 2972 } 2973 } else { 2974 pr_info("%#lx: %s isolation failed, page count %d, type %pGp\n", 2975 pfn, msg_page[huge], page_count(page), &page->flags.f); 2976 ret = -EBUSY; 2977 } 2978 return ret; 2979 } 2980 2981 /** 2982 * soft_offline_page - Soft offline a page. 2983 * @pfn: pfn to soft-offline 2984 * @flags: flags. Same as memory_failure(). 2985 * 2986 * Returns 0 on success, 2987 * -EOPNOTSUPP for hwpoison_filter() filtered the error event, or 2988 * disabled by /proc/sys/vm/enable_soft_offline, 2989 * < 0 otherwise negated errno. 2990 * 2991 * Soft offline a page, by migration or invalidation, 2992 * without killing anything. This is for the case when 2993 * a page is not corrupted yet (so it's still valid to access), 2994 * but has had a number of corrected errors and is better taken 2995 * out. 2996 * 2997 * The actual policy on when to do that is maintained by 2998 * user space. 2999 * 3000 * This should never impact any application or cause data loss, 3001 * however it might take some time. 3002 * 3003 * This is not a 100% solution for all memory, but tries to be 3004 * ``good enough'' for the majority of memory. 3005 */ 3006 int soft_offline_page(unsigned long pfn, int flags) 3007 { 3008 int ret; 3009 bool try_again = true; 3010 struct page *page; 3011 3012 if (!pfn_valid(pfn)) { 3013 WARN_ON_ONCE(flags & MF_COUNT_INCREASED); 3014 return -ENXIO; 3015 } 3016 3017 /* Only online pages can be soft-offlined (esp., not ZONE_DEVICE). */ 3018 page = pfn_to_online_page(pfn); 3019 if (!page) { 3020 put_ref_page(pfn, flags); 3021 return -EIO; 3022 } 3023 3024 if (!sysctl_enable_soft_offline) { 3025 pr_info_once("disabled by /proc/sys/vm/enable_soft_offline\n"); 3026 put_ref_page(pfn, flags); 3027 return -EOPNOTSUPP; 3028 } 3029 3030 mutex_lock(&mf_mutex); 3031 3032 if (PageHWPoison(page)) { 3033 pr_info("%#lx: page already poisoned\n", pfn); 3034 put_ref_page(pfn, flags); 3035 mutex_unlock(&mf_mutex); 3036 return 0; 3037 } 3038 3039 retry: 3040 get_online_mems(); 3041 ret = get_hwpoison_page(page, flags | MF_SOFT_OFFLINE); 3042 put_online_mems(); 3043 3044 if (hwpoison_filter(page)) { 3045 if (ret > 0) 3046 put_page(page); 3047 3048 mutex_unlock(&mf_mutex); 3049 return -EOPNOTSUPP; 3050 } 3051 3052 if (ret > 0) { 3053 ret = soft_offline_in_use_page(page); 3054 } else if (ret == 0) { 3055 if (!page_handle_poison(page, true, false)) { 3056 if (try_again) { 3057 try_again = false; 3058 flags &= ~MF_COUNT_INCREASED; 3059 goto retry; 3060 } 3061 ret = -EBUSY; 3062 } 3063 } 3064 3065 mutex_unlock(&mf_mutex); 3066 3067 return ret; 3068 } 3069