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