debug-pagealloc.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <linux/kernel.h>
  2. #include <linux/string.h>
  3. #include <linux/mm.h>
  4. #include <linux/highmem.h>
  5. #include <linux/page-debug-flags.h>
  6. #include <linux/poison.h>
  7. #include <linux/ratelimit.h>
  8. static inline void set_page_poison(struct page *page)
  9. {
  10. __set_bit(PAGE_DEBUG_FLAG_POISON, &page->debug_flags);
  11. }
  12. static inline void clear_page_poison(struct page *page)
  13. {
  14. __clear_bit(PAGE_DEBUG_FLAG_POISON, &page->debug_flags);
  15. }
  16. static inline bool page_poison(struct page *page)
  17. {
  18. return test_bit(PAGE_DEBUG_FLAG_POISON, &page->debug_flags);
  19. }
  20. static void poison_page(struct page *page)
  21. {
  22. void *addr = kmap_atomic(page);
  23. set_page_poison(page);
  24. memset(addr, PAGE_POISON, PAGE_SIZE);
  25. kunmap_atomic(addr);
  26. }
  27. static void poison_pages(struct page *page, int n)
  28. {
  29. int i;
  30. for (i = 0; i < n; i++)
  31. poison_page(page + i);
  32. }
  33. static bool single_bit_flip(unsigned char a, unsigned char b)
  34. {
  35. unsigned char error = a ^ b;
  36. return error && !(error & (error - 1));
  37. }
  38. static void check_poison_mem(unsigned char *mem, size_t bytes)
  39. {
  40. static DEFINE_RATELIMIT_STATE(ratelimit, 5 * HZ, 10);
  41. unsigned char *start;
  42. unsigned char *end;
  43. start = memchr_inv(mem, PAGE_POISON, bytes);
  44. if (!start)
  45. return;
  46. for (end = mem + bytes - 1; end > start; end--) {
  47. if (*end != PAGE_POISON)
  48. break;
  49. }
  50. if (!__ratelimit(&ratelimit))
  51. return;
  52. else if (start == end && single_bit_flip(*start, PAGE_POISON))
  53. printk(KERN_ERR "pagealloc: single bit error\n");
  54. else
  55. printk(KERN_ERR "pagealloc: memory corruption\n");
  56. print_hex_dump(KERN_ERR, "", DUMP_PREFIX_ADDRESS, 16, 1, start,
  57. end - start + 1, 1);
  58. dump_stack();
  59. }
  60. static void unpoison_page(struct page *page)
  61. {
  62. void *addr;
  63. if (!page_poison(page))
  64. return;
  65. addr = kmap_atomic(page);
  66. check_poison_mem(addr, PAGE_SIZE);
  67. clear_page_poison(page);
  68. kunmap_atomic(addr);
  69. }
  70. static void unpoison_pages(struct page *page, int n)
  71. {
  72. int i;
  73. for (i = 0; i < n; i++)
  74. unpoison_page(page + i);
  75. }
  76. void kernel_map_pages(struct page *page, int numpages, int enable)
  77. {
  78. if (enable)
  79. unpoison_pages(page, numpages);
  80. else
  81. poison_pages(page, numpages);
  82. }