]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - mm/memory-failure.c
mm,hwpoison: refactor soft_offline_huge_page and __soft_offline_page
[mirror_ubuntu-jammy-kernel.git] / mm / memory-failure.c
CommitLineData
1439f94c 1// SPDX-License-Identifier: GPL-2.0-only
6a46079c
AK
2/*
3 * Copyright (C) 2008, 2009 Intel Corporation
4 * Authors: Andi Kleen, Fengguang Wu
5 *
6a46079c 6 * High level machine check handler. Handles pages reported by the
1c80b990 7 * hardware as being corrupted usually due to a multi-bit ECC memory or cache
6a46079c 8 * failure.
1c80b990
AK
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.
6a46079c
AK
12 *
13 * Handles page cache pages in various states. The tricky part
1c80b990
AK
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.
e0de78df
AK
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/vm/page-types when running a real workload.
1c80b990
AK
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.
6a46079c 35 */
6a46079c
AK
36#include <linux/kernel.h>
37#include <linux/mm.h>
38#include <linux/page-flags.h>
478c5ffc 39#include <linux/kernel-page-flags.h>
3f07c014 40#include <linux/sched/signal.h>
29930025 41#include <linux/sched/task.h>
01e00f88 42#include <linux/ksm.h>
6a46079c 43#include <linux/rmap.h>
b9e15baf 44#include <linux/export.h>
6a46079c
AK
45#include <linux/pagemap.h>
46#include <linux/swap.h>
47#include <linux/backing-dev.h>
facb6011 48#include <linux/migrate.h>
facb6011 49#include <linux/suspend.h>
5a0e3ad6 50#include <linux/slab.h>
bf998156 51#include <linux/swapops.h>
7af446a8 52#include <linux/hugetlb.h>
20d6c96b 53#include <linux/memory_hotplug.h>
5db8a73a 54#include <linux/mm_inline.h>
6100e34b 55#include <linux/memremap.h>
ea8f5fb8 56#include <linux/kfifo.h>
a5f65109 57#include <linux/ratelimit.h>
d4ae9916 58#include <linux/page-isolation.h>
6a46079c 59#include "internal.h"
97f0b134 60#include "ras/ras_event.h"
6a46079c
AK
61
62int sysctl_memory_failure_early_kill __read_mostly = 0;
63
64int sysctl_memory_failure_recovery __read_mostly = 1;
65
293c07e3 66atomic_long_t num_poisoned_pages __read_mostly = ATOMIC_LONG_INIT(0);
6a46079c 67
6b9a217e 68static bool page_handle_poison(struct page *page, bool hugepage_or_freepage, bool release)
06be6ff3 69{
6b9a217e
OS
70 if (hugepage_or_freepage) {
71 /*
72 * Doing this check for free pages is also fine since dissolve_free_huge_page
73 * returns 0 for non-hugetlb pages as well.
74 */
75 if (dissolve_free_huge_page(page) || !take_page_off_buddy(page))
76 /*
77 * We could fail to take off the target page from buddy
78 * for example due to racy page allocaiton, but that's
79 * acceptable because soft-offlined page is not broken
80 * and if someone really want to use it, they should
81 * take it.
82 */
83 return false;
84 }
85
06be6ff3 86 SetPageHWPoison(page);
79f5f8fa
OS
87 if (release)
88 put_page(page);
06be6ff3
OS
89 page_ref_inc(page);
90 num_poisoned_pages_inc();
6b9a217e
OS
91
92 return true;
06be6ff3
OS
93}
94
27df5068
AK
95#if defined(CONFIG_HWPOISON_INJECT) || defined(CONFIG_HWPOISON_INJECT_MODULE)
96
1bfe5feb 97u32 hwpoison_filter_enable = 0;
7c116f2b
WF
98u32 hwpoison_filter_dev_major = ~0U;
99u32 hwpoison_filter_dev_minor = ~0U;
478c5ffc
WF
100u64 hwpoison_filter_flags_mask;
101u64 hwpoison_filter_flags_value;
1bfe5feb 102EXPORT_SYMBOL_GPL(hwpoison_filter_enable);
7c116f2b
WF
103EXPORT_SYMBOL_GPL(hwpoison_filter_dev_major);
104EXPORT_SYMBOL_GPL(hwpoison_filter_dev_minor);
478c5ffc
WF
105EXPORT_SYMBOL_GPL(hwpoison_filter_flags_mask);
106EXPORT_SYMBOL_GPL(hwpoison_filter_flags_value);
7c116f2b
WF
107
108static int hwpoison_filter_dev(struct page *p)
109{
110 struct address_space *mapping;
111 dev_t dev;
112
113 if (hwpoison_filter_dev_major == ~0U &&
114 hwpoison_filter_dev_minor == ~0U)
115 return 0;
116
117 /*
1c80b990 118 * page_mapping() does not accept slab pages.
7c116f2b
WF
119 */
120 if (PageSlab(p))
121 return -EINVAL;
122
123 mapping = page_mapping(p);
124 if (mapping == NULL || mapping->host == NULL)
125 return -EINVAL;
126
127 dev = mapping->host->i_sb->s_dev;
128 if (hwpoison_filter_dev_major != ~0U &&
129 hwpoison_filter_dev_major != MAJOR(dev))
130 return -EINVAL;
131 if (hwpoison_filter_dev_minor != ~0U &&
132 hwpoison_filter_dev_minor != MINOR(dev))
133 return -EINVAL;
134
135 return 0;
136}
137
478c5ffc
WF
138static int hwpoison_filter_flags(struct page *p)
139{
140 if (!hwpoison_filter_flags_mask)
141 return 0;
142
143 if ((stable_page_flags(p) & hwpoison_filter_flags_mask) ==
144 hwpoison_filter_flags_value)
145 return 0;
146 else
147 return -EINVAL;
148}
149
4fd466eb
AK
150/*
151 * This allows stress tests to limit test scope to a collection of tasks
152 * by putting them under some memcg. This prevents killing unrelated/important
153 * processes such as /sbin/init. Note that the target task may share clean
154 * pages with init (eg. libc text), which is harmless. If the target task
155 * share _dirty_ pages with another task B, the test scheme must make sure B
156 * is also included in the memcg. At last, due to race conditions this filter
157 * can only guarantee that the page either belongs to the memcg tasks, or is
158 * a freed page.
159 */
94a59fb3 160#ifdef CONFIG_MEMCG
4fd466eb
AK
161u64 hwpoison_filter_memcg;
162EXPORT_SYMBOL_GPL(hwpoison_filter_memcg);
163static int hwpoison_filter_task(struct page *p)
164{
4fd466eb
AK
165 if (!hwpoison_filter_memcg)
166 return 0;
167
94a59fb3 168 if (page_cgroup_ino(p) != hwpoison_filter_memcg)
4fd466eb
AK
169 return -EINVAL;
170
171 return 0;
172}
173#else
174static int hwpoison_filter_task(struct page *p) { return 0; }
175#endif
176
7c116f2b
WF
177int hwpoison_filter(struct page *p)
178{
1bfe5feb
HL
179 if (!hwpoison_filter_enable)
180 return 0;
181
7c116f2b
WF
182 if (hwpoison_filter_dev(p))
183 return -EINVAL;
184
478c5ffc
WF
185 if (hwpoison_filter_flags(p))
186 return -EINVAL;
187
4fd466eb
AK
188 if (hwpoison_filter_task(p))
189 return -EINVAL;
190
7c116f2b
WF
191 return 0;
192}
27df5068
AK
193#else
194int hwpoison_filter(struct page *p)
195{
196 return 0;
197}
198#endif
199
7c116f2b
WF
200EXPORT_SYMBOL_GPL(hwpoison_filter);
201
ae1139ec
DW
202/*
203 * Kill all processes that have a poisoned page mapped and then isolate
204 * the page.
205 *
206 * General strategy:
207 * Find all processes having the page mapped and kill them.
208 * But we keep a page reference around so that the page is not
209 * actually freed yet.
210 * Then stash the page away
211 *
212 * There's no convenient way to get back to mapped processes
213 * from the VMAs. So do a brute-force search over all
214 * running processes.
215 *
216 * Remember that machine checks are not common (or rather
217 * if they are common you have other problems), so this shouldn't
218 * be a performance issue.
219 *
220 * Also there are some races possible while we get from the
221 * error detection to actually handle it.
222 */
223
224struct to_kill {
225 struct list_head nd;
226 struct task_struct *tsk;
227 unsigned long addr;
228 short size_shift;
ae1139ec
DW
229};
230
6a46079c 231/*
7329bbeb
TL
232 * Send all the processes who have the page mapped a signal.
233 * ``action optional'' if they are not immediately affected by the error
234 * ``action required'' if error happened in current execution context
6a46079c 235 */
ae1139ec 236static int kill_proc(struct to_kill *tk, unsigned long pfn, int flags)
6a46079c 237{
ae1139ec
DW
238 struct task_struct *t = tk->tsk;
239 short addr_lsb = tk->size_shift;
872e9a20 240 int ret = 0;
6a46079c 241
03151c6e 242 pr_err("Memory failure: %#lx: Sending SIGBUS to %s:%d due to hardware memory corruption\n",
872e9a20 243 pfn, t->comm, t->pid);
7329bbeb 244
872e9a20 245 if (flags & MF_ACTION_REQUIRED) {
03151c6e
NH
246 WARN_ON_ONCE(t != current);
247 ret = force_sig_mceerr(BUS_MCEERR_AR,
872e9a20 248 (void __user *)tk->addr, addr_lsb);
7329bbeb
TL
249 } else {
250 /*
251 * Don't use force here, it's convenient if the signal
252 * can be temporarily blocked.
253 * This could cause a loop when the user sets SIGBUS
254 * to SIG_IGN, but hopefully no one will do that?
255 */
ae1139ec 256 ret = send_sig_mceerr(BUS_MCEERR_AO, (void __user *)tk->addr,
c0f45555 257 addr_lsb, t); /* synchronous? */
7329bbeb 258 }
6a46079c 259 if (ret < 0)
495367c0 260 pr_info("Memory failure: Error sending signal to %s:%d: %d\n",
1170532b 261 t->comm, t->pid, ret);
6a46079c
AK
262 return ret;
263}
264
588f9ce6
AK
265/*
266 * When a unknown page type is encountered drain as many buffers as possible
267 * in the hope to turn the page into a LRU or free page, which we can handle.
268 */
facb6011 269void shake_page(struct page *p, int access)
588f9ce6 270{
8bcb74de
NH
271 if (PageHuge(p))
272 return;
273
588f9ce6
AK
274 if (!PageSlab(p)) {
275 lru_add_drain_all();
276 if (PageLRU(p))
277 return;
c0554329 278 drain_all_pages(page_zone(p));
588f9ce6
AK
279 if (PageLRU(p) || is_free_buddy_page(p))
280 return;
281 }
facb6011 282
588f9ce6 283 /*
6b4f7799
JW
284 * Only call shrink_node_slabs here (which would also shrink
285 * other caches) if access is not potentially fatal.
588f9ce6 286 */
cb731d6c
VD
287 if (access)
288 drop_slab_node(page_to_nid(p));
588f9ce6
AK
289}
290EXPORT_SYMBOL_GPL(shake_page);
291
6100e34b
DW
292static unsigned long dev_pagemap_mapping_shift(struct page *page,
293 struct vm_area_struct *vma)
294{
295 unsigned long address = vma_address(page, vma);
296 pgd_t *pgd;
297 p4d_t *p4d;
298 pud_t *pud;
299 pmd_t *pmd;
300 pte_t *pte;
301
302 pgd = pgd_offset(vma->vm_mm, address);
303 if (!pgd_present(*pgd))
304 return 0;
305 p4d = p4d_offset(pgd, address);
306 if (!p4d_present(*p4d))
307 return 0;
308 pud = pud_offset(p4d, address);
309 if (!pud_present(*pud))
310 return 0;
311 if (pud_devmap(*pud))
312 return PUD_SHIFT;
313 pmd = pmd_offset(pud, address);
314 if (!pmd_present(*pmd))
315 return 0;
316 if (pmd_devmap(*pmd))
317 return PMD_SHIFT;
318 pte = pte_offset_map(pmd, address);
319 if (!pte_present(*pte))
320 return 0;
321 if (pte_devmap(*pte))
322 return PAGE_SHIFT;
323 return 0;
324}
6a46079c
AK
325
326/*
327 * Failure handling: if we can't find or can't kill a process there's
328 * not much we can do. We just print a message and ignore otherwise.
329 */
330
331/*
332 * Schedule a process for later kill.
333 * Uses GFP_ATOMIC allocations to avoid potential recursions in the VM.
6a46079c
AK
334 */
335static void add_to_kill(struct task_struct *tsk, struct page *p,
336 struct vm_area_struct *vma,
996ff7a0 337 struct list_head *to_kill)
6a46079c
AK
338{
339 struct to_kill *tk;
340
996ff7a0
JC
341 tk = kmalloc(sizeof(struct to_kill), GFP_ATOMIC);
342 if (!tk) {
343 pr_err("Memory failure: Out of memory while machine check handling\n");
344 return;
6a46079c 345 }
996ff7a0 346
6a46079c 347 tk->addr = page_address_in_vma(p, vma);
6100e34b
DW
348 if (is_zone_device_page(p))
349 tk->size_shift = dev_pagemap_mapping_shift(p, vma);
350 else
75068518 351 tk->size_shift = page_shift(compound_head(p));
6a46079c
AK
352
353 /*
3d7fed4a
JC
354 * Send SIGKILL if "tk->addr == -EFAULT". Also, as
355 * "tk->size_shift" is always non-zero for !is_zone_device_page(),
356 * so "tk->size_shift == 0" effectively checks no mapping on
357 * ZONE_DEVICE. Indeed, when a devdax page is mmapped N times
358 * to a process' address space, it's possible not all N VMAs
359 * contain mappings for the page, but at least one VMA does.
360 * Only deliver SIGBUS with payload derived from the VMA that
361 * has a mapping for the page.
6a46079c 362 */
3d7fed4a 363 if (tk->addr == -EFAULT) {
495367c0 364 pr_info("Memory failure: Unable to find user space address %lx in %s\n",
6a46079c 365 page_to_pfn(p), tsk->comm);
3d7fed4a
JC
366 } else if (tk->size_shift == 0) {
367 kfree(tk);
368 return;
6a46079c 369 }
996ff7a0 370
6a46079c
AK
371 get_task_struct(tsk);
372 tk->tsk = tsk;
373 list_add_tail(&tk->nd, to_kill);
374}
375
376/*
377 * Kill the processes that have been collected earlier.
378 *
379 * Only do anything when DOIT is set, otherwise just free the list
380 * (this is used for clean pages which do not need killing)
381 * Also when FAIL is set do a force kill because something went
382 * wrong earlier.
383 */
ae1139ec
DW
384static void kill_procs(struct list_head *to_kill, int forcekill, bool fail,
385 unsigned long pfn, int flags)
6a46079c
AK
386{
387 struct to_kill *tk, *next;
388
389 list_for_each_entry_safe (tk, next, to_kill, nd) {
6751ed65 390 if (forcekill) {
6a46079c 391 /*
af901ca1 392 * In case something went wrong with munmapping
6a46079c
AK
393 * make sure the process doesn't catch the
394 * signal and then access the memory. Just kill it.
6a46079c 395 */
3d7fed4a 396 if (fail || tk->addr == -EFAULT) {
495367c0 397 pr_err("Memory failure: %#lx: forcibly killing %s:%d because of failure to unmap corrupted page\n",
1170532b 398 pfn, tk->tsk->comm, tk->tsk->pid);
6376360e
NH
399 do_send_sig_info(SIGKILL, SEND_SIG_PRIV,
400 tk->tsk, PIDTYPE_PID);
6a46079c
AK
401 }
402
403 /*
404 * In theory the process could have mapped
405 * something else on the address in-between. We could
406 * check for that, but we need to tell the
407 * process anyways.
408 */
ae1139ec 409 else if (kill_proc(tk, pfn, flags) < 0)
495367c0 410 pr_err("Memory failure: %#lx: Cannot send advisory machine check signal to %s:%d\n",
1170532b 411 pfn, tk->tsk->comm, tk->tsk->pid);
6a46079c
AK
412 }
413 put_task_struct(tk->tsk);
414 kfree(tk);
415 }
416}
417
3ba08129
NH
418/*
419 * Find a dedicated thread which is supposed to handle SIGBUS(BUS_MCEERR_AO)
420 * on behalf of the thread group. Return task_struct of the (first found)
421 * dedicated thread if found, and return NULL otherwise.
422 *
423 * We already hold read_lock(&tasklist_lock) in the caller, so we don't
424 * have to call rcu_read_lock/unlock() in this function.
425 */
426static struct task_struct *find_early_kill_thread(struct task_struct *tsk)
6a46079c 427{
3ba08129
NH
428 struct task_struct *t;
429
4e018b45
NH
430 for_each_thread(tsk, t) {
431 if (t->flags & PF_MCE_PROCESS) {
432 if (t->flags & PF_MCE_EARLY)
433 return t;
434 } else {
435 if (sysctl_memory_failure_early_kill)
436 return t;
437 }
438 }
3ba08129
NH
439 return NULL;
440}
441
442/*
443 * Determine whether a given process is "early kill" process which expects
444 * to be signaled when some page under the process is hwpoisoned.
445 * Return task_struct of the dedicated thread (main thread unless explicitly
446 * specified) if the process is "early kill," and otherwise returns NULL.
03151c6e
NH
447 *
448 * Note that the above is true for Action Optional case, but not for Action
449 * Required case where SIGBUS should sent only to the current thread.
3ba08129
NH
450 */
451static struct task_struct *task_early_kill(struct task_struct *tsk,
452 int force_early)
453{
6a46079c 454 if (!tsk->mm)
3ba08129 455 return NULL;
03151c6e
NH
456 if (force_early) {
457 /*
458 * Comparing ->mm here because current task might represent
459 * a subthread, while tsk always points to the main thread.
460 */
461 if (tsk->mm == current->mm)
462 return current;
463 else
464 return NULL;
465 }
4e018b45 466 return find_early_kill_thread(tsk);
6a46079c
AK
467}
468
469/*
470 * Collect processes when the error hit an anonymous page.
471 */
472static void collect_procs_anon(struct page *page, struct list_head *to_kill,
996ff7a0 473 int force_early)
6a46079c
AK
474{
475 struct vm_area_struct *vma;
476 struct task_struct *tsk;
477 struct anon_vma *av;
bf181b9f 478 pgoff_t pgoff;
6a46079c 479
4fc3f1d6 480 av = page_lock_anon_vma_read(page);
6a46079c 481 if (av == NULL) /* Not actually mapped anymore */
9b679320
PZ
482 return;
483
a0f7a756 484 pgoff = page_to_pgoff(page);
9b679320 485 read_lock(&tasklist_lock);
6a46079c 486 for_each_process (tsk) {
5beb4930 487 struct anon_vma_chain *vmac;
3ba08129 488 struct task_struct *t = task_early_kill(tsk, force_early);
5beb4930 489
3ba08129 490 if (!t)
6a46079c 491 continue;
bf181b9f
ML
492 anon_vma_interval_tree_foreach(vmac, &av->rb_root,
493 pgoff, pgoff) {
5beb4930 494 vma = vmac->vma;
6a46079c
AK
495 if (!page_mapped_in_vma(page, vma))
496 continue;
3ba08129 497 if (vma->vm_mm == t->mm)
996ff7a0 498 add_to_kill(t, page, vma, to_kill);
6a46079c
AK
499 }
500 }
6a46079c 501 read_unlock(&tasklist_lock);
4fc3f1d6 502 page_unlock_anon_vma_read(av);
6a46079c
AK
503}
504
505/*
506 * Collect processes when the error hit a file mapped page.
507 */
508static void collect_procs_file(struct page *page, struct list_head *to_kill,
996ff7a0 509 int force_early)
6a46079c
AK
510{
511 struct vm_area_struct *vma;
512 struct task_struct *tsk;
6a46079c 513 struct address_space *mapping = page->mapping;
c43bc03d 514 pgoff_t pgoff;
6a46079c 515
d28eb9c8 516 i_mmap_lock_read(mapping);
9b679320 517 read_lock(&tasklist_lock);
c43bc03d 518 pgoff = page_to_pgoff(page);
6a46079c 519 for_each_process(tsk) {
3ba08129 520 struct task_struct *t = task_early_kill(tsk, force_early);
6a46079c 521
3ba08129 522 if (!t)
6a46079c 523 continue;
6b2dbba8 524 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff,
6a46079c
AK
525 pgoff) {
526 /*
527 * Send early kill signal to tasks where a vma covers
528 * the page but the corrupted page is not necessarily
529 * mapped it in its pte.
530 * Assume applications who requested early kill want
531 * to be informed of all such data corruptions.
532 */
3ba08129 533 if (vma->vm_mm == t->mm)
996ff7a0 534 add_to_kill(t, page, vma, to_kill);
6a46079c
AK
535 }
536 }
6a46079c 537 read_unlock(&tasklist_lock);
d28eb9c8 538 i_mmap_unlock_read(mapping);
6a46079c
AK
539}
540
541/*
542 * Collect the processes who have the corrupted page mapped to kill.
6a46079c 543 */
74614de1
TL
544static void collect_procs(struct page *page, struct list_head *tokill,
545 int force_early)
6a46079c 546{
6a46079c
AK
547 if (!page->mapping)
548 return;
549
6a46079c 550 if (PageAnon(page))
996ff7a0 551 collect_procs_anon(page, tokill, force_early);
6a46079c 552 else
996ff7a0 553 collect_procs_file(page, tokill, force_early);
6a46079c
AK
554}
555
6a46079c 556static const char *action_name[] = {
cc637b17
XX
557 [MF_IGNORED] = "Ignored",
558 [MF_FAILED] = "Failed",
559 [MF_DELAYED] = "Delayed",
560 [MF_RECOVERED] = "Recovered",
64d37a2b
NH
561};
562
563static const char * const action_page_types[] = {
cc637b17
XX
564 [MF_MSG_KERNEL] = "reserved kernel page",
565 [MF_MSG_KERNEL_HIGH_ORDER] = "high-order kernel page",
566 [MF_MSG_SLAB] = "kernel slab page",
567 [MF_MSG_DIFFERENT_COMPOUND] = "different compound page after locking",
568 [MF_MSG_POISONED_HUGE] = "huge page already hardware poisoned",
569 [MF_MSG_HUGE] = "huge page",
570 [MF_MSG_FREE_HUGE] = "free huge page",
31286a84 571 [MF_MSG_NON_PMD_HUGE] = "non-pmd-sized huge page",
cc637b17
XX
572 [MF_MSG_UNMAP_FAILED] = "unmapping failed page",
573 [MF_MSG_DIRTY_SWAPCACHE] = "dirty swapcache page",
574 [MF_MSG_CLEAN_SWAPCACHE] = "clean swapcache page",
575 [MF_MSG_DIRTY_MLOCKED_LRU] = "dirty mlocked LRU page",
576 [MF_MSG_CLEAN_MLOCKED_LRU] = "clean mlocked LRU page",
577 [MF_MSG_DIRTY_UNEVICTABLE_LRU] = "dirty unevictable LRU page",
578 [MF_MSG_CLEAN_UNEVICTABLE_LRU] = "clean unevictable LRU page",
579 [MF_MSG_DIRTY_LRU] = "dirty LRU page",
580 [MF_MSG_CLEAN_LRU] = "clean LRU page",
581 [MF_MSG_TRUNCATED_LRU] = "already truncated LRU page",
582 [MF_MSG_BUDDY] = "free buddy page",
583 [MF_MSG_BUDDY_2ND] = "free buddy page (2nd try)",
6100e34b 584 [MF_MSG_DAX] = "dax page",
cc637b17 585 [MF_MSG_UNKNOWN] = "unknown page",
64d37a2b
NH
586};
587
dc2a1cbf
WF
588/*
589 * XXX: It is possible that a page is isolated from LRU cache,
590 * and then kept in swap cache or failed to remove from page cache.
591 * The page count will stop it from being freed by unpoison.
592 * Stress tests should be aware of this memory leak problem.
593 */
594static int delete_from_lru_cache(struct page *p)
595{
596 if (!isolate_lru_page(p)) {
597 /*
598 * Clear sensible page flags, so that the buddy system won't
599 * complain when the page is unpoison-and-freed.
600 */
601 ClearPageActive(p);
602 ClearPageUnevictable(p);
18365225
MH
603
604 /*
605 * Poisoned page might never drop its ref count to 0 so we have
606 * to uncharge it manually from its memcg.
607 */
608 mem_cgroup_uncharge(p);
609
dc2a1cbf
WF
610 /*
611 * drop the page count elevated by isolate_lru_page()
612 */
09cbfeaf 613 put_page(p);
dc2a1cbf
WF
614 return 0;
615 }
616 return -EIO;
617}
618
78bb9203
NH
619static int truncate_error_page(struct page *p, unsigned long pfn,
620 struct address_space *mapping)
621{
622 int ret = MF_FAILED;
623
624 if (mapping->a_ops->error_remove_page) {
625 int err = mapping->a_ops->error_remove_page(mapping, p);
626
627 if (err != 0) {
628 pr_info("Memory failure: %#lx: Failed to punch page: %d\n",
629 pfn, err);
630 } else if (page_has_private(p) &&
631 !try_to_release_page(p, GFP_NOIO)) {
632 pr_info("Memory failure: %#lx: failed to release buffers\n",
633 pfn);
634 } else {
635 ret = MF_RECOVERED;
636 }
637 } else {
638 /*
639 * If the file system doesn't support it just invalidate
640 * This fails on dirty or anything with private pages
641 */
642 if (invalidate_inode_page(p))
643 ret = MF_RECOVERED;
644 else
645 pr_info("Memory failure: %#lx: Failed to invalidate\n",
646 pfn);
647 }
648
649 return ret;
650}
651
6a46079c
AK
652/*
653 * Error hit kernel page.
654 * Do nothing, try to be lucky and not touch this instead. For a few cases we
655 * could be more sophisticated.
656 */
657static int me_kernel(struct page *p, unsigned long pfn)
6a46079c 658{
cc637b17 659 return MF_IGNORED;
6a46079c
AK
660}
661
662/*
663 * Page in unknown state. Do nothing.
664 */
665static int me_unknown(struct page *p, unsigned long pfn)
666{
495367c0 667 pr_err("Memory failure: %#lx: Unknown page state\n", pfn);
cc637b17 668 return MF_FAILED;
6a46079c
AK
669}
670
6a46079c
AK
671/*
672 * Clean (or cleaned) page cache page.
673 */
674static int me_pagecache_clean(struct page *p, unsigned long pfn)
675{
6a46079c
AK
676 struct address_space *mapping;
677
dc2a1cbf
WF
678 delete_from_lru_cache(p);
679
6a46079c
AK
680 /*
681 * For anonymous pages we're done the only reference left
682 * should be the one m_f() holds.
683 */
684 if (PageAnon(p))
cc637b17 685 return MF_RECOVERED;
6a46079c
AK
686
687 /*
688 * Now truncate the page in the page cache. This is really
689 * more like a "temporary hole punch"
690 * Don't do this for block devices when someone else
691 * has a reference, because it could be file system metadata
692 * and that's not safe to truncate.
693 */
694 mapping = page_mapping(p);
695 if (!mapping) {
696 /*
697 * Page has been teared down in the meanwhile
698 */
cc637b17 699 return MF_FAILED;
6a46079c
AK
700 }
701
702 /*
703 * Truncation is a bit tricky. Enable it per file system for now.
704 *
705 * Open: to take i_mutex or not for this? Right now we don't.
706 */
78bb9203 707 return truncate_error_page(p, pfn, mapping);
6a46079c
AK
708}
709
710/*
549543df 711 * Dirty pagecache page
6a46079c
AK
712 * Issues: when the error hit a hole page the error is not properly
713 * propagated.
714 */
715static int me_pagecache_dirty(struct page *p, unsigned long pfn)
716{
717 struct address_space *mapping = page_mapping(p);
718
719 SetPageError(p);
720 /* TBD: print more information about the file. */
721 if (mapping) {
722 /*
723 * IO error will be reported by write(), fsync(), etc.
724 * who check the mapping.
725 * This way the application knows that something went
726 * wrong with its dirty file data.
727 *
728 * There's one open issue:
729 *
730 * The EIO will be only reported on the next IO
731 * operation and then cleared through the IO map.
732 * Normally Linux has two mechanisms to pass IO error
733 * first through the AS_EIO flag in the address space
734 * and then through the PageError flag in the page.
735 * Since we drop pages on memory failure handling the
736 * only mechanism open to use is through AS_AIO.
737 *
738 * This has the disadvantage that it gets cleared on
739 * the first operation that returns an error, while
740 * the PageError bit is more sticky and only cleared
741 * when the page is reread or dropped. If an
742 * application assumes it will always get error on
743 * fsync, but does other operations on the fd before
25985edc 744 * and the page is dropped between then the error
6a46079c
AK
745 * will not be properly reported.
746 *
747 * This can already happen even without hwpoisoned
748 * pages: first on metadata IO errors (which only
749 * report through AS_EIO) or when the page is dropped
750 * at the wrong time.
751 *
752 * So right now we assume that the application DTRT on
753 * the first EIO, but we're not worse than other parts
754 * of the kernel.
755 */
af21bfaf 756 mapping_set_error(mapping, -EIO);
6a46079c
AK
757 }
758
759 return me_pagecache_clean(p, pfn);
760}
761
762/*
763 * Clean and dirty swap cache.
764 *
765 * Dirty swap cache page is tricky to handle. The page could live both in page
766 * cache and swap cache(ie. page is freshly swapped in). So it could be
767 * referenced concurrently by 2 types of PTEs:
768 * normal PTEs and swap PTEs. We try to handle them consistently by calling
769 * try_to_unmap(TTU_IGNORE_HWPOISON) to convert the normal PTEs to swap PTEs,
770 * and then
771 * - clear dirty bit to prevent IO
772 * - remove from LRU
773 * - but keep in the swap cache, so that when we return to it on
774 * a later page fault, we know the application is accessing
775 * corrupted data and shall be killed (we installed simple
776 * interception code in do_swap_page to catch it).
777 *
778 * Clean swap cache pages can be directly isolated. A later page fault will
779 * bring in the known good data from disk.
780 */
781static int me_swapcache_dirty(struct page *p, unsigned long pfn)
782{
6a46079c
AK
783 ClearPageDirty(p);
784 /* Trigger EIO in shmem: */
785 ClearPageUptodate(p);
786
dc2a1cbf 787 if (!delete_from_lru_cache(p))
cc637b17 788 return MF_DELAYED;
dc2a1cbf 789 else
cc637b17 790 return MF_FAILED;
6a46079c
AK
791}
792
793static int me_swapcache_clean(struct page *p, unsigned long pfn)
794{
6a46079c 795 delete_from_swap_cache(p);
e43c3afb 796
dc2a1cbf 797 if (!delete_from_lru_cache(p))
cc637b17 798 return MF_RECOVERED;
dc2a1cbf 799 else
cc637b17 800 return MF_FAILED;
6a46079c
AK
801}
802
803/*
804 * Huge pages. Needs work.
805 * Issues:
93f70f90
NH
806 * - Error on hugepage is contained in hugepage unit (not in raw page unit.)
807 * To narrow down kill region to one page, we need to break up pmd.
6a46079c
AK
808 */
809static int me_huge_page(struct page *p, unsigned long pfn)
810{
6de2b1aa 811 int res = 0;
93f70f90 812 struct page *hpage = compound_head(p);
78bb9203 813 struct address_space *mapping;
2491ffee
NH
814
815 if (!PageHuge(hpage))
816 return MF_DELAYED;
817
78bb9203
NH
818 mapping = page_mapping(hpage);
819 if (mapping) {
820 res = truncate_error_page(hpage, pfn, mapping);
821 } else {
822 unlock_page(hpage);
823 /*
824 * migration entry prevents later access on error anonymous
825 * hugepage, so we can free and dissolve it into buddy to
826 * save healthy subpages.
827 */
828 if (PageAnon(hpage))
829 put_page(hpage);
830 dissolve_free_huge_page(p);
831 res = MF_RECOVERED;
832 lock_page(hpage);
93f70f90 833 }
78bb9203
NH
834
835 return res;
6a46079c
AK
836}
837
838/*
839 * Various page states we can handle.
840 *
841 * A page state is defined by its current page->flags bits.
842 * The table matches them in order and calls the right handler.
843 *
844 * This is quite tricky because we can access page at any time
25985edc 845 * in its live cycle, so all accesses have to be extremely careful.
6a46079c
AK
846 *
847 * This is not complete. More states could be added.
848 * For any missing state don't attempt recovery.
849 */
850
851#define dirty (1UL << PG_dirty)
6326fec1 852#define sc ((1UL << PG_swapcache) | (1UL << PG_swapbacked))
6a46079c
AK
853#define unevict (1UL << PG_unevictable)
854#define mlock (1UL << PG_mlocked)
6a46079c 855#define lru (1UL << PG_lru)
6a46079c 856#define head (1UL << PG_head)
6a46079c 857#define slab (1UL << PG_slab)
6a46079c
AK
858#define reserved (1UL << PG_reserved)
859
860static struct page_state {
861 unsigned long mask;
862 unsigned long res;
cc637b17 863 enum mf_action_page_type type;
6a46079c
AK
864 int (*action)(struct page *p, unsigned long pfn);
865} error_states[] = {
cc637b17 866 { reserved, reserved, MF_MSG_KERNEL, me_kernel },
95d01fc6
WF
867 /*
868 * free pages are specially detected outside this table:
869 * PG_buddy pages only make a small fraction of all free pages.
870 */
6a46079c
AK
871
872 /*
873 * Could in theory check if slab page is free or if we can drop
874 * currently unused objects without touching them. But just
875 * treat it as standard kernel for now.
876 */
cc637b17 877 { slab, slab, MF_MSG_SLAB, me_kernel },
6a46079c 878
cc637b17 879 { head, head, MF_MSG_HUGE, me_huge_page },
6a46079c 880
cc637b17
XX
881 { sc|dirty, sc|dirty, MF_MSG_DIRTY_SWAPCACHE, me_swapcache_dirty },
882 { sc|dirty, sc, MF_MSG_CLEAN_SWAPCACHE, me_swapcache_clean },
6a46079c 883
cc637b17
XX
884 { mlock|dirty, mlock|dirty, MF_MSG_DIRTY_MLOCKED_LRU, me_pagecache_dirty },
885 { mlock|dirty, mlock, MF_MSG_CLEAN_MLOCKED_LRU, me_pagecache_clean },
6a46079c 886
cc637b17
XX
887 { unevict|dirty, unevict|dirty, MF_MSG_DIRTY_UNEVICTABLE_LRU, me_pagecache_dirty },
888 { unevict|dirty, unevict, MF_MSG_CLEAN_UNEVICTABLE_LRU, me_pagecache_clean },
5f4b9fc5 889
cc637b17
XX
890 { lru|dirty, lru|dirty, MF_MSG_DIRTY_LRU, me_pagecache_dirty },
891 { lru|dirty, lru, MF_MSG_CLEAN_LRU, me_pagecache_clean },
6a46079c
AK
892
893 /*
894 * Catchall entry: must be at end.
895 */
cc637b17 896 { 0, 0, MF_MSG_UNKNOWN, me_unknown },
6a46079c
AK
897};
898
2326c467
AK
899#undef dirty
900#undef sc
901#undef unevict
902#undef mlock
2326c467 903#undef lru
2326c467 904#undef head
2326c467
AK
905#undef slab
906#undef reserved
907
ff604cf6
NH
908/*
909 * "Dirty/Clean" indication is not 100% accurate due to the possibility of
910 * setting PG_dirty outside page lock. See also comment above set_page_dirty().
911 */
cc3e2af4
XX
912static void action_result(unsigned long pfn, enum mf_action_page_type type,
913 enum mf_result result)
6a46079c 914{
97f0b134
XX
915 trace_memory_failure_event(pfn, type, result);
916
495367c0 917 pr_err("Memory failure: %#lx: recovery action for %s: %s\n",
64d37a2b 918 pfn, action_page_types[type], action_name[result]);
6a46079c
AK
919}
920
921static int page_action(struct page_state *ps, struct page *p,
bd1ce5f9 922 unsigned long pfn)
6a46079c
AK
923{
924 int result;
7456b040 925 int count;
6a46079c
AK
926
927 result = ps->action(p, pfn);
7456b040 928
bd1ce5f9 929 count = page_count(p) - 1;
cc637b17 930 if (ps->action == me_swapcache_dirty && result == MF_DELAYED)
138ce286 931 count--;
78bb9203 932 if (count > 0) {
495367c0 933 pr_err("Memory failure: %#lx: %s still referenced by %d users\n",
64d37a2b 934 pfn, action_page_types[ps->type], count);
cc637b17 935 result = MF_FAILED;
138ce286 936 }
64d37a2b 937 action_result(pfn, ps->type, result);
6a46079c
AK
938
939 /* Could do more checks here if page looks ok */
940 /*
941 * Could adjust zone counters here to correct for the missing page.
942 */
943
cc637b17 944 return (result == MF_RECOVERED || result == MF_DELAYED) ? 0 : -EBUSY;
6a46079c
AK
945}
946
ead07f6a
NH
947/**
948 * get_hwpoison_page() - Get refcount for memory error handling:
949 * @page: raw error page (hit by memory error)
950 *
951 * Return: return 0 if failed to grab the refcount, otherwise true (some
952 * non-zero value.)
953 */
7e27f22c 954static int get_hwpoison_page(struct page *page)
ead07f6a
NH
955{
956 struct page *head = compound_head(page);
957
4e41a30c 958 if (!PageHuge(head) && PageTransHuge(head)) {
98ed2b00
NH
959 /*
960 * Non anonymous thp exists only in allocation/free time. We
961 * can't handle such a case correctly, so let's give it up.
962 * This should be better than triggering BUG_ON when kernel
963 * tries to touch the "partially handled" page.
964 */
965 if (!PageAnon(head)) {
495367c0 966 pr_err("Memory failure: %#lx: non anonymous thp\n",
98ed2b00
NH
967 page_to_pfn(page));
968 return 0;
969 }
ead07f6a
NH
970 }
971
c2e7e00b
KK
972 if (get_page_unless_zero(head)) {
973 if (head == compound_head(page))
974 return 1;
975
495367c0
CY
976 pr_info("Memory failure: %#lx cannot catch tail\n",
977 page_to_pfn(page));
c2e7e00b
KK
978 put_page(head);
979 }
980
981 return 0;
ead07f6a 982}
ead07f6a 983
6a46079c
AK
984/*
985 * Do all that is necessary to remove user space mappings. Unmap
986 * the pages and send SIGBUS to the processes if the data was dirty.
987 */
666e5a40 988static bool hwpoison_user_mappings(struct page *p, unsigned long pfn,
83b57531 989 int flags, struct page **hpagep)
6a46079c 990{
a128ca71 991 enum ttu_flags ttu = TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS;
6a46079c
AK
992 struct address_space *mapping;
993 LIST_HEAD(tokill);
c0d0381a 994 bool unmap_success = true;
6751ed65 995 int kill = 1, forcekill;
54b9dd14 996 struct page *hpage = *hpagep;
286c469a 997 bool mlocked = PageMlocked(hpage);
6a46079c 998
93a9eb39
NH
999 /*
1000 * Here we are interested only in user-mapped pages, so skip any
1001 * other types of pages.
1002 */
1003 if (PageReserved(p) || PageSlab(p))
666e5a40 1004 return true;
93a9eb39 1005 if (!(PageLRU(hpage) || PageHuge(p)))
666e5a40 1006 return true;
6a46079c 1007
6a46079c
AK
1008 /*
1009 * This check implies we don't kill processes if their pages
1010 * are in the swap cache early. Those are always late kills.
1011 */
7af446a8 1012 if (!page_mapped(hpage))
666e5a40 1013 return true;
1668bfd5 1014
52089b14 1015 if (PageKsm(p)) {
495367c0 1016 pr_err("Memory failure: %#lx: can't handle KSM pages.\n", pfn);
666e5a40 1017 return false;
52089b14 1018 }
6a46079c
AK
1019
1020 if (PageSwapCache(p)) {
495367c0
CY
1021 pr_err("Memory failure: %#lx: keeping poisoned page in swap cache\n",
1022 pfn);
6a46079c
AK
1023 ttu |= TTU_IGNORE_HWPOISON;
1024 }
1025
1026 /*
1027 * Propagate the dirty bit from PTEs to struct page first, because we
1028 * need this to decide if we should kill or just drop the page.
db0480b3
WF
1029 * XXX: the dirty test could be racy: set_page_dirty() may not always
1030 * be called inside page lock (it's recommended but not enforced).
6a46079c 1031 */
7af446a8 1032 mapping = page_mapping(hpage);
6751ed65 1033 if (!(flags & MF_MUST_KILL) && !PageDirty(hpage) && mapping &&
f56753ac 1034 mapping_can_writeback(mapping)) {
7af446a8
NH
1035 if (page_mkclean(hpage)) {
1036 SetPageDirty(hpage);
6a46079c
AK
1037 } else {
1038 kill = 0;
1039 ttu |= TTU_IGNORE_HWPOISON;
495367c0 1040 pr_info("Memory failure: %#lx: corrupted page was clean: dropped without side effects\n",
6a46079c
AK
1041 pfn);
1042 }
1043 }
1044
1045 /*
1046 * First collect all the processes that have the page
1047 * mapped in dirty form. This has to be done before try_to_unmap,
1048 * because ttu takes the rmap data structures down.
1049 *
1050 * Error handling: We ignore errors here because
1051 * there's nothing that can be done.
1052 */
1053 if (kill)
415c64c1 1054 collect_procs(hpage, &tokill, flags & MF_ACTION_REQUIRED);
6a46079c 1055
c0d0381a
MK
1056 if (!PageHuge(hpage)) {
1057 unmap_success = try_to_unmap(hpage, ttu);
1058 } else {
1059 /*
1060 * For hugetlb pages, try_to_unmap could potentially call
1061 * huge_pmd_unshare. Because of this, take semaphore in
1062 * write mode here and set TTU_RMAP_LOCKED to indicate we
1063 * have taken the lock at this higer level.
1064 *
1065 * Note that the call to hugetlb_page_mapping_lock_write
1066 * is necessary even if mapping is already set. It handles
1067 * ugliness of potentially having to drop page lock to obtain
1068 * i_mmap_rwsem.
1069 */
1070 mapping = hugetlb_page_mapping_lock_write(hpage);
1071
1072 if (mapping) {
1073 unmap_success = try_to_unmap(hpage,
1074 ttu|TTU_RMAP_LOCKED);
1075 i_mmap_unlock_write(mapping);
1076 } else {
1077 pr_info("Memory failure: %#lx: could not find mapping for mapped huge page\n",
1078 pfn);
1079 unmap_success = false;
1080 }
1081 }
666e5a40 1082 if (!unmap_success)
495367c0 1083 pr_err("Memory failure: %#lx: failed to unmap page (mapcount=%d)\n",
1170532b 1084 pfn, page_mapcount(hpage));
a6d30ddd 1085
286c469a
NH
1086 /*
1087 * try_to_unmap() might put mlocked page in lru cache, so call
1088 * shake_page() again to ensure that it's flushed.
1089 */
1090 if (mlocked)
1091 shake_page(hpage, 0);
1092
6a46079c
AK
1093 /*
1094 * Now that the dirty bit has been propagated to the
1095 * struct page and all unmaps done we can decide if
1096 * killing is needed or not. Only kill when the page
6751ed65
TL
1097 * was dirty or the process is not restartable,
1098 * otherwise the tokill list is merely
6a46079c
AK
1099 * freed. When there was a problem unmapping earlier
1100 * use a more force-full uncatchable kill to prevent
1101 * any accesses to the poisoned memory.
1102 */
415c64c1 1103 forcekill = PageDirty(hpage) || (flags & MF_MUST_KILL);
ae1139ec 1104 kill_procs(&tokill, forcekill, !unmap_success, pfn, flags);
1668bfd5 1105
666e5a40 1106 return unmap_success;
6a46079c
AK
1107}
1108
0348d2eb
NH
1109static int identify_page_state(unsigned long pfn, struct page *p,
1110 unsigned long page_flags)
761ad8d7
NH
1111{
1112 struct page_state *ps;
0348d2eb
NH
1113
1114 /*
1115 * The first check uses the current page flags which may not have any
1116 * relevant information. The second check with the saved page flags is
1117 * carried out only if the first check can't determine the page status.
1118 */
1119 for (ps = error_states;; ps++)
1120 if ((p->flags & ps->mask) == ps->res)
1121 break;
1122
1123 page_flags |= (p->flags & (1UL << PG_dirty));
1124
1125 if (!ps->mask)
1126 for (ps = error_states;; ps++)
1127 if ((page_flags & ps->mask) == ps->res)
1128 break;
1129 return page_action(ps, p, pfn);
1130}
1131
694bf0b0
OS
1132static int try_to_split_thp_page(struct page *page, const char *msg)
1133{
1134 lock_page(page);
1135 if (!PageAnon(page) || unlikely(split_huge_page(page))) {
1136 unsigned long pfn = page_to_pfn(page);
1137
1138 unlock_page(page);
1139 if (!PageAnon(page))
1140 pr_info("%s: %#lx: non anonymous thp\n", msg, pfn);
1141 else
1142 pr_info("%s: %#lx: thp split failed\n", msg, pfn);
1143 put_page(page);
1144 return -EBUSY;
1145 }
1146 unlock_page(page);
1147
1148 return 0;
1149}
1150
83b57531 1151static int memory_failure_hugetlb(unsigned long pfn, int flags)
0348d2eb 1152{
761ad8d7
NH
1153 struct page *p = pfn_to_page(pfn);
1154 struct page *head = compound_head(p);
1155 int res;
1156 unsigned long page_flags;
1157
1158 if (TestSetPageHWPoison(head)) {
1159 pr_err("Memory failure: %#lx: already hardware poisoned\n",
1160 pfn);
1161 return 0;
1162 }
1163
1164 num_poisoned_pages_inc();
1165
1166 if (!(flags & MF_COUNT_INCREASED) && !get_hwpoison_page(p)) {
1167 /*
1168 * Check "filter hit" and "race with other subpage."
1169 */
1170 lock_page(head);
1171 if (PageHWPoison(head)) {
1172 if ((hwpoison_filter(p) && TestClearPageHWPoison(p))
1173 || (p != head && TestSetPageHWPoison(head))) {
1174 num_poisoned_pages_dec();
1175 unlock_page(head);
1176 return 0;
1177 }
1178 }
1179 unlock_page(head);
1180 dissolve_free_huge_page(p);
1181 action_result(pfn, MF_MSG_FREE_HUGE, MF_DELAYED);
1182 return 0;
1183 }
1184
1185 lock_page(head);
1186 page_flags = head->flags;
1187
1188 if (!PageHWPoison(head)) {
1189 pr_err("Memory failure: %#lx: just unpoisoned\n", pfn);
1190 num_poisoned_pages_dec();
1191 unlock_page(head);
dd6e2402 1192 put_page(head);
761ad8d7
NH
1193 return 0;
1194 }
1195
31286a84
NH
1196 /*
1197 * TODO: hwpoison for pud-sized hugetlb doesn't work right now, so
1198 * simply disable it. In order to make it work properly, we need
1199 * make sure that:
1200 * - conversion of a pud that maps an error hugetlb into hwpoison
1201 * entry properly works, and
1202 * - other mm code walking over page table is aware of pud-aligned
1203 * hwpoison entries.
1204 */
1205 if (huge_page_size(page_hstate(head)) > PMD_SIZE) {
1206 action_result(pfn, MF_MSG_NON_PMD_HUGE, MF_IGNORED);
1207 res = -EBUSY;
1208 goto out;
1209 }
1210
83b57531 1211 if (!hwpoison_user_mappings(p, pfn, flags, &head)) {
761ad8d7
NH
1212 action_result(pfn, MF_MSG_UNMAP_FAILED, MF_IGNORED);
1213 res = -EBUSY;
1214 goto out;
1215 }
1216
0348d2eb 1217 res = identify_page_state(pfn, p, page_flags);
761ad8d7
NH
1218out:
1219 unlock_page(head);
1220 return res;
1221}
1222
6100e34b
DW
1223static int memory_failure_dev_pagemap(unsigned long pfn, int flags,
1224 struct dev_pagemap *pgmap)
1225{
1226 struct page *page = pfn_to_page(pfn);
1227 const bool unmap_success = true;
1228 unsigned long size = 0;
1229 struct to_kill *tk;
1230 LIST_HEAD(tokill);
1231 int rc = -EBUSY;
1232 loff_t start;
27359fd6 1233 dax_entry_t cookie;
6100e34b
DW
1234
1235 /*
1236 * Prevent the inode from being freed while we are interrogating
1237 * the address_space, typically this would be handled by
1238 * lock_page(), but dax pages do not use the page lock. This
1239 * also prevents changes to the mapping of this pfn until
1240 * poison signaling is complete.
1241 */
27359fd6
MW
1242 cookie = dax_lock_page(page);
1243 if (!cookie)
6100e34b
DW
1244 goto out;
1245
1246 if (hwpoison_filter(page)) {
1247 rc = 0;
1248 goto unlock;
1249 }
1250
25b2995a 1251 if (pgmap->type == MEMORY_DEVICE_PRIVATE) {
6100e34b
DW
1252 /*
1253 * TODO: Handle HMM pages which may need coordination
1254 * with device-side memory.
1255 */
1256 goto unlock;
6100e34b
DW
1257 }
1258
1259 /*
1260 * Use this flag as an indication that the dax page has been
1261 * remapped UC to prevent speculative consumption of poison.
1262 */
1263 SetPageHWPoison(page);
1264
1265 /*
1266 * Unlike System-RAM there is no possibility to swap in a
1267 * different physical page at a given virtual address, so all
1268 * userspace consumption of ZONE_DEVICE memory necessitates
1269 * SIGBUS (i.e. MF_MUST_KILL)
1270 */
1271 flags |= MF_ACTION_REQUIRED | MF_MUST_KILL;
1272 collect_procs(page, &tokill, flags & MF_ACTION_REQUIRED);
1273
1274 list_for_each_entry(tk, &tokill, nd)
1275 if (tk->size_shift)
1276 size = max(size, 1UL << tk->size_shift);
1277 if (size) {
1278 /*
1279 * Unmap the largest mapping to avoid breaking up
1280 * device-dax mappings which are constant size. The
1281 * actual size of the mapping being torn down is
1282 * communicated in siginfo, see kill_proc()
1283 */
1284 start = (page->index << PAGE_SHIFT) & ~(size - 1);
1285 unmap_mapping_range(page->mapping, start, start + size, 0);
1286 }
1287 kill_procs(&tokill, flags & MF_MUST_KILL, !unmap_success, pfn, flags);
1288 rc = 0;
1289unlock:
27359fd6 1290 dax_unlock_page(page, cookie);
6100e34b
DW
1291out:
1292 /* drop pgmap ref acquired in caller */
1293 put_dev_pagemap(pgmap);
1294 action_result(pfn, MF_MSG_DAX, rc ? MF_FAILED : MF_RECOVERED);
1295 return rc;
1296}
1297
cd42f4a3
TL
1298/**
1299 * memory_failure - Handle memory failure of a page.
1300 * @pfn: Page Number of the corrupted page
cd42f4a3
TL
1301 * @flags: fine tune action taken
1302 *
1303 * This function is called by the low level machine check code
1304 * of an architecture when it detects hardware memory corruption
1305 * of a page. It tries its best to recover, which includes
1306 * dropping pages, killing processes etc.
1307 *
1308 * The function is primarily of use for corruptions that
1309 * happen outside the current execution context (e.g. when
1310 * detected by a background scrubber)
1311 *
1312 * Must run in process context (e.g. a work queue) with interrupts
1313 * enabled and no spinlocks hold.
1314 */
83b57531 1315int memory_failure(unsigned long pfn, int flags)
6a46079c 1316{
6a46079c 1317 struct page *p;
7af446a8 1318 struct page *hpage;
415c64c1 1319 struct page *orig_head;
6100e34b 1320 struct dev_pagemap *pgmap;
6a46079c 1321 int res;
524fca1e 1322 unsigned long page_flags;
6a46079c
AK
1323
1324 if (!sysctl_memory_failure_recovery)
83b57531 1325 panic("Memory failure on page %lx", pfn);
6a46079c 1326
96c804a6
DH
1327 p = pfn_to_online_page(pfn);
1328 if (!p) {
1329 if (pfn_valid(pfn)) {
1330 pgmap = get_dev_pagemap(pfn, NULL);
1331 if (pgmap)
1332 return memory_failure_dev_pagemap(pfn, flags,
1333 pgmap);
1334 }
495367c0
CY
1335 pr_err("Memory failure: %#lx: memory outside kernel control\n",
1336 pfn);
a7560fc8 1337 return -ENXIO;
6a46079c
AK
1338 }
1339
761ad8d7 1340 if (PageHuge(p))
83b57531 1341 return memory_failure_hugetlb(pfn, flags);
6a46079c 1342 if (TestSetPageHWPoison(p)) {
495367c0
CY
1343 pr_err("Memory failure: %#lx: already hardware poisoned\n",
1344 pfn);
6a46079c
AK
1345 return 0;
1346 }
1347
761ad8d7 1348 orig_head = hpage = compound_head(p);
b37ff71c 1349 num_poisoned_pages_inc();
6a46079c
AK
1350
1351 /*
1352 * We need/can do nothing about count=0 pages.
1353 * 1) it's a free page, and therefore in safe hand:
1354 * prep_new_page() will be the gate keeper.
761ad8d7 1355 * 2) it's part of a non-compound high order page.
6a46079c
AK
1356 * Implies some kernel user: cannot stop them from
1357 * R/W the page; let's pray that the page has been
1358 * used and will be freed some time later.
1359 * In fact it's dangerous to directly bump up page count from 0,
1c4c3b99 1360 * that may make page_ref_freeze()/page_ref_unfreeze() mismatch.
6a46079c 1361 */
ead07f6a 1362 if (!(flags & MF_COUNT_INCREASED) && !get_hwpoison_page(p)) {
8d22ba1b 1363 if (is_free_buddy_page(p)) {
cc637b17 1364 action_result(pfn, MF_MSG_BUDDY, MF_DELAYED);
8d22ba1b
WF
1365 return 0;
1366 } else {
cc637b17 1367 action_result(pfn, MF_MSG_KERNEL_HIGH_ORDER, MF_IGNORED);
8d22ba1b
WF
1368 return -EBUSY;
1369 }
6a46079c
AK
1370 }
1371
761ad8d7 1372 if (PageTransHuge(hpage)) {
694bf0b0 1373 if (try_to_split_thp_page(p, "Memory Failure") < 0)
415c64c1 1374 return -EBUSY;
415c64c1 1375 VM_BUG_ON_PAGE(!page_count(p), p);
415c64c1
NH
1376 }
1377
e43c3afb
WF
1378 /*
1379 * We ignore non-LRU pages for good reasons.
1380 * - PG_locked is only well defined for LRU pages and a few others
48c935ad 1381 * - to avoid races with __SetPageLocked()
e43c3afb
WF
1382 * - to avoid races with __SetPageSlab*() (and more non-atomic ops)
1383 * The check (unnecessarily) ignores LRU pages being isolated and
1384 * walked by the page reclaim code, however that's not a big loss.
1385 */
8bcb74de
NH
1386 shake_page(p, 0);
1387 /* shake_page could have turned it free. */
1388 if (!PageLRU(p) && is_free_buddy_page(p)) {
1389 if (flags & MF_COUNT_INCREASED)
1390 action_result(pfn, MF_MSG_BUDDY, MF_DELAYED);
1391 else
1392 action_result(pfn, MF_MSG_BUDDY_2ND, MF_DELAYED);
1393 return 0;
e43c3afb 1394 }
e43c3afb 1395
761ad8d7 1396 lock_page(p);
847ce401 1397
f37d4298
AK
1398 /*
1399 * The page could have changed compound pages during the locking.
1400 * If this happens just bail out.
1401 */
415c64c1 1402 if (PageCompound(p) && compound_head(p) != orig_head) {
cc637b17 1403 action_result(pfn, MF_MSG_DIFFERENT_COMPOUND, MF_IGNORED);
f37d4298
AK
1404 res = -EBUSY;
1405 goto out;
1406 }
1407
524fca1e
NH
1408 /*
1409 * We use page flags to determine what action should be taken, but
1410 * the flags can be modified by the error containment action. One
1411 * example is an mlocked page, where PG_mlocked is cleared by
1412 * page_remove_rmap() in try_to_unmap_one(). So to determine page status
1413 * correctly, we save a copy of the page flags at this time.
1414 */
7d9d46ac 1415 page_flags = p->flags;
524fca1e 1416
847ce401
WF
1417 /*
1418 * unpoison always clear PG_hwpoison inside page lock
1419 */
1420 if (!PageHWPoison(p)) {
495367c0 1421 pr_err("Memory failure: %#lx: just unpoisoned\n", pfn);
b37ff71c 1422 num_poisoned_pages_dec();
761ad8d7 1423 unlock_page(p);
dd6e2402 1424 put_page(p);
a09233f3 1425 return 0;
847ce401 1426 }
7c116f2b
WF
1427 if (hwpoison_filter(p)) {
1428 if (TestClearPageHWPoison(p))
b37ff71c 1429 num_poisoned_pages_dec();
761ad8d7 1430 unlock_page(p);
dd6e2402 1431 put_page(p);
7c116f2b
WF
1432 return 0;
1433 }
847ce401 1434
761ad8d7 1435 if (!PageTransTail(p) && !PageLRU(p))
0bc1f8b0
CY
1436 goto identify_page_state;
1437
6edd6cc6
NH
1438 /*
1439 * It's very difficult to mess with pages currently under IO
1440 * and in many cases impossible, so we just avoid it here.
1441 */
6a46079c
AK
1442 wait_on_page_writeback(p);
1443
1444 /*
1445 * Now take care of user space mappings.
e64a782f 1446 * Abort on fail: __delete_from_page_cache() assumes unmapped page.
6a46079c 1447 */
1b473bec 1448 if (!hwpoison_user_mappings(p, pfn, flags, &p)) {
cc637b17 1449 action_result(pfn, MF_MSG_UNMAP_FAILED, MF_IGNORED);
1668bfd5
WF
1450 res = -EBUSY;
1451 goto out;
1452 }
6a46079c
AK
1453
1454 /*
1455 * Torn down by someone else?
1456 */
dc2a1cbf 1457 if (PageLRU(p) && !PageSwapCache(p) && p->mapping == NULL) {
cc637b17 1458 action_result(pfn, MF_MSG_TRUNCATED_LRU, MF_IGNORED);
d95ea51e 1459 res = -EBUSY;
6a46079c
AK
1460 goto out;
1461 }
1462
0bc1f8b0 1463identify_page_state:
0348d2eb 1464 res = identify_page_state(pfn, p, page_flags);
6a46079c 1465out:
761ad8d7 1466 unlock_page(p);
6a46079c
AK
1467 return res;
1468}
cd42f4a3 1469EXPORT_SYMBOL_GPL(memory_failure);
847ce401 1470
ea8f5fb8
HY
1471#define MEMORY_FAILURE_FIFO_ORDER 4
1472#define MEMORY_FAILURE_FIFO_SIZE (1 << MEMORY_FAILURE_FIFO_ORDER)
1473
1474struct memory_failure_entry {
1475 unsigned long pfn;
ea8f5fb8
HY
1476 int flags;
1477};
1478
1479struct memory_failure_cpu {
1480 DECLARE_KFIFO(fifo, struct memory_failure_entry,
1481 MEMORY_FAILURE_FIFO_SIZE);
1482 spinlock_t lock;
1483 struct work_struct work;
1484};
1485
1486static DEFINE_PER_CPU(struct memory_failure_cpu, memory_failure_cpu);
1487
1488/**
1489 * memory_failure_queue - Schedule handling memory failure of a page.
1490 * @pfn: Page Number of the corrupted page
ea8f5fb8
HY
1491 * @flags: Flags for memory failure handling
1492 *
1493 * This function is called by the low level hardware error handler
1494 * when it detects hardware memory corruption of a page. It schedules
1495 * the recovering of error page, including dropping pages, killing
1496 * processes etc.
1497 *
1498 * The function is primarily of use for corruptions that
1499 * happen outside the current execution context (e.g. when
1500 * detected by a background scrubber)
1501 *
1502 * Can run in IRQ context.
1503 */
83b57531 1504void memory_failure_queue(unsigned long pfn, int flags)
ea8f5fb8
HY
1505{
1506 struct memory_failure_cpu *mf_cpu;
1507 unsigned long proc_flags;
1508 struct memory_failure_entry entry = {
1509 .pfn = pfn,
ea8f5fb8
HY
1510 .flags = flags,
1511 };
1512
1513 mf_cpu = &get_cpu_var(memory_failure_cpu);
1514 spin_lock_irqsave(&mf_cpu->lock, proc_flags);
498d319b 1515 if (kfifo_put(&mf_cpu->fifo, entry))
ea8f5fb8
HY
1516 schedule_work_on(smp_processor_id(), &mf_cpu->work);
1517 else
8e33a52f 1518 pr_err("Memory failure: buffer overflow when queuing memory failure at %#lx\n",
ea8f5fb8
HY
1519 pfn);
1520 spin_unlock_irqrestore(&mf_cpu->lock, proc_flags);
1521 put_cpu_var(memory_failure_cpu);
1522}
1523EXPORT_SYMBOL_GPL(memory_failure_queue);
1524
1525static void memory_failure_work_func(struct work_struct *work)
1526{
1527 struct memory_failure_cpu *mf_cpu;
1528 struct memory_failure_entry entry = { 0, };
1529 unsigned long proc_flags;
1530 int gotten;
1531
06202231 1532 mf_cpu = container_of(work, struct memory_failure_cpu, work);
ea8f5fb8
HY
1533 for (;;) {
1534 spin_lock_irqsave(&mf_cpu->lock, proc_flags);
1535 gotten = kfifo_get(&mf_cpu->fifo, &entry);
1536 spin_unlock_irqrestore(&mf_cpu->lock, proc_flags);
1537 if (!gotten)
1538 break;
cf870c70 1539 if (entry.flags & MF_SOFT_OFFLINE)
feec24a6 1540 soft_offline_page(entry.pfn, entry.flags);
cf870c70 1541 else
83b57531 1542 memory_failure(entry.pfn, entry.flags);
ea8f5fb8
HY
1543 }
1544}
1545
06202231
JM
1546/*
1547 * Process memory_failure work queued on the specified CPU.
1548 * Used to avoid return-to-userspace racing with the memory_failure workqueue.
1549 */
1550void memory_failure_queue_kick(int cpu)
1551{
1552 struct memory_failure_cpu *mf_cpu;
1553
1554 mf_cpu = &per_cpu(memory_failure_cpu, cpu);
1555 cancel_work_sync(&mf_cpu->work);
1556 memory_failure_work_func(&mf_cpu->work);
1557}
1558
ea8f5fb8
HY
1559static int __init memory_failure_init(void)
1560{
1561 struct memory_failure_cpu *mf_cpu;
1562 int cpu;
1563
1564 for_each_possible_cpu(cpu) {
1565 mf_cpu = &per_cpu(memory_failure_cpu, cpu);
1566 spin_lock_init(&mf_cpu->lock);
1567 INIT_KFIFO(mf_cpu->fifo);
1568 INIT_WORK(&mf_cpu->work, memory_failure_work_func);
1569 }
1570
1571 return 0;
1572}
1573core_initcall(memory_failure_init);
1574
a5f65109
NH
1575#define unpoison_pr_info(fmt, pfn, rs) \
1576({ \
1577 if (__ratelimit(rs)) \
1578 pr_info(fmt, pfn); \
1579})
1580
847ce401
WF
1581/**
1582 * unpoison_memory - Unpoison a previously poisoned page
1583 * @pfn: Page number of the to be unpoisoned page
1584 *
1585 * Software-unpoison a page that has been poisoned by
1586 * memory_failure() earlier.
1587 *
1588 * This is only done on the software-level, so it only works
1589 * for linux injected failures, not real hardware failures
1590 *
1591 * Returns 0 for success, otherwise -errno.
1592 */
1593int unpoison_memory(unsigned long pfn)
1594{
1595 struct page *page;
1596 struct page *p;
1597 int freeit = 0;
a5f65109
NH
1598 static DEFINE_RATELIMIT_STATE(unpoison_rs, DEFAULT_RATELIMIT_INTERVAL,
1599 DEFAULT_RATELIMIT_BURST);
847ce401
WF
1600
1601 if (!pfn_valid(pfn))
1602 return -ENXIO;
1603
1604 p = pfn_to_page(pfn);
1605 page = compound_head(p);
1606
1607 if (!PageHWPoison(p)) {
495367c0 1608 unpoison_pr_info("Unpoison: Page was already unpoisoned %#lx\n",
a5f65109 1609 pfn, &unpoison_rs);
847ce401
WF
1610 return 0;
1611 }
1612
230ac719 1613 if (page_count(page) > 1) {
495367c0 1614 unpoison_pr_info("Unpoison: Someone grabs the hwpoison page %#lx\n",
a5f65109 1615 pfn, &unpoison_rs);
230ac719
NH
1616 return 0;
1617 }
1618
1619 if (page_mapped(page)) {
495367c0 1620 unpoison_pr_info("Unpoison: Someone maps the hwpoison page %#lx\n",
a5f65109 1621 pfn, &unpoison_rs);
230ac719
NH
1622 return 0;
1623 }
1624
1625 if (page_mapping(page)) {
495367c0 1626 unpoison_pr_info("Unpoison: the hwpoison page has non-NULL mapping %#lx\n",
a5f65109 1627 pfn, &unpoison_rs);
230ac719
NH
1628 return 0;
1629 }
1630
0cea3fdc
WL
1631 /*
1632 * unpoison_memory() can encounter thp only when the thp is being
1633 * worked by memory_failure() and the page lock is not held yet.
1634 * In such case, we yield to memory_failure() and make unpoison fail.
1635 */
e76d30e2 1636 if (!PageHuge(page) && PageTransHuge(page)) {
495367c0 1637 unpoison_pr_info("Unpoison: Memory failure is now running on %#lx\n",
a5f65109 1638 pfn, &unpoison_rs);
ead07f6a 1639 return 0;
0cea3fdc
WL
1640 }
1641
ead07f6a 1642 if (!get_hwpoison_page(p)) {
847ce401 1643 if (TestClearPageHWPoison(p))
8e30456b 1644 num_poisoned_pages_dec();
495367c0 1645 unpoison_pr_info("Unpoison: Software-unpoisoned free page %#lx\n",
a5f65109 1646 pfn, &unpoison_rs);
847ce401
WF
1647 return 0;
1648 }
1649
7eaceacc 1650 lock_page(page);
847ce401
WF
1651 /*
1652 * This test is racy because PG_hwpoison is set outside of page lock.
1653 * That's acceptable because that won't trigger kernel panic. Instead,
1654 * the PG_hwpoison page will be caught and isolated on the entrance to
1655 * the free buddy page pool.
1656 */
c9fbdd5f 1657 if (TestClearPageHWPoison(page)) {
495367c0 1658 unpoison_pr_info("Unpoison: Software-unpoisoned page %#lx\n",
a5f65109 1659 pfn, &unpoison_rs);
b37ff71c 1660 num_poisoned_pages_dec();
847ce401
WF
1661 freeit = 1;
1662 }
1663 unlock_page(page);
1664
dd6e2402 1665 put_page(page);
3ba5eebc 1666 if (freeit && !(pfn == my_zero_pfn(0) && page_count(p) == 1))
dd6e2402 1667 put_page(page);
847ce401
WF
1668
1669 return 0;
1670}
1671EXPORT_SYMBOL(unpoison_memory);
facb6011 1672
666feb21 1673static struct page *new_page(struct page *p, unsigned long private)
facb6011 1674{
19fc7bed
JK
1675 struct migration_target_control mtc = {
1676 .nid = page_to_nid(p),
1677 .gfp_mask = GFP_USER | __GFP_MOVABLE | __GFP_RETRY_MAYFAIL,
1678 };
94310cbc 1679
19fc7bed 1680 return alloc_migration_target(p, (unsigned long)&mtc);
facb6011
AK
1681}
1682
1683/*
1684 * Safely get reference count of an arbitrary page.
1685 * Returns 0 for a free page, -EIO for a zero refcount page
1686 * that is not free, and 1 for any other page type.
1687 * For 1 the page is returned with increased page count, otherwise not.
1688 */
af8fae7c 1689static int __get_any_page(struct page *p, unsigned long pfn, int flags)
facb6011
AK
1690{
1691 int ret;
1692
1693 if (flags & MF_COUNT_INCREASED)
1694 return 1;
1695
d950b958
NH
1696 /*
1697 * When the target page is a free hugepage, just remove it
1698 * from free hugepage list.
1699 */
ead07f6a 1700 if (!get_hwpoison_page(p)) {
d950b958 1701 if (PageHuge(p)) {
71dd0b8a 1702 pr_info("%s: %#lx free huge page\n", __func__, pfn);
af8fae7c 1703 ret = 0;
d950b958 1704 } else if (is_free_buddy_page(p)) {
71dd0b8a 1705 pr_info("%s: %#lx free buddy page\n", __func__, pfn);
facb6011
AK
1706 ret = 0;
1707 } else {
71dd0b8a
BP
1708 pr_info("%s: %#lx: unknown zero refcount page type %lx\n",
1709 __func__, pfn, p->flags);
facb6011
AK
1710 ret = -EIO;
1711 }
1712 } else {
1713 /* Not a free page */
1714 ret = 1;
1715 }
facb6011
AK
1716 return ret;
1717}
1718
af8fae7c
NH
1719static int get_any_page(struct page *page, unsigned long pfn, int flags)
1720{
1721 int ret = __get_any_page(page, pfn, flags);
1722
85fbe5d1
YX
1723 if (ret == 1 && !PageHuge(page) &&
1724 !PageLRU(page) && !__PageMovable(page)) {
af8fae7c
NH
1725 /*
1726 * Try to free it.
1727 */
dd6e2402 1728 put_page(page);
af8fae7c
NH
1729 shake_page(page, 1);
1730
1731 /*
1732 * Did it turn free?
1733 */
1734 ret = __get_any_page(page, pfn, 0);
d96b339f 1735 if (ret == 1 && !PageLRU(page)) {
4f32be67 1736 /* Drop page reference which is from __get_any_page() */
dd6e2402 1737 put_page(page);
82a2481e
AK
1738 pr_info("soft_offline: %#lx: unknown non LRU page type %lx (%pGp)\n",
1739 pfn, page->flags, &page->flags);
af8fae7c
NH
1740 return -EIO;
1741 }
1742 }
1743 return ret;
1744}
1745
6b9a217e 1746static bool isolate_page(struct page *page, struct list_head *pagelist)
d950b958 1747{
6b9a217e
OS
1748 bool isolated = false;
1749 bool lru = PageLRU(page);
d950b958 1750
6b9a217e
OS
1751 if (PageHuge(page)) {
1752 isolated = isolate_huge_page(page, pagelist);
1753 } else {
1754 if (lru)
1755 isolated = !isolate_lru_page(page);
1756 else
1757 isolated = !isolate_movable_page(page, ISOLATE_UNEVICTABLE);
1758
1759 if (isolated)
1760 list_add(&page->lru, pagelist);
0ebff32c 1761 }
d950b958 1762
6b9a217e
OS
1763 if (isolated && lru)
1764 inc_node_page_state(page, NR_ISOLATED_ANON +
1765 page_is_file_lru(page));
1766
03613808 1767 /*
6b9a217e
OS
1768 * If we succeed to isolate the page, we grabbed another refcount on
1769 * the page, so we can safely drop the one we got from get_any_pages().
1770 * If we failed to isolate the page, it means that we cannot go further
1771 * and we will return an error, so drop the reference we got from
1772 * get_any_pages() as well.
03613808 1773 */
6b9a217e
OS
1774 put_page(page);
1775 return isolated;
d950b958
NH
1776}
1777
6b9a217e
OS
1778/*
1779 * __soft_offline_page handles hugetlb-pages and non-hugetlb pages.
1780 * If the page is a non-dirty unmapped page-cache page, it simply invalidates.
1781 * If the page is mapped, it migrates the contents over.
1782 */
1783static int __soft_offline_page(struct page *page)
af8fae7c 1784{
6b9a217e 1785 int ret = 0;
af8fae7c 1786 unsigned long pfn = page_to_pfn(page);
6b9a217e
OS
1787 struct page *hpage = compound_head(page);
1788 char const *msg_page[] = {"page", "hugepage"};
1789 bool huge = PageHuge(page);
1790 LIST_HEAD(pagelist);
facb6011 1791
facb6011 1792 /*
af8fae7c
NH
1793 * Check PageHWPoison again inside page lock because PageHWPoison
1794 * is set by memory_failure() outside page lock. Note that
1795 * memory_failure() also double-checks PageHWPoison inside page lock,
1796 * so there's no race between soft_offline_page() and memory_failure().
facb6011 1797 */
0ebff32c 1798 lock_page(page);
6b9a217e
OS
1799 if (!PageHuge(page))
1800 wait_on_page_writeback(page);
af8fae7c
NH
1801 if (PageHWPoison(page)) {
1802 unlock_page(page);
dd6e2402 1803 put_page(page);
af8fae7c
NH
1804 pr_info("soft offline: %#lx page already poisoned\n", pfn);
1805 return -EBUSY;
1806 }
6b9a217e
OS
1807
1808 if (!PageHuge(page))
1809 /*
1810 * Try to invalidate first. This should work for
1811 * non dirty unmapped page cache pages.
1812 */
1813 ret = invalidate_inode_page(page);
facb6011 1814 unlock_page(page);
6b9a217e 1815
facb6011 1816 /*
facb6011
AK
1817 * RED-PEN would be better to keep it isolated here, but we
1818 * would need to fix isolation locking first.
1819 */
6b9a217e 1820 if (ret) {
fb46e735 1821 pr_info("soft_offline: %#lx: invalidated\n", pfn);
6b9a217e 1822 page_handle_poison(page, false, true);
af8fae7c 1823 return 0;
facb6011
AK
1824 }
1825
6b9a217e 1826 if (isolate_page(hpage, &pagelist)) {
68711a74 1827 ret = migrate_pages(&pagelist, new_page, NULL, MPOL_MF_MOVE_ALL,
9c620e2b 1828 MIGRATE_SYNC, MR_MEMORY_FAILURE);
79f5f8fa 1829 if (!ret) {
6b9a217e
OS
1830 bool release = !huge;
1831
1832 if (!page_handle_poison(page, huge, release))
1833 ret = -EBUSY;
79f5f8fa 1834 } else {
85fbe5d1
YX
1835 if (!list_empty(&pagelist))
1836 putback_movable_pages(&pagelist);
59c82b70 1837
6b9a217e
OS
1838 pr_info("soft offline: %#lx: %s migration failed %d, type %lx (%pGp)\n",
1839 pfn, msg_page[huge], ret, page->flags, &page->flags);
facb6011
AK
1840 if (ret > 0)
1841 ret = -EIO;
1842 }
1843 } else {
6b9a217e
OS
1844 pr_info("soft offline: %#lx: %s isolation failed: %d, page count %d, type %lx (%pGp)\n",
1845 pfn, msg_page[huge], ret, page_count(page), page->flags, &page->flags);
1846 ret = -EBUSY;
facb6011 1847 }
facb6011
AK
1848 return ret;
1849}
86e05773 1850
6b9a217e 1851static int soft_offline_in_use_page(struct page *page)
acc14dc4 1852{
acc14dc4
NH
1853 struct page *hpage = compound_head(page);
1854
694bf0b0
OS
1855 if (!PageHuge(page) && PageTransHuge(hpage))
1856 if (try_to_split_thp_page(page, "soft offline") < 0)
acc14dc4 1857 return -EBUSY;
6b9a217e 1858 return __soft_offline_page(page);
acc14dc4
NH
1859}
1860
d4ae9916 1861static int soft_offline_free_page(struct page *page)
acc14dc4 1862{
6b9a217e 1863 int rc = 0;
acc14dc4 1864
6b9a217e
OS
1865 if (!page_handle_poison(page, true, false))
1866 rc = -EBUSY;
06be6ff3 1867
d4ae9916 1868 return rc;
acc14dc4
NH
1869}
1870
86e05773
WL
1871/**
1872 * soft_offline_page - Soft offline a page.
feec24a6 1873 * @pfn: pfn to soft-offline
86e05773
WL
1874 * @flags: flags. Same as memory_failure().
1875 *
1876 * Returns 0 on success, otherwise negated errno.
1877 *
1878 * Soft offline a page, by migration or invalidation,
1879 * without killing anything. This is for the case when
1880 * a page is not corrupted yet (so it's still valid to access),
1881 * but has had a number of corrected errors and is better taken
1882 * out.
1883 *
1884 * The actual policy on when to do that is maintained by
1885 * user space.
1886 *
1887 * This should never impact any application or cause data loss,
1888 * however it might take some time.
1889 *
1890 * This is not a 100% solution for all memory, but tries to be
1891 * ``good enough'' for the majority of memory.
1892 */
feec24a6 1893int soft_offline_page(unsigned long pfn, int flags)
86e05773
WL
1894{
1895 int ret;
feec24a6 1896 struct page *page;
86e05773 1897
feec24a6
NH
1898 if (!pfn_valid(pfn))
1899 return -ENXIO;
1900 /* Only online pages can be soft-offlined (esp., not ZONE_DEVICE). */
1901 page = pfn_to_online_page(pfn);
1902 if (!page)
86a66810 1903 return -EIO;
86a66810 1904
86e05773
WL
1905 if (PageHWPoison(page)) {
1906 pr_info("soft offline: %#lx page already poisoned\n", pfn);
1e0e635b 1907 if (flags & MF_COUNT_INCREASED)
dd6e2402 1908 put_page(page);
86e05773
WL
1909 return -EBUSY;
1910 }
86e05773 1911
bfc8c901 1912 get_online_mems();
86e05773 1913 ret = get_any_page(page, pfn, flags);
bfc8c901 1914 put_online_mems();
4e41a30c 1915
acc14dc4 1916 if (ret > 0)
6b9a217e 1917 ret = soft_offline_in_use_page(page);
acc14dc4 1918 else if (ret == 0)
d4ae9916 1919 ret = soft_offline_free_page(page);
4e41a30c 1920
86e05773
WL
1921 return ret;
1922}