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