GNU Linux-libre 4.19.286-gnu1
[releases.git] / tools / testing / selftests / vm / gup_benchmark.c
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5
6 #include <sys/ioctl.h>
7 #include <sys/mman.h>
8 #include <sys/prctl.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11
12 #include <linux/types.h>
13
14 #define MB (1UL << 20)
15 #define PAGE_SIZE sysconf(_SC_PAGESIZE)
16
17 #define GUP_FAST_BENCHMARK      _IOWR('g', 1, struct gup_benchmark)
18
19 struct gup_benchmark {
20         __u64 delta_usec;
21         __u64 addr;
22         __u64 size;
23         __u32 nr_pages_per_call;
24         __u32 flags;
25         __u64 expansion[10];    /* For future use */
26 };
27
28 int main(int argc, char **argv)
29 {
30         struct gup_benchmark gup;
31         unsigned long size = 128 * MB;
32         int i, fd, opt, nr_pages = 1, thp = -1, repeats = 1, write = 0;
33         char *p;
34
35         while ((opt = getopt(argc, argv, "m:r:n:tT")) != -1) {
36                 switch (opt) {
37                 case 'm':
38                         size = atoi(optarg) * MB;
39                         break;
40                 case 'r':
41                         repeats = atoi(optarg);
42                         break;
43                 case 'n':
44                         nr_pages = atoi(optarg);
45                         break;
46                 case 't':
47                         thp = 1;
48                         break;
49                 case 'T':
50                         thp = 0;
51                         break;
52                 case 'w':
53                         write = 1;
54                         break;
55                 default:
56                         return -1;
57                 }
58         }
59
60         gup.nr_pages_per_call = nr_pages;
61         gup.flags = write;
62
63         fd = open("/sys/kernel/debug/gup_benchmark", O_RDWR);
64         if (fd == -1)
65                 perror("open"), exit(1);
66
67         p = mmap(NULL, size, PROT_READ | PROT_WRITE,
68                         MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
69         if (p == MAP_FAILED)
70                 perror("mmap"), exit(1);
71         gup.addr = (unsigned long)p;
72
73         if (thp == 1)
74                 madvise(p, size, MADV_HUGEPAGE);
75         else if (thp == 0)
76                 madvise(p, size, MADV_NOHUGEPAGE);
77
78         for (; (unsigned long)p < gup.addr + size; p += PAGE_SIZE)
79                 p[0] = 0;
80
81         for (i = 0; i < repeats; i++) {
82                 gup.size = size;
83                 if (ioctl(fd, GUP_FAST_BENCHMARK, &gup))
84                         perror("ioctl"), exit(1);
85
86                 printf("Time: %lld us", gup.delta_usec);
87                 if (gup.size != size)
88                         printf(", truncated (size: %lld)", gup.size);
89                 printf("\n");
90         }
91
92         return 0;
93 }