hugepage-mmap.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * hugepage-mmap:
  4. *
  5. * Example of using huge page memory in a user application using the mmap
  6. * system call. Before running this application, make sure that the
  7. * administrator has mounted the hugetlbfs filesystem (on some directory
  8. * like /mnt) using the command mount -t hugetlbfs nodev /mnt. In this
  9. * example, the app is requesting memory of size 256MB that is backed by
  10. * huge pages.
  11. */
  12. #define _GNU_SOURCE
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include <unistd.h>
  16. #include <sys/mman.h>
  17. #include <fcntl.h>
  18. #include "../kselftest.h"
  19. #define LENGTH (256UL*1024*1024)
  20. #define PROTECTION (PROT_READ | PROT_WRITE)
  21. static void check_bytes(char *addr)
  22. {
  23. ksft_print_msg("First hex is %x\n", *((unsigned int *)addr));
  24. }
  25. static void write_bytes(char *addr)
  26. {
  27. unsigned long i;
  28. for (i = 0; i < LENGTH; i++)
  29. *(addr + i) = (char)i;
  30. }
  31. static int read_bytes(char *addr)
  32. {
  33. unsigned long i;
  34. check_bytes(addr);
  35. for (i = 0; i < LENGTH; i++)
  36. if (*(addr + i) != (char)i) {
  37. ksft_print_msg("Error: Mismatch at %lu\n", i);
  38. return 1;
  39. }
  40. return 0;
  41. }
  42. int main(void)
  43. {
  44. void *addr;
  45. int fd, ret;
  46. ksft_print_header();
  47. ksft_set_plan(1);
  48. fd = memfd_create("hugepage-mmap", MFD_HUGETLB);
  49. if (fd < 0)
  50. ksft_exit_fail_msg("memfd_create() failed: %s\n", strerror(errno));
  51. addr = mmap(NULL, LENGTH, PROTECTION, MAP_SHARED, fd, 0);
  52. if (addr == MAP_FAILED) {
  53. close(fd);
  54. ksft_exit_fail_msg("mmap(): %s\n", strerror(errno));
  55. }
  56. ksft_print_msg("Returned address is %p\n", addr);
  57. check_bytes(addr);
  58. write_bytes(addr);
  59. ret = read_bytes(addr);
  60. munmap(addr, LENGTH);
  61. close(fd);
  62. ksft_test_result(!ret, "Read same data\n");
  63. ksft_exit(!ret);
  64. }