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#include "vm_util.h"
19
20#define LENGTH (256UL*1024*1024)
21#define PROTECTION (PROT_READ | PROT_WRITE)
22
23/* Only ia64 requires this */
24#ifdef __ia64__
25#define ADDR (void *)(0x8000000000000000UL)
26#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_FIXED)
27#else
28#define ADDR (void *)(0x0UL)
29#define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB)
30#endif
31
32static void check_bytes(char *addr)
33{
34	printf("First hex is %x\n", *((unsigned int *)addr));
35}
36
37static void write_bytes(char *addr, size_t length)
38{
39	unsigned long i;
40
41	for (i = 0; i < length; i++)
42		*(addr + i) = (char)i;
43}
44
45static int read_bytes(char *addr, size_t length)
46{
47	unsigned long i;
48
49	check_bytes(addr);
50	for (i = 0; i < length; i++)
51		if (*(addr + i) != (char)i) {
52			printf("Mismatch at %lu\n", i);
53			return 1;
54		}
55	return 0;
56}
57
58int main(int argc, char **argv)
59{
60	void *addr;
61	int ret;
62	size_t hugepage_size;
63	size_t length = LENGTH;
64	int flags = FLAGS;
65	int shift = 0;
66
67	hugepage_size = default_huge_page_size();
68	/* munmap with fail if the length is not page aligned */
69	if (hugepage_size > length)
70		length = hugepage_size;
71
72	if (argc > 1)
73		length = atol(argv[1]) << 20;
74	if (argc > 2) {
75		shift = atoi(argv[2]);
76		if (shift)
77			flags |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
78	}
79
80	if (shift)
81		printf("%u kB hugepages\n", 1 << (shift - 10));
82	else
83		printf("Default size hugepages\n");
84	printf("Mapping %lu Mbytes\n", (unsigned long)length >> 20);
85
86	addr = mmap(ADDR, length, PROTECTION, flags, -1, 0);
87	if (addr == MAP_FAILED) {
88		perror("mmap");
89		exit(1);
90	}
91
92	printf("Returned address is %p\n", addr);
93	check_bytes(addr);
94	write_bytes(addr, length);
95	ret = read_bytes(addr, length);
96
97	/* munmap() length of MAP_HUGETLB memory must be hugepage aligned */
98	if (munmap(addr, length)) {
99		perror("munmap");
100		exit(1);
101	}
102
103	return ret;
104}
105