map_hugetlb.c 1.7 KB

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