map_hugetlb.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 int 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. return 1;
  48. }
  49. return 0;
  50. }
  51. int main(void)
  52. {
  53. void *addr;
  54. int ret;
  55. addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, 0, 0);
  56. if (addr == MAP_FAILED) {
  57. perror("mmap");
  58. exit(1);
  59. }
  60. printf("Returned address is %p\n", addr);
  61. check_bytes(addr);
  62. write_bytes(addr);
  63. ret = read_bytes(addr);
  64. munmap(addr, LENGTH);
  65. return ret;
  66. }