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