hugepage-mmap.c 2.0 KB

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