1 // SPDX-License-Identifier: GPL-2.0
5 * Example of using huge page memory in a user application using Sys V shared
6 * memory system calls. In this example the app is requesting 256MB of
7 * memory that is backed by huge pages. The application uses the flag
8 * SHM_HUGETLB in the shmget system call to inform the kernel that it is
9 * requesting huge pages.
11 * For the ia64 architecture, the Linux kernel reserves Region number 4 for
12 * huge pages. That means that if one requires a fixed address, a huge page
13 * aligned address starting with 0x800000... will be required. If a fixed
14 * address is not required, the kernel will select an address in the proper
16 * Other architectures, such as ppc64, i386 or x86_64 are not so constrained.
18 * Note: The default shared memory limit is quite low on many kernels,
19 * you may need to increase it via:
21 * echo 268435456 > /proc/sys/kernel/shmmax
23 * This will increase the maximum size per shared memory segment to 256MB.
24 * The other limit that you will hit eventually is shmall which is the
25 * total amount of shared memory in pages. To set it to 16GB on a system
26 * with a 4kB pagesize do:
28 * echo 4194304 > /proc/sys/kernel/shmall
33 #include <sys/types.h>
39 #define SHM_HUGETLB 04000
42 #define LENGTH (256UL*1024*1024)
44 #define dprintf(x) printf(x)
46 /* Only ia64 requires this */
48 #define ADDR (void *)(0x8000000000000000UL)
49 #define SHMAT_FLAGS (SHM_RND)
51 #define ADDR (void *)(0x0UL)
52 #define SHMAT_FLAGS (0)
61 shmid
= shmget(2, LENGTH
, SHM_HUGETLB
| IPC_CREAT
| SHM_R
| SHM_W
);
66 printf("shmid: 0x%x\n", shmid
);
68 shmaddr
= shmat(shmid
, ADDR
, SHMAT_FLAGS
);
69 if (shmaddr
== (char *)-1) {
70 perror("Shared memory attach failure");
71 shmctl(shmid
, IPC_RMID
, NULL
);
74 printf("shmaddr: %p\n", shmaddr
);
76 dprintf("Starting the writes:\n");
77 for (i
= 0; i
< LENGTH
; i
++) {
78 shmaddr
[i
] = (char)(i
);
79 if (!(i
% (1024 * 1024)))
84 dprintf("Starting the Check...");
85 for (i
= 0; i
< LENGTH
; i
++)
86 if (shmaddr
[i
] != (char)i
) {
87 printf("\nIndex %lu mismatched\n", i
);
92 if (shmdt((const void *)shmaddr
) != 0) {
93 perror("Detach failure");
94 shmctl(shmid
, IPC_RMID
, NULL
);
98 shmctl(shmid
, IPC_RMID
, NULL
);