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