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