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