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 * Note: The default shared memory limit is quite low on many kernels,
12 * you may need to increase it via:
14 * echo 268435456 > /proc/sys/kernel/shmmax
16 * This will increase the maximum size per shared memory segment to 256MB.
17 * The other limit that you will hit eventually is shmall which is the
18 * total amount of shared memory in pages. To set it to 16GB on a system
19 * with a 4kB pagesize do:
21 * echo 4194304 > /proc/sys/kernel/shmall
26 #include <sys/types.h>
31 #define LENGTH (256UL*1024*1024)
33 #define dprintf(x) printf(x)
41 shmid
= shmget(2, LENGTH
, SHM_HUGETLB
| IPC_CREAT
| SHM_R
| SHM_W
);
46 printf("shmid: 0x%x\n", shmid
);
48 shmaddr
= shmat(shmid
, NULL
, 0);
49 if (shmaddr
== (char *)-1) {
50 perror("Shared memory attach failure");
51 shmctl(shmid
, IPC_RMID
, NULL
);
54 printf("shmaddr: %p\n", shmaddr
);
56 dprintf("Starting the writes:\n");
57 for (i
= 0; i
< LENGTH
; i
++) {
58 shmaddr
[i
] = (char)(i
);
59 if (!(i
% (1024 * 1024)))
64 dprintf("Starting the Check...");
65 for (i
= 0; i
< LENGTH
; i
++)
66 if (shmaddr
[i
] != (char)i
) {
67 printf("\nIndex %lu mismatched\n", i
);
72 if (shmdt((const void *)shmaddr
) != 0) {
73 perror("Detach failure");
74 shmctl(shmid
, IPC_RMID
, NULL
);
78 shmctl(shmid
, IPC_RMID
, NULL
);