1 #include <linux/kernel.h>
2 #include <linux/string.h>
4 #include <linux/highmem.h>
5 #include <linux/page_ext.h>
6 #include <linux/poison.h>
7 #include <linux/ratelimit.h>
9 static bool __page_poisoning_enabled __read_mostly;
10 static bool want_page_poisoning __read_mostly =
11 !IS_ENABLED(CONFIG_ARCH_SUPPORTS_DEBUG_PAGEALLOC);
13 static int early_page_poison_param(char *buf)
18 if (strcmp(buf, "on") == 0)
19 want_page_poisoning = true;
20 else if (strcmp(buf, "off") == 0)
21 want_page_poisoning = false;
25 early_param("page_poison", early_page_poison_param);
27 bool page_poisoning_enabled(void)
29 return __page_poisoning_enabled;
32 static bool need_page_poisoning(void)
34 return want_page_poisoning;
37 static void init_page_poisoning(void)
39 if (!want_page_poisoning)
42 __page_poisoning_enabled = true;
45 struct page_ext_operations page_poisoning_ops = {
46 .need = need_page_poisoning,
47 .init = init_page_poisoning,
50 static inline void set_page_poison(struct page *page)
52 struct page_ext *page_ext;
54 page_ext = lookup_page_ext(page);
55 __set_bit(PAGE_EXT_DEBUG_POISON, &page_ext->flags);
58 static inline void clear_page_poison(struct page *page)
60 struct page_ext *page_ext;
62 page_ext = lookup_page_ext(page);
63 __clear_bit(PAGE_EXT_DEBUG_POISON, &page_ext->flags);
66 static inline bool page_poison(struct page *page)
68 struct page_ext *page_ext;
70 page_ext = lookup_page_ext(page);
71 return test_bit(PAGE_EXT_DEBUG_POISON, &page_ext->flags);
74 static void poison_page(struct page *page)
76 void *addr = kmap_atomic(page);
78 set_page_poison(page);
79 memset(addr, PAGE_POISON, PAGE_SIZE);
83 void poison_pages(struct page *page, int n)
87 for (i = 0; i < n; i++)
88 poison_page(page + i);
91 static bool single_bit_flip(unsigned char a, unsigned char b)
93 unsigned char error = a ^ b;
95 return error && !(error & (error - 1));
98 static void check_poison_mem(unsigned char *mem, size_t bytes)
100 static DEFINE_RATELIMIT_STATE(ratelimit, 5 * HZ, 10);
101 unsigned char *start;
104 if (IS_ENABLED(CONFIG_PAGE_POISONING_NO_SANITY))
107 start = memchr_inv(mem, PAGE_POISON, bytes);
111 for (end = mem + bytes - 1; end > start; end--) {
112 if (*end != PAGE_POISON)
116 if (!__ratelimit(&ratelimit))
118 else if (start == end && single_bit_flip(*start, PAGE_POISON))
119 printk(KERN_ERR "pagealloc: single bit error\n");
121 printk(KERN_ERR "pagealloc: memory corruption\n");
123 print_hex_dump(KERN_ERR, "", DUMP_PREFIX_ADDRESS, 16, 1, start,
128 static void unpoison_page(struct page *page)
132 if (!page_poison(page))
135 addr = kmap_atomic(page);
136 check_poison_mem(addr, PAGE_SIZE);
137 clear_page_poison(page);
141 void unpoison_pages(struct page *page, int n)
145 for (i = 0; i < n; i++)
146 unpoison_page(page + i);
149 void kernel_poison_pages(struct page *page, int numpages, int enable)
151 if (!page_poisoning_enabled())
155 unpoison_pages(page, numpages);
157 poison_pages(page, numpages);