hugepage-mmap.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * hugepage-mmap:
  4. *
  5. * Example of using huge page memory in a user application using the mmap
  6. * system call. Before running this application, make sure that the
  7. * administrator has mounted the hugetlbfs filesystem (on some directory
  8. * like /mnt) using the command mount -t hugetlbfs nodev /mnt. In this
  9. * example, the app is requesting memory of size 256MB that is backed by
  10. * huge pages.
  11. *
  12. * For the ia64 architecture, the Linux kernel reserves Region number 4 for
  13. * huge pages. That means that if one requires a fixed address, a huge page
  14. * aligned address starting with 0x800000... will be required. If a fixed
  15. * address is not required, the kernel will select an address in the proper
  16. * range.
  17. * Other architectures, such as ppc64, i386 or x86_64 are not so constrained.
  18. */
  19. #include <stdlib.h>
  20. #include <stdio.h>
  21. #include <unistd.h>
  22. #include <sys/mman.h>
  23. #include <fcntl.h>
  24. #define FILE_NAME "huge/hugepagefile"
  25. #define LENGTH (256UL*1024*1024)
  26. #define PROTECTION (PROT_READ | PROT_WRITE)
  27. /* Only ia64 requires this */
  28. #ifdef __ia64__
  29. #define ADDR (void *)(0x8000000000000000UL)
  30. #define FLAGS (MAP_SHARED | MAP_FIXED)
  31. #else
  32. #define ADDR (void *)(0x0UL)
  33. #define FLAGS (MAP_SHARED)
  34. #endif
  35. static void check_bytes(char *addr)
  36. {
  37. printf("First hex is %x\n", *((unsigned int *)addr));
  38. }
  39. static void write_bytes(char *addr)
  40. {
  41. unsigned long i;
  42. for (i = 0; i < LENGTH; i++)
  43. *(addr + i) = (char)i;
  44. }
  45. static int read_bytes(char *addr)
  46. {
  47. unsigned long i;
  48. check_bytes(addr);
  49. for (i = 0; i < LENGTH; i++)
  50. if (*(addr + i) != (char)i) {
  51. printf("Mismatch at %lu\n", i);
  52. return 1;
  53. }
  54. return 0;
  55. }
  56. int main(void)
  57. {
  58. void *addr;
  59. int fd, ret;
  60. fd = open(FILE_NAME, O_CREAT | O_RDWR, 0755);
  61. if (fd < 0) {
  62. perror("Open failed");
  63. exit(1);
  64. }
  65. addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, fd, 0);
  66. if (addr == MAP_FAILED) {
  67. perror("mmap");
  68. unlink(FILE_NAME);
  69. exit(1);
  70. }
  71. printf("Returned address is %p\n", addr);
  72. check_bytes(addr);
  73. write_bytes(addr);
  74. ret = read_bytes(addr);
  75. munmap(addr, LENGTH);
  76. close(fd);
  77. unlink(FILE_NAME);
  78. return ret;
  79. }