GNU Linux-libre 4.19.264-gnu1
[releases.git] / tools / testing / selftests / vm / map_hugetlb.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Example of using hugepage memory in a user application using the mmap
4  * system call with MAP_HUGETLB flag.  Before running this program make
5  * sure the administrator has allocated enough default sized huge pages
6  * to cover the 256 MB allocation.
7  *
8  * For ia64 architecture, Linux kernel reserves Region number 4 for hugepages.
9  * That means the addresses starting with 0x800000... will need to be
10  * specified.  Specifying a fixed address is not required on ppc64, i386
11  * or x86_64.
12  */
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <sys/mman.h>
17 #include <fcntl.h>
18
19 #define LENGTH (256UL*1024*1024)
20 #define PROTECTION (PROT_READ | PROT_WRITE)
21
22 #ifndef MAP_HUGETLB
23 #define MAP_HUGETLB 0x40000 /* arch specific */
24 #endif
25
26 /* Only ia64 requires this */
27 #ifdef __ia64__
28 #define ADDR (void *)(0x8000000000000000UL)
29 #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_FIXED)
30 #else
31 #define ADDR (void *)(0x0UL)
32 #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB)
33 #endif
34
35 static void check_bytes(char *addr)
36 {
37         printf("First hex is %x\n", *((unsigned int *)addr));
38 }
39
40 static void write_bytes(char *addr)
41 {
42         unsigned long i;
43
44         for (i = 0; i < LENGTH; i++)
45                 *(addr + i) = (char)i;
46 }
47
48 static int read_bytes(char *addr)
49 {
50         unsigned long i;
51
52         check_bytes(addr);
53         for (i = 0; i < LENGTH; i++)
54                 if (*(addr + i) != (char)i) {
55                         printf("Mismatch at %lu\n", i);
56                         return 1;
57                 }
58         return 0;
59 }
60
61 int main(void)
62 {
63         void *addr;
64         int ret;
65
66         addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, -1, 0);
67         if (addr == MAP_FAILED) {
68                 perror("mmap");
69                 exit(1);
70         }
71
72         printf("Returned address is %p\n", addr);
73         check_bytes(addr);
74         write_bytes(addr);
75         ret = read_bytes(addr);
76
77         /* munmap() length of MAP_HUGETLB memory must be hugepage aligned */
78         if (munmap(addr, LENGTH)) {
79                 perror("munmap");
80                 exit(1);
81         }
82
83         return ret;
84 }