Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * hugepage-mmap:
0004  *
0005  * Example of using huge page memory in a user application using the mmap
0006  * system call.  Before running this application, make sure that the
0007  * administrator has mounted the hugetlbfs filesystem (on some directory
0008  * like /mnt) using the command mount -t hugetlbfs nodev /mnt. In this
0009  * example, the app is requesting memory of size 256MB that is backed by
0010  * huge pages.
0011  *
0012  * For the ia64 architecture, the Linux kernel reserves Region number 4 for
0013  * huge pages.  That means that if one requires a fixed address, a huge page
0014  * aligned address starting with 0x800000... will be required.  If a fixed
0015  * address is not required, the kernel will select an address in the proper
0016  * range.
0017  * Other architectures, such as ppc64, i386 or x86_64 are not so constrained.
0018  */
0019 
0020 #include <stdlib.h>
0021 #include <stdio.h>
0022 #include <unistd.h>
0023 #include <sys/mman.h>
0024 #include <fcntl.h>
0025 
0026 #define FILE_NAME "huge/hugepagefile"
0027 #define LENGTH (256UL*1024*1024)
0028 #define PROTECTION (PROT_READ | PROT_WRITE)
0029 
0030 /* Only ia64 requires this */
0031 #ifdef __ia64__
0032 #define ADDR (void *)(0x8000000000000000UL)
0033 #define FLAGS (MAP_SHARED | MAP_FIXED)
0034 #else
0035 #define ADDR (void *)(0x0UL)
0036 #define FLAGS (MAP_SHARED)
0037 #endif
0038 
0039 static void check_bytes(char *addr)
0040 {
0041     printf("First hex is %x\n", *((unsigned int *)addr));
0042 }
0043 
0044 static void write_bytes(char *addr)
0045 {
0046     unsigned long i;
0047 
0048     for (i = 0; i < LENGTH; i++)
0049         *(addr + i) = (char)i;
0050 }
0051 
0052 static int read_bytes(char *addr)
0053 {
0054     unsigned long i;
0055 
0056     check_bytes(addr);
0057     for (i = 0; i < LENGTH; i++)
0058         if (*(addr + i) != (char)i) {
0059             printf("Mismatch at %lu\n", i);
0060             return 1;
0061         }
0062     return 0;
0063 }
0064 
0065 int main(void)
0066 {
0067     void *addr;
0068     int fd, ret;
0069 
0070     fd = open(FILE_NAME, O_CREAT | O_RDWR, 0755);
0071     if (fd < 0) {
0072         perror("Open failed");
0073         exit(1);
0074     }
0075 
0076     addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, fd, 0);
0077     if (addr == MAP_FAILED) {
0078         perror("mmap");
0079         unlink(FILE_NAME);
0080         exit(1);
0081     }
0082 
0083     printf("Returned address is %p\n", addr);
0084     check_bytes(addr);
0085     write_bytes(addr);
0086     ret = read_bytes(addr);
0087 
0088     munmap(addr, LENGTH);
0089     close(fd);
0090     unlink(FILE_NAME);
0091 
0092     return ret;
0093 }