hugetlb_vs_thp_test.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <stdio.h>
  3. #include <sys/mman.h>
  4. #include <unistd.h>
  5. #include "utils.h"
  6. /* This must match the huge page & THP size */
  7. #define SIZE (16 * 1024 * 1024)
  8. static int test_body(void)
  9. {
  10. void *addr;
  11. char *p;
  12. addr = (void *)0xa0000000;
  13. p = mmap(addr, SIZE, PROT_READ | PROT_WRITE,
  14. MAP_HUGETLB | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  15. if (p != MAP_FAILED) {
  16. /*
  17. * Typically the mmap will fail because no huge pages are
  18. * allocated on the system. But if there are huge pages
  19. * allocated the mmap will succeed. That's fine too, we just
  20. * munmap here before continuing. munmap() length of
  21. * MAP_HUGETLB memory must be hugepage aligned.
  22. */
  23. if (munmap(addr, SIZE)) {
  24. perror("munmap");
  25. return 1;
  26. }
  27. }
  28. p = mmap(addr, SIZE, PROT_READ | PROT_WRITE,
  29. MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
  30. if (p == MAP_FAILED) {
  31. printf("Mapping failed @ %p\n", addr);
  32. perror("mmap");
  33. return 1;
  34. }
  35. /*
  36. * Either a user or kernel access is sufficient to trigger the bug.
  37. * A kernel access is easier to spot & debug, as it will trigger the
  38. * softlockup or RCU stall detectors, and when the system is kicked
  39. * into xmon we get a backtrace in the kernel.
  40. *
  41. * A good option is:
  42. * getcwd(p, SIZE);
  43. *
  44. * For the purposes of this testcase it's preferable to spin in
  45. * userspace, so the harness can kill us if we get stuck. That way we
  46. * see a test failure rather than a dead system.
  47. */
  48. *p = 0xf;
  49. munmap(addr, SIZE);
  50. return 0;
  51. }
  52. static int test_main(void)
  53. {
  54. int i;
  55. /* 10,000 because it's a "bunch", and completes reasonably quickly */
  56. for (i = 0; i < 10000; i++)
  57. if (test_body())
  58. return 1;
  59. return 0;
  60. }
  61. int main(void)
  62. {
  63. return test_harness(test_main, "hugetlb_vs_thp");
  64. }