hugepage-mmap.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 "huge/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 int 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. return 1;
  52. }
  53. return 0;
  54. }
  55. int main(void)
  56. {
  57. void *addr;
  58. int fd, ret;
  59. fd = open(FILE_NAME, O_CREAT | O_RDWR, 0755);
  60. if (fd < 0) {
  61. perror("Open failed");
  62. exit(1);
  63. }
  64. addr = mmap(ADDR, LENGTH, PROTECTION, FLAGS, fd, 0);
  65. if (addr == MAP_FAILED) {
  66. perror("mmap");
  67. unlink(FILE_NAME);
  68. exit(1);
  69. }
  70. printf("Returned address is %p\n", addr);
  71. check_bytes(addr);
  72. write_bytes(addr);
  73. ret = read_bytes(addr);
  74. munmap(addr, LENGTH);
  75. close(fd);
  76. unlink(FILE_NAME);
  77. return ret;
  78. }