hugetlbfstest.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #define _GNU_SOURCE
  2. #include <assert.h>
  3. #include <fcntl.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <sys/mman.h>
  8. #include <sys/stat.h>
  9. #include <sys/types.h>
  10. #include <unistd.h>
  11. typedef unsigned long long u64;
  12. static size_t length = 1 << 24;
  13. static u64 read_rss(void)
  14. {
  15. char buf[4096], *s = buf;
  16. int i, fd;
  17. u64 rss;
  18. fd = open("/proc/self/statm", O_RDONLY);
  19. assert(fd > 2);
  20. memset(buf, 0, sizeof(buf));
  21. read(fd, buf, sizeof(buf) - 1);
  22. for (i = 0; i < 1; i++)
  23. s = strchr(s, ' ') + 1;
  24. rss = strtoull(s, NULL, 10);
  25. return rss << 12; /* assumes 4k pagesize */
  26. }
  27. static void do_mmap(int fd, int extra_flags, int unmap)
  28. {
  29. int *p;
  30. int flags = MAP_PRIVATE | MAP_POPULATE | extra_flags;
  31. u64 before, after;
  32. int ret;
  33. before = read_rss();
  34. p = mmap(NULL, length, PROT_READ | PROT_WRITE, flags, fd, 0);
  35. assert(p != MAP_FAILED ||
  36. !"mmap returned an unexpected error");
  37. after = read_rss();
  38. assert(llabs(after - before - length) < 0x40000 ||
  39. !"rss didn't grow as expected");
  40. if (!unmap)
  41. return;
  42. ret = munmap(p, length);
  43. assert(!ret || !"munmap returned an unexpected error");
  44. after = read_rss();
  45. assert(llabs(after - before) < 0x40000 ||
  46. !"rss didn't shrink as expected");
  47. }
  48. static int open_file(const char *path)
  49. {
  50. int fd, err;
  51. unlink(path);
  52. fd = open(path, O_CREAT | O_RDWR | O_TRUNC | O_EXCL
  53. | O_LARGEFILE | O_CLOEXEC, 0600);
  54. assert(fd > 2);
  55. unlink(path);
  56. err = ftruncate(fd, length);
  57. assert(!err);
  58. return fd;
  59. }
  60. int main(void)
  61. {
  62. int hugefd, fd;
  63. fd = open_file("/dev/shm/hugetlbhog");
  64. hugefd = open_file("/hugepages/hugetlbhog");
  65. system("echo 100 > /proc/sys/vm/nr_hugepages");
  66. do_mmap(-1, MAP_ANONYMOUS, 1);
  67. do_mmap(fd, 0, 1);
  68. do_mmap(-1, MAP_ANONYMOUS | MAP_HUGETLB, 1);
  69. do_mmap(hugefd, 0, 1);
  70. do_mmap(hugefd, MAP_HUGETLB, 1);
  71. /* Leak the last one to test do_exit() */
  72. do_mmap(-1, MAP_ANONYMOUS | MAP_HUGETLB, 0);
  73. printf("oll korrekt.\n");
  74. return 0;
  75. }