1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * hugepage-shm: 4 * 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. 10 * 11 * Note: The default shared memory limit is quite low on many kernels, 12 * you may need to increase it via: 13 * 14 * echo 268435456 > /proc/sys/kernel/shmmax 15 * 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: 20 * 21 * echo 4194304 > /proc/sys/kernel/shmall 22 */ 23 24 #include <stdlib.h> 25 #include <stdio.h> 26 #include <sys/types.h> 27 #include <sys/ipc.h> 28 #include <sys/shm.h> 29 #include <sys/mman.h> 30 31 #define LENGTH (256UL*1024*1024) 32 33 #define dprintf(x) printf(x) 34 35 int main(void) 36 { 37 int shmid; 38 unsigned long i; 39 char *shmaddr; 40 41 shmid = shmget(2, LENGTH, SHM_HUGETLB | IPC_CREAT | SHM_R | SHM_W); 42 if (shmid < 0) { 43 perror("shmget"); 44 exit(1); 45 } 46 printf("shmid: 0x%x\n", shmid); 47 48 shmaddr = shmat(shmid, NULL, 0); 49 if (shmaddr == (char *)-1) { 50 perror("Shared memory attach failure"); 51 shmctl(shmid, IPC_RMID, NULL); 52 exit(2); 53 } 54 printf("shmaddr: %p\n", shmaddr); 55 56 dprintf("Starting the writes:\n"); 57 for (i = 0; i < LENGTH; i++) { 58 shmaddr[i] = (char)(i); 59 if (!(i % (1024 * 1024))) 60 dprintf("."); 61 } 62 dprintf("\n"); 63 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); 68 exit(3); 69 } 70 dprintf("Done.\n"); 71 72 if (shmdt((const void *)shmaddr) != 0) { 73 perror("Detach failure"); 74 shmctl(shmid, IPC_RMID, NULL); 75 exit(4); 76 } 77 78 shmctl(shmid, IPC_RMID, NULL); 79 80 return 0; 81 } 82