1 /*
2 * Copyright (C) 2008, 2009 Intel Corporation
3 * Authors: Andi Kleen, Fengguang Wu
4 *
5 * This software may be redistributed and/or modified under the terms of
6 * the GNU General Public License ("GPL") version 2 only as published by the
7 * Free Software Foundation.
8 *
9 * High level machine check handler. Handles pages reported by the
10 * hardware as being corrupted usually due to a multi-bit ECC memory or cache
11 * failure.
12 *
13 * In addition there is a "soft offline" entry point that allows stop using
14 * not-yet-corrupted-by-suspicious pages without killing anything.
15 *
16 * Handles page cache pages in various states. The tricky part
17 * here is that we can access any page asynchronously in respect to
18 * other VM users, because memory failures could happen anytime and
19 * anywhere. This could violate some of their assumptions. This is why
20 * this code has to be extremely careful. Generally it tries to use
21 * normal locking rules, as in get the standard locks, even if that means
22 * the error handling takes potentially a long time.
23 *
24 * There are several operations here with exponential complexity because
25 * of unsuitable VM data structures. For example the operation to map back
26 * from RMAP chains to processes has to walk the complete process list and
27 * has non linear complexity with the number. But since memory corruptions
28 * are rare we hope to get away with this. This avoids impacting the core
29 * VM.
30 */
31
32 /*
33 * Notebook:
34 * - hugetlb needs more code
35 * - kcore/oldmem/vmcore/mem/kmem check for hwpoison pages
36 * - pass bad pages to kdump next kernel
37 */
38 #include <linux/kernel.h>
39 #include <linux/mm.h>
40 #include <linux/page-flags.h>
41 #include <linux/kernel-page-flags.h>
42 #include <linux/sched.h>
43 #include <linux/ksm.h>
44 #include <linux/rmap.h>
45 #include <linux/export.h>
46 #include <linux/pagemap.h>
47 #include <linux/swap.h>
48 #include <linux/backing-dev.h>
49 #include <linux/migrate.h>
50 #include <linux/page-isolation.h>
51 #include <linux/suspend.h>
52 #include <linux/slab.h>
53 #include <linux/swapops.h>
54 #include <linux/hugetlb.h>
55 #include <linux/memory_hotplug.h>
56 #include <linux/mm_inline.h>
57 #include <linux/kfifo.h>
58 #include "internal.h"
59
60 int sysctl_memory_failure_early_kill __read_mostly = 0;
61
62 int sysctl_memory_failure_recovery __read_mostly = 1;
63
64 atomic_long_t num_poisoned_pages __read_mostly = ATOMIC_LONG_INIT(0);
65
66 #if defined(CONFIG_HWPOISON_INJECT) || defined(CONFIG_HWPOISON_INJECT_MODULE)
67
68 u32 hwpoison_filter_enable = 0;
69 u32 hwpoison_filter_dev_major = ~0U;
70 u32 hwpoison_filter_dev_minor = ~0U;
71 u64 hwpoison_filter_flags_mask;
72 u64 hwpoison_filter_flags_value;
73 EXPORT_SYMBOL_GPL(hwpoison_filter_enable);
74 EXPORT_SYMBOL_GPL(hwpoison_filter_dev_major);
75 EXPORT_SYMBOL_GPL(hwpoison_filter_dev_minor);
76 EXPORT_SYMBOL_GPL(hwpoison_filter_flags_mask);
77 EXPORT_SYMBOL_GPL(hwpoison_filter_flags_value);
78
hwpoison_filter_dev(struct page * p)79 static int hwpoison_filter_dev(struct page *p)
80 {
81 struct address_space *mapping;
82 dev_t dev;
83
84 if (hwpoison_filter_dev_major == ~0U &&
85 hwpoison_filter_dev_minor == ~0U)
86 return 0;
87
88 /*
89 * page_mapping() does not accept slab pages.
90 */
91 if (PageSlab(p))
92 return -EINVAL;
93
94 mapping = page_mapping(p);
95 if (mapping == NULL || mapping->host == NULL)
96 return -EINVAL;
97
98 dev = mapping->host->i_sb->s_dev;
99 if (hwpoison_filter_dev_major != ~0U &&
100 hwpoison_filter_dev_major != MAJOR(dev))
101 return -EINVAL;
102 if (hwpoison_filter_dev_minor != ~0U &&
103 hwpoison_filter_dev_minor != MINOR(dev))
104 return -EINVAL;
105
106 return 0;
107 }
108
hwpoison_filter_flags(struct page * p)109 static int hwpoison_filter_flags(struct page *p)
110 {
111 if (!hwpoison_filter_flags_mask)
112 return 0;
113
114 if ((stable_page_flags(p) & hwpoison_filter_flags_mask) ==
115 hwpoison_filter_flags_value)
116 return 0;
117 else
118 return -EINVAL;
119 }
120
121 /*
122 * This allows stress tests to limit test scope to a collection of tasks
123 * by putting them under some memcg. This prevents killing unrelated/important
124 * processes such as /sbin/init. Note that the target task may share clean
125 * pages with init (eg. libc text), which is harmless. If the target task
126 * share _dirty_ pages with another task B, the test scheme must make sure B
127 * is also included in the memcg. At last, due to race conditions this filter
128 * can only guarantee that the page either belongs to the memcg tasks, or is
129 * a freed page.
130 */
131 #ifdef CONFIG_MEMCG_SWAP
132 u64 hwpoison_filter_memcg;
133 EXPORT_SYMBOL_GPL(hwpoison_filter_memcg);
hwpoison_filter_task(struct page * p)134 static int hwpoison_filter_task(struct page *p)
135 {
136 struct mem_cgroup *mem;
137 struct cgroup_subsys_state *css;
138 unsigned long ino;
139
140 if (!hwpoison_filter_memcg)
141 return 0;
142
143 mem = try_get_mem_cgroup_from_page(p);
144 if (!mem)
145 return -EINVAL;
146
147 css = mem_cgroup_css(mem);
148 ino = cgroup_ino(css->cgroup);
149 css_put(css);
150
151 if (ino != hwpoison_filter_memcg)
152 return -EINVAL;
153
154 return 0;
155 }
156 #else
hwpoison_filter_task(struct page * p)157 static int hwpoison_filter_task(struct page *p) { return 0; }
158 #endif
159
hwpoison_filter(struct page * p)160 int hwpoison_filter(struct page *p)
161 {
162 if (!hwpoison_filter_enable)
163 return 0;
164
165 if (hwpoison_filter_dev(p))
166 return -EINVAL;
167
168 if (hwpoison_filter_flags(p))
169 return -EINVAL;
170
171 if (hwpoison_filter_task(p))
172 return -EINVAL;
173
174 return 0;
175 }
176 #else
hwpoison_filter(struct page * p)177 int hwpoison_filter(struct page *p)
178 {
179 return 0;
180 }
181 #endif
182
183 EXPORT_SYMBOL_GPL(hwpoison_filter);
184
185 /*
186 * Send all the processes who have the page mapped a signal.
187 * ``action optional'' if they are not immediately affected by the error
188 * ``action required'' if error happened in current execution context
189 */
kill_proc(struct task_struct * t,unsigned long addr,int trapno,unsigned long pfn,struct page * page,int flags)190 static int kill_proc(struct task_struct *t, unsigned long addr, int trapno,
191 unsigned long pfn, struct page *page, int flags)
192 {
193 struct siginfo si;
194 int ret;
195
196 printk(KERN_ERR
197 "MCE %#lx: Killing %s:%d due to hardware memory corruption\n",
198 pfn, t->comm, t->pid);
199 si.si_signo = SIGBUS;
200 si.si_errno = 0;
201 si.si_addr = (void *)addr;
202 #ifdef __ARCH_SI_TRAPNO
203 si.si_trapno = trapno;
204 #endif
205 si.si_addr_lsb = compound_order(compound_head(page)) + PAGE_SHIFT;
206
207 if ((flags & MF_ACTION_REQUIRED) && t->mm == current->mm) {
208 si.si_code = BUS_MCEERR_AR;
209 ret = force_sig_info(SIGBUS, &si, current);
210 } else {
211 /*
212 * Don't use force here, it's convenient if the signal
213 * can be temporarily blocked.
214 * This could cause a loop when the user sets SIGBUS
215 * to SIG_IGN, but hopefully no one will do that?
216 */
217 si.si_code = BUS_MCEERR_AO;
218 ret = send_sig_info(SIGBUS, &si, t); /* synchronous? */
219 }
220 if (ret < 0)
221 printk(KERN_INFO "MCE: Error sending signal to %s:%d: %d\n",
222 t->comm, t->pid, ret);
223 return ret;
224 }
225
226 /*
227 * When a unknown page type is encountered drain as many buffers as possible
228 * in the hope to turn the page into a LRU or free page, which we can handle.
229 */
shake_page(struct page * p,int access)230 void shake_page(struct page *p, int access)
231 {
232 if (!PageSlab(p)) {
233 lru_add_drain_all();
234 if (PageLRU(p))
235 return;
236 drain_all_pages();
237 if (PageLRU(p) || is_free_buddy_page(p))
238 return;
239 }
240
241 /*
242 * Only call shrink_slab here (which would also shrink other caches) if
243 * access is not potentially fatal.
244 */
245 if (access) {
246 int nr;
247 int nid = page_to_nid(p);
248 do {
249 struct shrink_control shrink = {
250 .gfp_mask = GFP_KERNEL,
251 };
252 node_set(nid, shrink.nodes_to_scan);
253
254 nr = shrink_slab(&shrink, 1000, 1000);
255 if (page_count(p) == 1)
256 break;
257 } while (nr > 10);
258 }
259 }
260 EXPORT_SYMBOL_GPL(shake_page);
261
262 /*
263 * Kill all processes that have a poisoned page mapped and then isolate
264 * the page.
265 *
266 * General strategy:
267 * Find all processes having the page mapped and kill them.
268 * But we keep a page reference around so that the page is not
269 * actually freed yet.
270 * Then stash the page away
271 *
272 * There's no convenient way to get back to mapped processes
273 * from the VMAs. So do a brute-force search over all
274 * running processes.
275 *
276 * Remember that machine checks are not common (or rather
277 * if they are common you have other problems), so this shouldn't
278 * be a performance issue.
279 *
280 * Also there are some races possible while we get from the
281 * error detection to actually handle it.
282 */
283
284 struct to_kill {
285 struct list_head nd;
286 struct task_struct *tsk;
287 unsigned long addr;
288 char addr_valid;
289 };
290
291 /*
292 * Failure handling: if we can't find or can't kill a process there's
293 * not much we can do. We just print a message and ignore otherwise.
294 */
295
296 /*
297 * Schedule a process for later kill.
298 * Uses GFP_ATOMIC allocations to avoid potential recursions in the VM.
299 * TBD would GFP_NOIO be enough?
300 */
add_to_kill(struct task_struct * tsk,struct page * p,struct vm_area_struct * vma,struct list_head * to_kill,struct to_kill ** tkc)301 static void add_to_kill(struct task_struct *tsk, struct page *p,
302 struct vm_area_struct *vma,
303 struct list_head *to_kill,
304 struct to_kill **tkc)
305 {
306 struct to_kill *tk;
307
308 if (*tkc) {
309 tk = *tkc;
310 *tkc = NULL;
311 } else {
312 tk = kmalloc(sizeof(struct to_kill), GFP_ATOMIC);
313 if (!tk) {
314 printk(KERN_ERR
315 "MCE: Out of memory while machine check handling\n");
316 return;
317 }
318 }
319 tk->addr = page_address_in_vma(p, vma);
320 tk->addr_valid = 1;
321
322 /*
323 * In theory we don't have to kill when the page was
324 * munmaped. But it could be also a mremap. Since that's
325 * likely very rare kill anyways just out of paranoia, but use
326 * a SIGKILL because the error is not contained anymore.
327 */
328 if (tk->addr == -EFAULT) {
329 pr_info("MCE: Unable to find user space address %lx in %s\n",
330 page_to_pfn(p), tsk->comm);
331 tk->addr_valid = 0;
332 }
333 get_task_struct(tsk);
334 tk->tsk = tsk;
335 list_add_tail(&tk->nd, to_kill);
336 }
337
338 /*
339 * Kill the processes that have been collected earlier.
340 *
341 * Only do anything when DOIT is set, otherwise just free the list
342 * (this is used for clean pages which do not need killing)
343 * Also when FAIL is set do a force kill because something went
344 * wrong earlier.
345 */
kill_procs(struct list_head * to_kill,int forcekill,int trapno,int fail,struct page * page,unsigned long pfn,int flags)346 static void kill_procs(struct list_head *to_kill, int forcekill, int trapno,
347 int fail, struct page *page, unsigned long pfn,
348 int flags)
349 {
350 struct to_kill *tk, *next;
351
352 list_for_each_entry_safe (tk, next, to_kill, nd) {
353 if (forcekill) {
354 /*
355 * In case something went wrong with munmapping
356 * make sure the process doesn't catch the
357 * signal and then access the memory. Just kill it.
358 */
359 if (fail || tk->addr_valid == 0) {
360 printk(KERN_ERR
361 "MCE %#lx: forcibly killing %s:%d because of failure to unmap corrupted page\n",
362 pfn, tk->tsk->comm, tk->tsk->pid);
363 force_sig(SIGKILL, tk->tsk);
364 }
365
366 /*
367 * In theory the process could have mapped
368 * something else on the address in-between. We could
369 * check for that, but we need to tell the
370 * process anyways.
371 */
372 else if (kill_proc(tk->tsk, tk->addr, trapno,
373 pfn, page, flags) < 0)
374 printk(KERN_ERR
375 "MCE %#lx: Cannot send advisory machine check signal to %s:%d\n",
376 pfn, tk->tsk->comm, tk->tsk->pid);
377 }
378 put_task_struct(tk->tsk);
379 kfree(tk);
380 }
381 }
382
383 /*
384 * Find a dedicated thread which is supposed to handle SIGBUS(BUS_MCEERR_AO)
385 * on behalf of the thread group. Return task_struct of the (first found)
386 * dedicated thread if found, and return NULL otherwise.
387 *
388 * We already hold read_lock(&tasklist_lock) in the caller, so we don't
389 * have to call rcu_read_lock/unlock() in this function.
390 */
find_early_kill_thread(struct task_struct * tsk)391 static struct task_struct *find_early_kill_thread(struct task_struct *tsk)
392 {
393 struct task_struct *t;
394
395 for_each_thread(tsk, t)
396 if ((t->flags & PF_MCE_PROCESS) && (t->flags & PF_MCE_EARLY))
397 return t;
398 return NULL;
399 }
400
401 /*
402 * Determine whether a given process is "early kill" process which expects
403 * to be signaled when some page under the process is hwpoisoned.
404 * Return task_struct of the dedicated thread (main thread unless explicitly
405 * specified) if the process is "early kill," and otherwise returns NULL.
406 */
task_early_kill(struct task_struct * tsk,int force_early)407 static struct task_struct *task_early_kill(struct task_struct *tsk,
408 int force_early)
409 {
410 struct task_struct *t;
411 if (!tsk->mm)
412 return NULL;
413 if (force_early)
414 return tsk;
415 t = find_early_kill_thread(tsk);
416 if (t)
417 return t;
418 if (sysctl_memory_failure_early_kill)
419 return tsk;
420 return NULL;
421 }
422
423 /*
424 * Collect processes when the error hit an anonymous page.
425 */
collect_procs_anon(struct page * page,struct list_head * to_kill,struct to_kill ** tkc,int force_early)426 static void collect_procs_anon(struct page *page, struct list_head *to_kill,
427 struct to_kill **tkc, int force_early)
428 {
429 struct vm_area_struct *vma;
430 struct task_struct *tsk;
431 struct anon_vma *av;
432 pgoff_t pgoff;
433
434 av = page_lock_anon_vma_read(page);
435 if (av == NULL) /* Not actually mapped anymore */
436 return;
437
438 pgoff = page_to_pgoff(page);
439 read_lock(&tasklist_lock);
440 for_each_process (tsk) {
441 struct anon_vma_chain *vmac;
442 struct task_struct *t = task_early_kill(tsk, force_early);
443
444 if (!t)
445 continue;
446 anon_vma_interval_tree_foreach(vmac, &av->rb_root,
447 pgoff, pgoff) {
448 vma = vmac->vma;
449 if (!page_mapped_in_vma(page, vma))
450 continue;
451 if (vma->vm_mm == t->mm)
452 add_to_kill(t, page, vma, to_kill, tkc);
453 }
454 }
455 read_unlock(&tasklist_lock);
456 page_unlock_anon_vma_read(av);
457 }
458
459 /*
460 * Collect processes when the error hit a file mapped page.
461 */
collect_procs_file(struct page * page,struct list_head * to_kill,struct to_kill ** tkc,int force_early)462 static void collect_procs_file(struct page *page, struct list_head *to_kill,
463 struct to_kill **tkc, int force_early)
464 {
465 struct vm_area_struct *vma;
466 struct task_struct *tsk;
467 struct address_space *mapping = page->mapping;
468
469 mutex_lock(&mapping->i_mmap_mutex);
470 read_lock(&tasklist_lock);
471 for_each_process(tsk) {
472 pgoff_t pgoff = page_to_pgoff(page);
473 struct task_struct *t = task_early_kill(tsk, force_early);
474
475 if (!t)
476 continue;
477 vma_interval_tree_foreach(vma, &mapping->i_mmap, pgoff,
478 pgoff) {
479 /*
480 * Send early kill signal to tasks where a vma covers
481 * the page but the corrupted page is not necessarily
482 * mapped it in its pte.
483 * Assume applications who requested early kill want
484 * to be informed of all such data corruptions.
485 */
486 if (vma->vm_mm == t->mm)
487 add_to_kill(t, page, vma, to_kill, tkc);
488 }
489 }
490 read_unlock(&tasklist_lock);
491 mutex_unlock(&mapping->i_mmap_mutex);
492 }
493
494 /*
495 * Collect the processes who have the corrupted page mapped to kill.
496 * This is done in two steps for locking reasons.
497 * First preallocate one tokill structure outside the spin locks,
498 * so that we can kill at least one process reasonably reliable.
499 */
collect_procs(struct page * page,struct list_head * tokill,int force_early)500 static void collect_procs(struct page *page, struct list_head *tokill,
501 int force_early)
502 {
503 struct to_kill *tk;
504
505 if (!page->mapping)
506 return;
507
508 tk = kmalloc(sizeof(struct to_kill), GFP_NOIO);
509 if (!tk)
510 return;
511 if (PageAnon(page))
512 collect_procs_anon(page, tokill, &tk, force_early);
513 else
514 collect_procs_file(page, tokill, &tk, force_early);
515 kfree(tk);
516 }
517
518 /*
519 * Error handlers for various types of pages.
520 */
521
522 enum outcome {
523 IGNORED, /* Error: cannot be handled */
524 FAILED, /* Error: handling failed */
525 DELAYED, /* Will be handled later */
526 RECOVERED, /* Successfully recovered */
527 };
528
529 static const char *action_name[] = {
530 [IGNORED] = "Ignored",
531 [FAILED] = "Failed",
532 [DELAYED] = "Delayed",
533 [RECOVERED] = "Recovered",
534 };
535
536 /*
537 * XXX: It is possible that a page is isolated from LRU cache,
538 * and then kept in swap cache or failed to remove from page cache.
539 * The page count will stop it from being freed by unpoison.
540 * Stress tests should be aware of this memory leak problem.
541 */
delete_from_lru_cache(struct page * p)542 static int delete_from_lru_cache(struct page *p)
543 {
544 if (!isolate_lru_page(p)) {
545 /*
546 * Clear sensible page flags, so that the buddy system won't
547 * complain when the page is unpoison-and-freed.
548 */
549 ClearPageActive(p);
550 ClearPageUnevictable(p);
551
552 /*
553 * Poisoned page might never drop its ref count to 0 so we have
554 * to uncharge it manually from its memcg.
555 */
556 mem_cgroup_uncharge(p);
557
558 /*
559 * drop the page count elevated by isolate_lru_page()
560 */
561 page_cache_release(p);
562 return 0;
563 }
564 return -EIO;
565 }
566
567 /*
568 * Error hit kernel page.
569 * Do nothing, try to be lucky and not touch this instead. For a few cases we
570 * could be more sophisticated.
571 */
me_kernel(struct page * p,unsigned long pfn)572 static int me_kernel(struct page *p, unsigned long pfn)
573 {
574 return IGNORED;
575 }
576
577 /*
578 * Page in unknown state. Do nothing.
579 */
me_unknown(struct page * p,unsigned long pfn)580 static int me_unknown(struct page *p, unsigned long pfn)
581 {
582 printk(KERN_ERR "MCE %#lx: Unknown page state\n", pfn);
583 return FAILED;
584 }
585
586 /*
587 * Clean (or cleaned) page cache page.
588 */
me_pagecache_clean(struct page * p,unsigned long pfn)589 static int me_pagecache_clean(struct page *p, unsigned long pfn)
590 {
591 int err;
592 int ret = FAILED;
593 struct address_space *mapping;
594
595 delete_from_lru_cache(p);
596
597 /*
598 * For anonymous pages we're done the only reference left
599 * should be the one m_f() holds.
600 */
601 if (PageAnon(p))
602 return RECOVERED;
603
604 /*
605 * Now truncate the page in the page cache. This is really
606 * more like a "temporary hole punch"
607 * Don't do this for block devices when someone else
608 * has a reference, because it could be file system metadata
609 * and that's not safe to truncate.
610 */
611 mapping = page_mapping(p);
612 if (!mapping) {
613 /*
614 * Page has been teared down in the meanwhile
615 */
616 return FAILED;
617 }
618
619 /*
620 * Truncation is a bit tricky. Enable it per file system for now.
621 *
622 * Open: to take i_mutex or not for this? Right now we don't.
623 */
624 if (mapping->a_ops->error_remove_page) {
625 err = mapping->a_ops->error_remove_page(mapping, p);
626 if (err != 0) {
627 printk(KERN_INFO "MCE %#lx: Failed to punch page: %d\n",
628 pfn, err);
629 } else if (page_has_private(p) &&
630 !try_to_release_page(p, GFP_NOIO)) {
631 pr_info("MCE %#lx: failed to release buffers\n", pfn);
632 } else {
633 ret = RECOVERED;
634 }
635 } else {
636 /*
637 * If the file system doesn't support it just invalidate
638 * This fails on dirty or anything with private pages
639 */
640 if (invalidate_inode_page(p))
641 ret = RECOVERED;
642 else
643 printk(KERN_INFO "MCE %#lx: Failed to invalidate\n",
644 pfn);
645 }
646 return ret;
647 }
648
649 /*
650 * Dirty pagecache page
651 * Issues: when the error hit a hole page the error is not properly
652 * propagated.
653 */
me_pagecache_dirty(struct page * p,unsigned long pfn)654 static int me_pagecache_dirty(struct page *p, unsigned long pfn)
655 {
656 struct address_space *mapping = page_mapping(p);
657
658 SetPageError(p);
659 /* TBD: print more information about the file. */
660 if (mapping) {
661 /*
662 * IO error will be reported by write(), fsync(), etc.
663 * who check the mapping.
664 * This way the application knows that something went
665 * wrong with its dirty file data.
666 *
667 * There's one open issue:
668 *
669 * The EIO will be only reported on the next IO
670 * operation and then cleared through the IO map.
671 * Normally Linux has two mechanisms to pass IO error
672 * first through the AS_EIO flag in the address space
673 * and then through the PageError flag in the page.
674 * Since we drop pages on memory failure handling the
675 * only mechanism open to use is through AS_AIO.
676 *
677 * This has the disadvantage that it gets cleared on
678 * the first operation that returns an error, while
679 * the PageError bit is more sticky and only cleared
680 * when the page is reread or dropped. If an
681 * application assumes it will always get error on
682 * fsync, but does other operations on the fd before
683 * and the page is dropped between then the error
684 * will not be properly reported.
685 *
686 * This can already happen even without hwpoisoned
687 * pages: first on metadata IO errors (which only
688 * report through AS_EIO) or when the page is dropped
689 * at the wrong time.
690 *
691 * So right now we assume that the application DTRT on
692 * the first EIO, but we're not worse than other parts
693 * of the kernel.
694 */
695 mapping_set_error(mapping, EIO);
696 }
697
698 return me_pagecache_clean(p, pfn);
699 }
700
701 /*
702 * Clean and dirty swap cache.
703 *
704 * Dirty swap cache page is tricky to handle. The page could live both in page
705 * cache and swap cache(ie. page is freshly swapped in). So it could be
706 * referenced concurrently by 2 types of PTEs:
707 * normal PTEs and swap PTEs. We try to handle them consistently by calling
708 * try_to_unmap(TTU_IGNORE_HWPOISON) to convert the normal PTEs to swap PTEs,
709 * and then
710 * - clear dirty bit to prevent IO
711 * - remove from LRU
712 * - but keep in the swap cache, so that when we return to it on
713 * a later page fault, we know the application is accessing
714 * corrupted data and shall be killed (we installed simple
715 * interception code in do_swap_page to catch it).
716 *
717 * Clean swap cache pages can be directly isolated. A later page fault will
718 * bring in the known good data from disk.
719 */
me_swapcache_dirty(struct page * p,unsigned long pfn)720 static int me_swapcache_dirty(struct page *p, unsigned long pfn)
721 {
722 ClearPageDirty(p);
723 /* Trigger EIO in shmem: */
724 ClearPageUptodate(p);
725
726 if (!delete_from_lru_cache(p))
727 return DELAYED;
728 else
729 return FAILED;
730 }
731
me_swapcache_clean(struct page * p,unsigned long pfn)732 static int me_swapcache_clean(struct page *p, unsigned long pfn)
733 {
734 delete_from_swap_cache(p);
735
736 if (!delete_from_lru_cache(p))
737 return RECOVERED;
738 else
739 return FAILED;
740 }
741
742 /*
743 * Huge pages. Needs work.
744 * Issues:
745 * - Error on hugepage is contained in hugepage unit (not in raw page unit.)
746 * To narrow down kill region to one page, we need to break up pmd.
747 */
me_huge_page(struct page * p,unsigned long pfn)748 static int me_huge_page(struct page *p, unsigned long pfn)
749 {
750 int res = 0;
751 struct page *hpage = compound_head(p);
752 /*
753 * We can safely recover from error on free or reserved (i.e.
754 * not in-use) hugepage by dequeuing it from freelist.
755 * To check whether a hugepage is in-use or not, we can't use
756 * page->lru because it can be used in other hugepage operations,
757 * such as __unmap_hugepage_range() and gather_surplus_pages().
758 * So instead we use page_mapping() and PageAnon().
759 * We assume that this function is called with page lock held,
760 * so there is no race between isolation and mapping/unmapping.
761 */
762 if (!(page_mapping(hpage) || PageAnon(hpage))) {
763 res = dequeue_hwpoisoned_huge_page(hpage);
764 if (!res)
765 return RECOVERED;
766 }
767 return DELAYED;
768 }
769
770 /*
771 * Various page states we can handle.
772 *
773 * A page state is defined by its current page->flags bits.
774 * The table matches them in order and calls the right handler.
775 *
776 * This is quite tricky because we can access page at any time
777 * in its live cycle, so all accesses have to be extremely careful.
778 *
779 * This is not complete. More states could be added.
780 * For any missing state don't attempt recovery.
781 */
782
783 #define dirty (1UL << PG_dirty)
784 #define sc (1UL << PG_swapcache)
785 #define unevict (1UL << PG_unevictable)
786 #define mlock (1UL << PG_mlocked)
787 #define writeback (1UL << PG_writeback)
788 #define lru (1UL << PG_lru)
789 #define swapbacked (1UL << PG_swapbacked)
790 #define head (1UL << PG_head)
791 #define tail (1UL << PG_tail)
792 #define compound (1UL << PG_compound)
793 #define slab (1UL << PG_slab)
794 #define reserved (1UL << PG_reserved)
795
796 static struct page_state {
797 unsigned long mask;
798 unsigned long res;
799 char *msg;
800 int (*action)(struct page *p, unsigned long pfn);
801 } error_states[] = {
802 { reserved, reserved, "reserved kernel", me_kernel },
803 /*
804 * free pages are specially detected outside this table:
805 * PG_buddy pages only make a small fraction of all free pages.
806 */
807
808 /*
809 * Could in theory check if slab page is free or if we can drop
810 * currently unused objects without touching them. But just
811 * treat it as standard kernel for now.
812 */
813 { slab, slab, "kernel slab", me_kernel },
814
815 #ifdef CONFIG_PAGEFLAGS_EXTENDED
816 { head, head, "huge", me_huge_page },
817 { tail, tail, "huge", me_huge_page },
818 #else
819 { compound, compound, "huge", me_huge_page },
820 #endif
821
822 { sc|dirty, sc|dirty, "dirty swapcache", me_swapcache_dirty },
823 { sc|dirty, sc, "clean swapcache", me_swapcache_clean },
824
825 { mlock|dirty, mlock|dirty, "dirty mlocked LRU", me_pagecache_dirty },
826 { mlock|dirty, mlock, "clean mlocked LRU", me_pagecache_clean },
827
828 { unevict|dirty, unevict|dirty, "dirty unevictable LRU", me_pagecache_dirty },
829 { unevict|dirty, unevict, "clean unevictable LRU", me_pagecache_clean },
830
831 { lru|dirty, lru|dirty, "dirty LRU", me_pagecache_dirty },
832 { lru|dirty, lru, "clean LRU", me_pagecache_clean },
833
834 /*
835 * Catchall entry: must be at end.
836 */
837 { 0, 0, "unknown page state", me_unknown },
838 };
839
840 #undef dirty
841 #undef sc
842 #undef unevict
843 #undef mlock
844 #undef writeback
845 #undef lru
846 #undef swapbacked
847 #undef head
848 #undef tail
849 #undef compound
850 #undef slab
851 #undef reserved
852
853 /*
854 * "Dirty/Clean" indication is not 100% accurate due to the possibility of
855 * setting PG_dirty outside page lock. See also comment above set_page_dirty().
856 */
action_result(unsigned long pfn,char * msg,int result)857 static void action_result(unsigned long pfn, char *msg, int result)
858 {
859 pr_err("MCE %#lx: %s page recovery: %s\n",
860 pfn, msg, action_name[result]);
861 }
862
page_action(struct page_state * ps,struct page * p,unsigned long pfn)863 static int page_action(struct page_state *ps, struct page *p,
864 unsigned long pfn)
865 {
866 int result;
867 int count;
868
869 result = ps->action(p, pfn);
870 action_result(pfn, ps->msg, result);
871
872 count = page_count(p) - 1;
873 if (ps->action == me_swapcache_dirty && result == DELAYED)
874 count--;
875 if (count != 0) {
876 printk(KERN_ERR
877 "MCE %#lx: %s page still referenced by %d users\n",
878 pfn, ps->msg, count);
879 result = FAILED;
880 }
881
882 /* Could do more checks here if page looks ok */
883 /*
884 * Could adjust zone counters here to correct for the missing page.
885 */
886
887 return (result == RECOVERED || result == DELAYED) ? 0 : -EBUSY;
888 }
889
890 /*
891 * Do all that is necessary to remove user space mappings. Unmap
892 * the pages and send SIGBUS to the processes if the data was dirty.
893 */
hwpoison_user_mappings(struct page * p,unsigned long pfn,int trapno,int flags,struct page ** hpagep)894 static int hwpoison_user_mappings(struct page *p, unsigned long pfn,
895 int trapno, int flags, struct page **hpagep)
896 {
897 enum ttu_flags ttu = TTU_UNMAP | TTU_IGNORE_MLOCK | TTU_IGNORE_ACCESS;
898 struct address_space *mapping;
899 LIST_HEAD(tokill);
900 int ret;
901 int kill = 1, forcekill;
902 struct page *hpage = *hpagep;
903 struct page *ppage;
904
905 /*
906 * Here we are interested only in user-mapped pages, so skip any
907 * other types of pages.
908 */
909 if (PageReserved(p) || PageSlab(p))
910 return SWAP_SUCCESS;
911 if (!(PageLRU(hpage) || PageHuge(p)))
912 return SWAP_SUCCESS;
913
914 /*
915 * This check implies we don't kill processes if their pages
916 * are in the swap cache early. Those are always late kills.
917 */
918 if (!page_mapped(hpage))
919 return SWAP_SUCCESS;
920
921 if (PageKsm(p)) {
922 pr_err("MCE %#lx: can't handle KSM pages.\n", pfn);
923 return SWAP_FAIL;
924 }
925
926 if (PageSwapCache(p)) {
927 printk(KERN_ERR
928 "MCE %#lx: keeping poisoned page in swap cache\n", pfn);
929 ttu |= TTU_IGNORE_HWPOISON;
930 }
931
932 /*
933 * Propagate the dirty bit from PTEs to struct page first, because we
934 * need this to decide if we should kill or just drop the page.
935 * XXX: the dirty test could be racy: set_page_dirty() may not always
936 * be called inside page lock (it's recommended but not enforced).
937 */
938 mapping = page_mapping(hpage);
939 if (!(flags & MF_MUST_KILL) && !PageDirty(hpage) && mapping &&
940 mapping_cap_writeback_dirty(mapping)) {
941 if (page_mkclean(hpage)) {
942 SetPageDirty(hpage);
943 } else {
944 kill = 0;
945 ttu |= TTU_IGNORE_HWPOISON;
946 printk(KERN_INFO
947 "MCE %#lx: corrupted page was clean: dropped without side effects\n",
948 pfn);
949 }
950 }
951
952 /*
953 * ppage: poisoned page
954 * if p is regular page(4k page)
955 * ppage == real poisoned page;
956 * else p is hugetlb or THP, ppage == head page.
957 */
958 ppage = hpage;
959
960 if (PageTransHuge(hpage)) {
961 /*
962 * Verify that this isn't a hugetlbfs head page, the check for
963 * PageAnon is just for avoid tripping a split_huge_page
964 * internal debug check, as split_huge_page refuses to deal with
965 * anything that isn't an anon page. PageAnon can't go away fro
966 * under us because we hold a refcount on the hpage, without a
967 * refcount on the hpage. split_huge_page can't be safely called
968 * in the first place, having a refcount on the tail isn't
969 * enough * to be safe.
970 */
971 if (!PageHuge(hpage) && PageAnon(hpage)) {
972 if (unlikely(split_huge_page(hpage))) {
973 /*
974 * FIXME: if splitting THP is failed, it is
975 * better to stop the following operation rather
976 * than causing panic by unmapping. System might
977 * survive if the page is freed later.
978 */
979 printk(KERN_INFO
980 "MCE %#lx: failed to split THP\n", pfn);
981
982 BUG_ON(!PageHWPoison(p));
983 return SWAP_FAIL;
984 }
985 /*
986 * We pinned the head page for hwpoison handling,
987 * now we split the thp and we are interested in
988 * the hwpoisoned raw page, so move the refcount
989 * to it. Similarly, page lock is shifted.
990 */
991 if (hpage != p) {
992 if (!(flags & MF_COUNT_INCREASED)) {
993 put_page(hpage);
994 get_page(p);
995 }
996 lock_page(p);
997 unlock_page(hpage);
998 *hpagep = p;
999 }
1000 /* THP is split, so ppage should be the real poisoned page. */
1001 ppage = p;
1002 }
1003 }
1004
1005 /*
1006 * First collect all the processes that have the page
1007 * mapped in dirty form. This has to be done before try_to_unmap,
1008 * because ttu takes the rmap data structures down.
1009 *
1010 * Error handling: We ignore errors here because
1011 * there's nothing that can be done.
1012 */
1013 if (kill)
1014 collect_procs(ppage, &tokill, flags & MF_ACTION_REQUIRED);
1015
1016 ret = try_to_unmap(ppage, ttu);
1017 if (ret != SWAP_SUCCESS)
1018 printk(KERN_ERR "MCE %#lx: failed to unmap page (mapcount=%d)\n",
1019 pfn, page_mapcount(ppage));
1020
1021 /*
1022 * Now that the dirty bit has been propagated to the
1023 * struct page and all unmaps done we can decide if
1024 * killing is needed or not. Only kill when the page
1025 * was dirty or the process is not restartable,
1026 * otherwise the tokill list is merely
1027 * freed. When there was a problem unmapping earlier
1028 * use a more force-full uncatchable kill to prevent
1029 * any accesses to the poisoned memory.
1030 */
1031 forcekill = PageDirty(ppage) || (flags & MF_MUST_KILL);
1032 kill_procs(&tokill, forcekill, trapno,
1033 ret != SWAP_SUCCESS, p, pfn, flags);
1034
1035 return ret;
1036 }
1037
set_page_hwpoison_huge_page(struct page * hpage)1038 static void set_page_hwpoison_huge_page(struct page *hpage)
1039 {
1040 int i;
1041 int nr_pages = 1 << compound_order(hpage);
1042 for (i = 0; i < nr_pages; i++)
1043 SetPageHWPoison(hpage + i);
1044 }
1045
clear_page_hwpoison_huge_page(struct page * hpage)1046 static void clear_page_hwpoison_huge_page(struct page *hpage)
1047 {
1048 int i;
1049 int nr_pages = 1 << compound_order(hpage);
1050 for (i = 0; i < nr_pages; i++)
1051 ClearPageHWPoison(hpage + i);
1052 }
1053
1054 /**
1055 * memory_failure - Handle memory failure of a page.
1056 * @pfn: Page Number of the corrupted page
1057 * @trapno: Trap number reported in the signal to user space.
1058 * @flags: fine tune action taken
1059 *
1060 * This function is called by the low level machine check code
1061 * of an architecture when it detects hardware memory corruption
1062 * of a page. It tries its best to recover, which includes
1063 * dropping pages, killing processes etc.
1064 *
1065 * The function is primarily of use for corruptions that
1066 * happen outside the current execution context (e.g. when
1067 * detected by a background scrubber)
1068 *
1069 * Must run in process context (e.g. a work queue) with interrupts
1070 * enabled and no spinlocks hold.
1071 */
memory_failure(unsigned long pfn,int trapno,int flags)1072 int memory_failure(unsigned long pfn, int trapno, int flags)
1073 {
1074 struct page_state *ps;
1075 struct page *p;
1076 struct page *hpage;
1077 int res;
1078 unsigned int nr_pages;
1079 unsigned long page_flags;
1080
1081 if (!sysctl_memory_failure_recovery)
1082 panic("Memory failure from trap %d on page %lx", trapno, pfn);
1083
1084 if (!pfn_valid(pfn)) {
1085 printk(KERN_ERR
1086 "MCE %#lx: memory outside kernel control\n",
1087 pfn);
1088 return -ENXIO;
1089 }
1090
1091 p = pfn_to_page(pfn);
1092 hpage = compound_head(p);
1093 if (TestSetPageHWPoison(p)) {
1094 printk(KERN_ERR "MCE %#lx: already hardware poisoned\n", pfn);
1095 return 0;
1096 }
1097
1098 /*
1099 * Currently errors on hugetlbfs pages are measured in hugepage units,
1100 * so nr_pages should be 1 << compound_order. OTOH when errors are on
1101 * transparent hugepages, they are supposed to be split and error
1102 * measurement is done in normal page units. So nr_pages should be one
1103 * in this case.
1104 */
1105 if (PageHuge(p))
1106 nr_pages = 1 << compound_order(hpage);
1107 else /* normal page or thp */
1108 nr_pages = 1;
1109 atomic_long_add(nr_pages, &num_poisoned_pages);
1110
1111 /*
1112 * We need/can do nothing about count=0 pages.
1113 * 1) it's a free page, and therefore in safe hand:
1114 * prep_new_page() will be the gate keeper.
1115 * 2) it's a free hugepage, which is also safe:
1116 * an affected hugepage will be dequeued from hugepage freelist,
1117 * so there's no concern about reusing it ever after.
1118 * 3) it's part of a non-compound high order page.
1119 * Implies some kernel user: cannot stop them from
1120 * R/W the page; let's pray that the page has been
1121 * used and will be freed some time later.
1122 * In fact it's dangerous to directly bump up page count from 0,
1123 * that may make page_freeze_refs()/page_unfreeze_refs() mismatch.
1124 */
1125 if (!(flags & MF_COUNT_INCREASED) &&
1126 !get_page_unless_zero(hpage)) {
1127 if (is_free_buddy_page(p)) {
1128 action_result(pfn, "free buddy", DELAYED);
1129 return 0;
1130 } else if (PageHuge(hpage)) {
1131 /*
1132 * Check "filter hit" and "race with other subpage."
1133 */
1134 lock_page(hpage);
1135 if (PageHWPoison(hpage)) {
1136 if ((hwpoison_filter(p) && TestClearPageHWPoison(p))
1137 || (p != hpage && TestSetPageHWPoison(hpage))) {
1138 atomic_long_sub(nr_pages, &num_poisoned_pages);
1139 unlock_page(hpage);
1140 return 0;
1141 }
1142 }
1143 set_page_hwpoison_huge_page(hpage);
1144 res = dequeue_hwpoisoned_huge_page(hpage);
1145 action_result(pfn, "free huge",
1146 res ? IGNORED : DELAYED);
1147 unlock_page(hpage);
1148 return res;
1149 } else {
1150 action_result(pfn, "high order kernel", IGNORED);
1151 return -EBUSY;
1152 }
1153 }
1154
1155 /*
1156 * We ignore non-LRU pages for good reasons.
1157 * - PG_locked is only well defined for LRU pages and a few others
1158 * - to avoid races with __set_page_locked()
1159 * - to avoid races with __SetPageSlab*() (and more non-atomic ops)
1160 * The check (unnecessarily) ignores LRU pages being isolated and
1161 * walked by the page reclaim code, however that's not a big loss.
1162 */
1163 if (!PageHuge(p)) {
1164 if (!PageLRU(hpage))
1165 shake_page(hpage, 0);
1166 if (!PageLRU(hpage)) {
1167 /*
1168 * shake_page could have turned it free.
1169 */
1170 if (is_free_buddy_page(p)) {
1171 if (flags & MF_COUNT_INCREASED)
1172 action_result(pfn, "free buddy", DELAYED);
1173 else
1174 action_result(pfn, "free buddy, 2nd try", DELAYED);
1175 return 0;
1176 }
1177 }
1178 }
1179
1180 lock_page(hpage);
1181
1182 /*
1183 * The page could have changed compound pages during the locking.
1184 * If this happens just bail out.
1185 */
1186 if (compound_head(p) != hpage) {
1187 action_result(pfn, "different compound page after locking", IGNORED);
1188 res = -EBUSY;
1189 goto out;
1190 }
1191
1192 /*
1193 * We use page flags to determine what action should be taken, but
1194 * the flags can be modified by the error containment action. One
1195 * example is an mlocked page, where PG_mlocked is cleared by
1196 * page_remove_rmap() in try_to_unmap_one(). So to determine page status
1197 * correctly, we save a copy of the page flags at this time.
1198 */
1199 if (PageHuge(p))
1200 page_flags = hpage->flags;
1201 else
1202 page_flags = p->flags;
1203
1204 /*
1205 * unpoison always clear PG_hwpoison inside page lock
1206 */
1207 if (!PageHWPoison(p)) {
1208 printk(KERN_ERR "MCE %#lx: just unpoisoned\n", pfn);
1209 atomic_long_sub(nr_pages, &num_poisoned_pages);
1210 put_page(hpage);
1211 res = 0;
1212 goto out;
1213 }
1214 if (hwpoison_filter(p)) {
1215 if (TestClearPageHWPoison(p))
1216 atomic_long_sub(nr_pages, &num_poisoned_pages);
1217 unlock_page(hpage);
1218 put_page(hpage);
1219 return 0;
1220 }
1221
1222 if (!PageHuge(p) && !PageTransTail(p) && !PageLRU(p))
1223 goto identify_page_state;
1224
1225 /*
1226 * For error on the tail page, we should set PG_hwpoison
1227 * on the head page to show that the hugepage is hwpoisoned
1228 */
1229 if (PageHuge(p) && PageTail(p) && TestSetPageHWPoison(hpage)) {
1230 action_result(pfn, "hugepage already hardware poisoned",
1231 IGNORED);
1232 unlock_page(hpage);
1233 put_page(hpage);
1234 return 0;
1235 }
1236 /*
1237 * Set PG_hwpoison on all pages in an error hugepage,
1238 * because containment is done in hugepage unit for now.
1239 * Since we have done TestSetPageHWPoison() for the head page with
1240 * page lock held, we can safely set PG_hwpoison bits on tail pages.
1241 */
1242 if (PageHuge(p))
1243 set_page_hwpoison_huge_page(hpage);
1244
1245 /*
1246 * It's very difficult to mess with pages currently under IO
1247 * and in many cases impossible, so we just avoid it here.
1248 */
1249 wait_on_page_writeback(p);
1250
1251 /*
1252 * Now take care of user space mappings.
1253 * Abort on fail: __delete_from_page_cache() assumes unmapped page.
1254 *
1255 * When the raw error page is thp tail page, hpage points to the raw
1256 * page after thp split.
1257 */
1258 if (hwpoison_user_mappings(p, pfn, trapno, flags, &hpage)
1259 != SWAP_SUCCESS) {
1260 action_result(pfn, "unmapping failed", IGNORED);
1261 res = -EBUSY;
1262 goto out;
1263 }
1264
1265 /*
1266 * Torn down by someone else?
1267 */
1268 if (PageLRU(p) && !PageSwapCache(p) && p->mapping == NULL) {
1269 action_result(pfn, "already truncated LRU", IGNORED);
1270 res = -EBUSY;
1271 goto out;
1272 }
1273
1274 identify_page_state:
1275 res = -EBUSY;
1276 /*
1277 * The first check uses the current page flags which may not have any
1278 * relevant information. The second check with the saved page flagss is
1279 * carried out only if the first check can't determine the page status.
1280 */
1281 for (ps = error_states;; ps++)
1282 if ((p->flags & ps->mask) == ps->res)
1283 break;
1284
1285 page_flags |= (p->flags & (1UL << PG_dirty));
1286
1287 if (!ps->mask)
1288 for (ps = error_states;; ps++)
1289 if ((page_flags & ps->mask) == ps->res)
1290 break;
1291 res = page_action(ps, p, pfn);
1292 out:
1293 unlock_page(hpage);
1294 return res;
1295 }
1296 EXPORT_SYMBOL_GPL(memory_failure);
1297
1298 #define MEMORY_FAILURE_FIFO_ORDER 4
1299 #define MEMORY_FAILURE_FIFO_SIZE (1 << MEMORY_FAILURE_FIFO_ORDER)
1300
1301 struct memory_failure_entry {
1302 unsigned long pfn;
1303 int trapno;
1304 int flags;
1305 };
1306
1307 struct memory_failure_cpu {
1308 DECLARE_KFIFO(fifo, struct memory_failure_entry,
1309 MEMORY_FAILURE_FIFO_SIZE);
1310 spinlock_t lock;
1311 struct work_struct work;
1312 };
1313
1314 static DEFINE_PER_CPU(struct memory_failure_cpu, memory_failure_cpu);
1315
1316 /**
1317 * memory_failure_queue - Schedule handling memory failure of a page.
1318 * @pfn: Page Number of the corrupted page
1319 * @trapno: Trap number reported in the signal to user space.
1320 * @flags: Flags for memory failure handling
1321 *
1322 * This function is called by the low level hardware error handler
1323 * when it detects hardware memory corruption of a page. It schedules
1324 * the recovering of error page, including dropping pages, killing
1325 * processes etc.
1326 *
1327 * The function is primarily of use for corruptions that
1328 * happen outside the current execution context (e.g. when
1329 * detected by a background scrubber)
1330 *
1331 * Can run in IRQ context.
1332 */
memory_failure_queue(unsigned long pfn,int trapno,int flags)1333 void memory_failure_queue(unsigned long pfn, int trapno, int flags)
1334 {
1335 struct memory_failure_cpu *mf_cpu;
1336 unsigned long proc_flags;
1337 struct memory_failure_entry entry = {
1338 .pfn = pfn,
1339 .trapno = trapno,
1340 .flags = flags,
1341 };
1342
1343 mf_cpu = &get_cpu_var(memory_failure_cpu);
1344 spin_lock_irqsave(&mf_cpu->lock, proc_flags);
1345 if (kfifo_put(&mf_cpu->fifo, entry))
1346 schedule_work_on(smp_processor_id(), &mf_cpu->work);
1347 else
1348 pr_err("Memory failure: buffer overflow when queuing memory failure at %#lx\n",
1349 pfn);
1350 spin_unlock_irqrestore(&mf_cpu->lock, proc_flags);
1351 put_cpu_var(memory_failure_cpu);
1352 }
1353 EXPORT_SYMBOL_GPL(memory_failure_queue);
1354
memory_failure_work_func(struct work_struct * work)1355 static void memory_failure_work_func(struct work_struct *work)
1356 {
1357 struct memory_failure_cpu *mf_cpu;
1358 struct memory_failure_entry entry = { 0, };
1359 unsigned long proc_flags;
1360 int gotten;
1361
1362 mf_cpu = this_cpu_ptr(&memory_failure_cpu);
1363 for (;;) {
1364 spin_lock_irqsave(&mf_cpu->lock, proc_flags);
1365 gotten = kfifo_get(&mf_cpu->fifo, &entry);
1366 spin_unlock_irqrestore(&mf_cpu->lock, proc_flags);
1367 if (!gotten)
1368 break;
1369 if (entry.flags & MF_SOFT_OFFLINE)
1370 soft_offline_page(pfn_to_page(entry.pfn), entry.flags);
1371 else
1372 memory_failure(entry.pfn, entry.trapno, entry.flags);
1373 }
1374 }
1375
memory_failure_init(void)1376 static int __init memory_failure_init(void)
1377 {
1378 struct memory_failure_cpu *mf_cpu;
1379 int cpu;
1380
1381 for_each_possible_cpu(cpu) {
1382 mf_cpu = &per_cpu(memory_failure_cpu, cpu);
1383 spin_lock_init(&mf_cpu->lock);
1384 INIT_KFIFO(mf_cpu->fifo);
1385 INIT_WORK(&mf_cpu->work, memory_failure_work_func);
1386 }
1387
1388 return 0;
1389 }
1390 core_initcall(memory_failure_init);
1391
1392 /**
1393 * unpoison_memory - Unpoison a previously poisoned page
1394 * @pfn: Page number of the to be unpoisoned page
1395 *
1396 * Software-unpoison a page that has been poisoned by
1397 * memory_failure() earlier.
1398 *
1399 * This is only done on the software-level, so it only works
1400 * for linux injected failures, not real hardware failures
1401 *
1402 * Returns 0 for success, otherwise -errno.
1403 */
unpoison_memory(unsigned long pfn)1404 int unpoison_memory(unsigned long pfn)
1405 {
1406 struct page *page;
1407 struct page *p;
1408 int freeit = 0;
1409 unsigned int nr_pages;
1410
1411 if (!pfn_valid(pfn))
1412 return -ENXIO;
1413
1414 p = pfn_to_page(pfn);
1415 page = compound_head(p);
1416
1417 if (!PageHWPoison(p)) {
1418 pr_info("MCE: Page was already unpoisoned %#lx\n", pfn);
1419 return 0;
1420 }
1421
1422 /*
1423 * unpoison_memory() can encounter thp only when the thp is being
1424 * worked by memory_failure() and the page lock is not held yet.
1425 * In such case, we yield to memory_failure() and make unpoison fail.
1426 */
1427 if (!PageHuge(page) && PageTransHuge(page)) {
1428 pr_info("MCE: Memory failure is now running on %#lx\n", pfn);
1429 return 0;
1430 }
1431
1432 nr_pages = 1 << compound_order(page);
1433
1434 if (!get_page_unless_zero(page)) {
1435 /*
1436 * Since HWPoisoned hugepage should have non-zero refcount,
1437 * race between memory failure and unpoison seems to happen.
1438 * In such case unpoison fails and memory failure runs
1439 * to the end.
1440 */
1441 if (PageHuge(page)) {
1442 pr_info("MCE: Memory failure is now running on free hugepage %#lx\n", pfn);
1443 return 0;
1444 }
1445 if (TestClearPageHWPoison(p))
1446 atomic_long_dec(&num_poisoned_pages);
1447 pr_info("MCE: Software-unpoisoned free page %#lx\n", pfn);
1448 return 0;
1449 }
1450
1451 lock_page(page);
1452 /*
1453 * This test is racy because PG_hwpoison is set outside of page lock.
1454 * That's acceptable because that won't trigger kernel panic. Instead,
1455 * the PG_hwpoison page will be caught and isolated on the entrance to
1456 * the free buddy page pool.
1457 */
1458 if (TestClearPageHWPoison(page)) {
1459 pr_info("MCE: Software-unpoisoned page %#lx\n", pfn);
1460 atomic_long_sub(nr_pages, &num_poisoned_pages);
1461 freeit = 1;
1462 if (PageHuge(page))
1463 clear_page_hwpoison_huge_page(page);
1464 }
1465 unlock_page(page);
1466
1467 put_page(page);
1468 if (freeit && !(pfn == my_zero_pfn(0) && page_count(p) == 1))
1469 put_page(page);
1470
1471 return 0;
1472 }
1473 EXPORT_SYMBOL(unpoison_memory);
1474
new_page(struct page * p,unsigned long private,int ** x)1475 static struct page *new_page(struct page *p, unsigned long private, int **x)
1476 {
1477 int nid = page_to_nid(p);
1478 if (PageHuge(p))
1479 return alloc_huge_page_node(page_hstate(compound_head(p)),
1480 nid);
1481 else
1482 return alloc_pages_exact_node(nid, GFP_HIGHUSER_MOVABLE, 0);
1483 }
1484
1485 /*
1486 * Safely get reference count of an arbitrary page.
1487 * Returns 0 for a free page, -EIO for a zero refcount page
1488 * that is not free, and 1 for any other page type.
1489 * For 1 the page is returned with increased page count, otherwise not.
1490 */
__get_any_page(struct page * p,unsigned long pfn,int flags)1491 static int __get_any_page(struct page *p, unsigned long pfn, int flags)
1492 {
1493 int ret;
1494
1495 if (flags & MF_COUNT_INCREASED)
1496 return 1;
1497
1498 /*
1499 * When the target page is a free hugepage, just remove it
1500 * from free hugepage list.
1501 */
1502 if (!get_page_unless_zero(compound_head(p))) {
1503 if (PageHuge(p)) {
1504 pr_info("%s: %#lx free huge page\n", __func__, pfn);
1505 ret = 0;
1506 } else if (is_free_buddy_page(p)) {
1507 pr_info("%s: %#lx free buddy page\n", __func__, pfn);
1508 ret = 0;
1509 } else {
1510 pr_info("%s: %#lx: unknown zero refcount page type %lx\n",
1511 __func__, pfn, p->flags);
1512 ret = -EIO;
1513 }
1514 } else {
1515 /* Not a free page */
1516 ret = 1;
1517 }
1518 return ret;
1519 }
1520
get_any_page(struct page * page,unsigned long pfn,int flags)1521 static int get_any_page(struct page *page, unsigned long pfn, int flags)
1522 {
1523 int ret = __get_any_page(page, pfn, flags);
1524
1525 if (ret == 1 && !PageHuge(page) && !PageLRU(page)) {
1526 /*
1527 * Try to free it.
1528 */
1529 put_page(page);
1530 shake_page(page, 1);
1531
1532 /*
1533 * Did it turn free?
1534 */
1535 ret = __get_any_page(page, pfn, 0);
1536 if (ret == 1 && !PageLRU(page)) {
1537 /* Drop page reference which is from __get_any_page() */
1538 put_page(page);
1539 pr_info("soft_offline: %#lx: unknown non LRU page type %lx\n",
1540 pfn, page->flags);
1541 return -EIO;
1542 }
1543 }
1544 return ret;
1545 }
1546
soft_offline_huge_page(struct page * page,int flags)1547 static int soft_offline_huge_page(struct page *page, int flags)
1548 {
1549 int ret;
1550 unsigned long pfn = page_to_pfn(page);
1551 struct page *hpage = compound_head(page);
1552 LIST_HEAD(pagelist);
1553
1554 /*
1555 * This double-check of PageHWPoison is to avoid the race with
1556 * memory_failure(). See also comment in __soft_offline_page().
1557 */
1558 lock_page(hpage);
1559 if (PageHWPoison(hpage)) {
1560 unlock_page(hpage);
1561 put_page(hpage);
1562 pr_info("soft offline: %#lx hugepage already poisoned\n", pfn);
1563 return -EBUSY;
1564 }
1565 unlock_page(hpage);
1566
1567 ret = isolate_huge_page(hpage, &pagelist);
1568 /*
1569 * get_any_page() and isolate_huge_page() takes a refcount each,
1570 * so need to drop one here.
1571 */
1572 put_page(hpage);
1573 if (!ret) {
1574 pr_info("soft offline: %#lx hugepage failed to isolate\n", pfn);
1575 return -EBUSY;
1576 }
1577
1578 ret = migrate_pages(&pagelist, new_page, NULL, MPOL_MF_MOVE_ALL,
1579 MIGRATE_SYNC, MR_MEMORY_FAILURE);
1580 if (ret) {
1581 pr_info("soft offline: %#lx: migration failed %d, type %lx\n",
1582 pfn, ret, page->flags);
1583 if (!list_empty(&pagelist))
1584 putback_movable_pages(&pagelist);
1585 if (ret > 0)
1586 ret = -EIO;
1587 } else {
1588 /* overcommit hugetlb page will be freed to buddy */
1589 if (PageHuge(page)) {
1590 set_page_hwpoison_huge_page(hpage);
1591 dequeue_hwpoisoned_huge_page(hpage);
1592 atomic_long_add(1 << compound_order(hpage),
1593 &num_poisoned_pages);
1594 } else {
1595 SetPageHWPoison(page);
1596 atomic_long_inc(&num_poisoned_pages);
1597 }
1598 }
1599 return ret;
1600 }
1601
__soft_offline_page(struct page * page,int flags)1602 static int __soft_offline_page(struct page *page, int flags)
1603 {
1604 int ret;
1605 unsigned long pfn = page_to_pfn(page);
1606
1607 /*
1608 * Check PageHWPoison again inside page lock because PageHWPoison
1609 * is set by memory_failure() outside page lock. Note that
1610 * memory_failure() also double-checks PageHWPoison inside page lock,
1611 * so there's no race between soft_offline_page() and memory_failure().
1612 */
1613 lock_page(page);
1614 wait_on_page_writeback(page);
1615 if (PageHWPoison(page)) {
1616 unlock_page(page);
1617 put_page(page);
1618 pr_info("soft offline: %#lx page already poisoned\n", pfn);
1619 return -EBUSY;
1620 }
1621 /*
1622 * Try to invalidate first. This should work for
1623 * non dirty unmapped page cache pages.
1624 */
1625 ret = invalidate_inode_page(page);
1626 unlock_page(page);
1627 /*
1628 * RED-PEN would be better to keep it isolated here, but we
1629 * would need to fix isolation locking first.
1630 */
1631 if (ret == 1) {
1632 put_page(page);
1633 pr_info("soft_offline: %#lx: invalidated\n", pfn);
1634 SetPageHWPoison(page);
1635 atomic_long_inc(&num_poisoned_pages);
1636 return 0;
1637 }
1638
1639 /*
1640 * Simple invalidation didn't work.
1641 * Try to migrate to a new page instead. migrate.c
1642 * handles a large number of cases for us.
1643 */
1644 ret = isolate_lru_page(page);
1645 /*
1646 * Drop page reference which is came from get_any_page()
1647 * successful isolate_lru_page() already took another one.
1648 */
1649 put_page(page);
1650 if (!ret) {
1651 LIST_HEAD(pagelist);
1652 inc_zone_page_state(page, NR_ISOLATED_ANON +
1653 page_is_file_cache(page));
1654 list_add(&page->lru, &pagelist);
1655 ret = migrate_pages(&pagelist, new_page, NULL, MPOL_MF_MOVE_ALL,
1656 MIGRATE_SYNC, MR_MEMORY_FAILURE);
1657 if (ret) {
1658 if (!list_empty(&pagelist)) {
1659 list_del(&page->lru);
1660 dec_zone_page_state(page, NR_ISOLATED_ANON +
1661 page_is_file_cache(page));
1662 putback_lru_page(page);
1663 }
1664
1665 pr_info("soft offline: %#lx: migration failed %d, type %lx\n",
1666 pfn, ret, page->flags);
1667 if (ret > 0)
1668 ret = -EIO;
1669 } else {
1670 /*
1671 * After page migration succeeds, the source page can
1672 * be trapped in pagevec and actual freeing is delayed.
1673 * Freeing code works differently based on PG_hwpoison,
1674 * so there's a race. We need to make sure that the
1675 * source page should be freed back to buddy before
1676 * setting PG_hwpoison.
1677 */
1678 if (!is_free_buddy_page(page))
1679 drain_all_pages();
1680 SetPageHWPoison(page);
1681 if (!is_free_buddy_page(page))
1682 pr_info("soft offline: %#lx: page leaked\n",
1683 pfn);
1684 atomic_long_inc(&num_poisoned_pages);
1685 }
1686 } else {
1687 pr_info("soft offline: %#lx: isolation failed: %d, page count %d, type %lx\n",
1688 pfn, ret, page_count(page), page->flags);
1689 }
1690 return ret;
1691 }
1692
1693 /**
1694 * soft_offline_page - Soft offline a page.
1695 * @page: page to offline
1696 * @flags: flags. Same as memory_failure().
1697 *
1698 * Returns 0 on success, otherwise negated errno.
1699 *
1700 * Soft offline a page, by migration or invalidation,
1701 * without killing anything. This is for the case when
1702 * a page is not corrupted yet (so it's still valid to access),
1703 * but has had a number of corrected errors and is better taken
1704 * out.
1705 *
1706 * The actual policy on when to do that is maintained by
1707 * user space.
1708 *
1709 * This should never impact any application or cause data loss,
1710 * however it might take some time.
1711 *
1712 * This is not a 100% solution for all memory, but tries to be
1713 * ``good enough'' for the majority of memory.
1714 */
soft_offline_page(struct page * page,int flags)1715 int soft_offline_page(struct page *page, int flags)
1716 {
1717 int ret;
1718 unsigned long pfn = page_to_pfn(page);
1719 struct page *hpage = compound_head(page);
1720
1721 if (PageHWPoison(page)) {
1722 pr_info("soft offline: %#lx page already poisoned\n", pfn);
1723 return -EBUSY;
1724 }
1725 if (!PageHuge(page) && PageTransHuge(hpage)) {
1726 if (PageAnon(hpage) && unlikely(split_huge_page(hpage))) {
1727 pr_info("soft offline: %#lx: failed to split THP\n",
1728 pfn);
1729 return -EBUSY;
1730 }
1731 }
1732
1733 get_online_mems();
1734
1735 /*
1736 * Isolate the page, so that it doesn't get reallocated if it
1737 * was free. This flag should be kept set until the source page
1738 * is freed and PG_hwpoison on it is set.
1739 */
1740 if (get_pageblock_migratetype(page) != MIGRATE_ISOLATE)
1741 set_migratetype_isolate(page, true);
1742
1743 ret = get_any_page(page, pfn, flags);
1744 put_online_mems();
1745 if (ret > 0) { /* for in-use pages */
1746 if (PageHuge(page))
1747 ret = soft_offline_huge_page(page, flags);
1748 else
1749 ret = __soft_offline_page(page, flags);
1750 } else if (ret == 0) { /* for free pages */
1751 if (PageHuge(page)) {
1752 set_page_hwpoison_huge_page(hpage);
1753 if (!dequeue_hwpoisoned_huge_page(hpage))
1754 atomic_long_add(1 << compound_order(hpage),
1755 &num_poisoned_pages);
1756 } else {
1757 if (!TestSetPageHWPoison(page))
1758 atomic_long_inc(&num_poisoned_pages);
1759 }
1760 }
1761 unset_migratetype_isolate(page, MIGRATE_MOVABLE);
1762 return ret;
1763 }
1764