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