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