map_hugetlb.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Example of using hugepage memory in a user application using the mmap
  4. * system call with MAP_HUGETLB flag. Before running this program make
  5. * sure the administrator has allocated enough default sized huge pages
  6. * to cover the 256 MB allocation.
  7. *
  8. * For ia64 architecture, Linux kernel reserves Region number 4 for hugepages.
  9. * That means the addresses starting with 0x800000... will need to be
  10. * specified. Specifying a fixed address is not required on ppc64, i386
  11. * or x86_64.
  12. */
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include <unistd.h>
  16. #include <sys/mman.h>
  17. #include <fcntl.h>
  18. #define LENGTH (256UL*1024*1024)
  19. #define PROTECTION (PROT_READ | PROT_WRITE)
  20. #ifndef MAP_HUGETLB
  21. #define MAP_HUGETLB 0x40000 /* arch specific */
  22. #endif
  23. /* Only ia64 requires this */
  24. #ifdef __ia64__
  25. #define ADDR (void *)(0x8000000000000000UL)
  26. #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_FIXED)
  27. #else
  28. #define ADDR (void *)(0x0UL)
  29. #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB)
  30. #endif
  31. static void check_bytes(char *addr)
  32. {
  33. printf("First hex is %x\n", *((unsigned int *)addr));
  34. }
  35. static void write_bytes(char *addr)
  36. {
  37. unsigned long i;
  38. for (i = 0; i < LENGTH; i++)
  39. *(addr + i) = (char)i;
  40. }
  41. static int read_bytes(char *addr)
  42. {
  43. unsigned long i;
  44. check_bytes(addr);
  45. for (i = 0; i < LENGTH; i++)
  46. if (*(addr + i) != (char)i) {
  47. printf("Mismatch at %lu\n", i);
  48. return 1;
  49. }
  50. return 0;
  51. }
  52. int main(void)
  53. {
  54. void *addr;
  55. int ret;
  56. addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, -1, 0);
  57. if (addr == MAP_FAILED) {
  58. perror("mmap");
  59. exit(1);
  60. }
  61. printf("Returned address is %p\n", addr);
  62. check_bytes(addr);
  63. write_bytes(addr);
  64. ret = read_bytes(addr);
  65. /* munmap() length of MAP_HUGETLB memory must be hugepage aligned */
  66. if (munmap(addr, LENGTH)) {
  67. perror("munmap");
  68. exit(1);
  69. }
  70. return ret;
  71. }