map_hugetlb.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Example of using hugepage memory in a user application using the mmap
  4. * system call with MAP_HUGETLB flag. Before running this program make
  5. * sure the administrator has allocated enough default sized huge pages
  6. * to cover the 256 MB allocation.
  7. */
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <unistd.h>
  11. #include <sys/mman.h>
  12. #include <fcntl.h>
  13. #include "vm_util.h"
  14. #include "../kselftest.h"
  15. #define LENGTH (256UL*1024*1024)
  16. #define PROTECTION (PROT_READ | PROT_WRITE)
  17. static void check_bytes(char *addr)
  18. {
  19. ksft_print_msg("First hex is %x\n", *((unsigned int *)addr));
  20. }
  21. static void write_bytes(char *addr, size_t length)
  22. {
  23. unsigned long i;
  24. for (i = 0; i < length; i++)
  25. *(addr + i) = (char)i;
  26. }
  27. static void read_bytes(char *addr, size_t length)
  28. {
  29. unsigned long i;
  30. check_bytes(addr);
  31. for (i = 0; i < length; i++)
  32. if (*(addr + i) != (char)i)
  33. ksft_exit_fail_msg("Mismatch at %lu\n", i);
  34. ksft_test_result_pass("Read correct data\n");
  35. }
  36. int main(int argc, char **argv)
  37. {
  38. void *addr;
  39. size_t hugepage_size;
  40. size_t length = LENGTH;
  41. int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB;
  42. int shift = 0;
  43. hugepage_size = default_huge_page_size();
  44. /* munmap with fail if the length is not page aligned */
  45. if (hugepage_size > length)
  46. length = hugepage_size;
  47. ksft_print_header();
  48. ksft_set_plan(1);
  49. if (argc > 1)
  50. length = atol(argv[1]) << 20;
  51. if (argc > 2) {
  52. shift = atoi(argv[2]);
  53. if (shift)
  54. flags |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
  55. }
  56. if (shift)
  57. ksft_print_msg("%u kB hugepages\n", 1 << (shift - 10));
  58. else
  59. ksft_print_msg("Default size hugepages\n");
  60. ksft_print_msg("Mapping %lu Mbytes\n", (unsigned long)length >> 20);
  61. addr = mmap(NULL, length, PROTECTION, flags, -1, 0);
  62. if (addr == MAP_FAILED)
  63. ksft_exit_fail_msg("mmap: %s\n", strerror(errno));
  64. ksft_print_msg("Returned address is %p\n", addr);
  65. check_bytes(addr);
  66. write_bytes(addr, length);
  67. read_bytes(addr, length);
  68. /* munmap() length of MAP_HUGETLB memory must be hugepage aligned */
  69. if (munmap(addr, length))
  70. ksft_exit_fail_msg("munmap: %s\n", strerror(errno));
  71. ksft_finished();
  72. }