hugetlbfstest.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. before = read_rss();
  33. p = mmap(NULL, length, PROT_READ | PROT_WRITE, flags, fd, 0);
  34. assert(p != MAP_FAILED ||
  35. !"mmap returned an unexpected error");
  36. after = read_rss();
  37. assert(llabs(after - before - length) < 0x40000 ||
  38. !"rss didn't grow as expected");
  39. if (!unmap)
  40. return;
  41. munmap(p, length);
  42. after = read_rss();
  43. assert(llabs(after - before) < 0x40000 ||
  44. !"rss didn't shrink as expected");
  45. }
  46. static int open_file(const char *path)
  47. {
  48. int fd, err;
  49. unlink(path);
  50. fd = open(path, O_CREAT | O_RDWR | O_TRUNC | O_EXCL
  51. | O_LARGEFILE | O_CLOEXEC, 0600);
  52. assert(fd > 2);
  53. unlink(path);
  54. err = ftruncate(fd, length);
  55. assert(!err);
  56. return fd;
  57. }
  58. int main(void)
  59. {
  60. int hugefd, fd;
  61. fd = open_file("/dev/shm/hugetlbhog");
  62. hugefd = open_file("/hugepages/hugetlbhog");
  63. system("echo 100 > /proc/sys/vm/nr_hugepages");
  64. do_mmap(-1, MAP_ANONYMOUS, 1);
  65. do_mmap(fd, 0, 1);
  66. do_mmap(-1, MAP_ANONYMOUS | MAP_HUGETLB, 1);
  67. do_mmap(hugefd, 0, 1);
  68. do_mmap(hugefd, MAP_HUGETLB, 1);
  69. /* Leak the last one to test do_exit() */
  70. do_mmap(-1, MAP_ANONYMOUS | MAP_HUGETLB, 0);
  71. printf("oll korrekt.\n");
  72. return 0;
  73. }