4141#include < array>
4242#include < fcntl.h>
4343#include < filesystem>
44+
45+ // <linux/mman.h> provides some linux-specific flags like
46+ // MAP_POPULATE, MAP_NORESERVE, MAP_HUGETLB.
47+ // They can be used only with linux, and are not availiable
48+ // for MacOS
49+
50+ #if defined(__linux__)
4451#include < linux/mman.h>
52+ #endif // __linux__
53+
4554#include < memory>
4655#include < optional>
4756#include < string>
@@ -78,11 +87,19 @@ struct HugepageX86Parameters {
7887};
7988
8089// Hugepage Allocation will happen in the order given below.
90+ //
91+ // MAP_HUGETLB, MAP_HUGE_1GB, MAP_HUGE_2MB are linux-specific
92+ //
93+ #if defined(__linux__)
8194static constexpr std::array<HugepageX86Parameters, 3 > hugepage_x86_options{
8295 HugepageX86Parameters{1 << 30 , MAP_HUGETLB | MAP_HUGE_1GB},
8396 HugepageX86Parameters{1 << 21 , MAP_HUGETLB | MAP_HUGE_2MB},
8497 HugepageX86Parameters{1 << 12 , 0 },
8598};
99+ #else
100+ static constexpr std::array<HugepageX86Parameters, 1 > hugepage_x86_options{
101+ HugepageX86Parameters{1 << 12 , 0 }};
102+ #endif // __linux__
86103
87104namespace detail {
88105
@@ -104,14 +121,21 @@ struct HugepageAllocation {
104121 auto pagesize = params.pagesize ;
105122 auto flags = params.mmap_flags ;
106123 sz = lib::round_up_to_multiple_of (bytes, pagesize);
107- ptr = mmap (
108- nullptr ,
109- sz,
110- PROT_READ | PROT_WRITE,
111- MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE | flags,
112- -1 ,
113- 0
114- );
124+
125+ int mmap_flags = MAP_PRIVATE;
126+ #if defined(MAP_ANONYMOUS)
127+ mmap_flags |= MAP_ANONYMOUS;
128+ #elif defined(MAP_ANON)
129+ mmap_flags |= MAP_ANON;
130+ #else
131+ #error "System does not support anonymous mmap (no MAP_ANONYMOUS or MAP_ANON)"
132+ #endif
133+ // Add Linux-specific flags
134+ #ifdef __linux__
135+ mmap_flags |= MAP_POPULATE;
136+ #endif // __linux__
137+
138+ ptr = mmap (nullptr , sz, PROT_READ | PROT_WRITE, mmap_flags | flags, -1 , 0 );
115139
116140 if (ptr != MAP_FAILED) {
117141 break ;
@@ -489,15 +513,16 @@ class MemoryMapper {
489513 }
490514 }
491515 lseek (fd, 0 , SEEK_SET);
516+
517+ int mmap_flags = MAP_SHARED; // Accessible from all processes
518+ // Add Linux-specific flags
519+ #ifdef __linux__
520+ mmap_flags |= MAP_NORESERVE; // Don't reserve space in DRAM for this until used
521+ mmap_flags |= MAP_POPULATE; // Populate page table entries in the DRAM
522+ #endif // __linux__
523+
492524 void * base = ::mmap (
493- nullptr ,
494- bytes.value (),
495- mmap_permissions (permission_),
496- MAP_NORESERVE // Don't reserve space in DRAM for this until used
497- | MAP_SHARED // Accessible from all processes
498- | MAP_POPULATE, // Populate page table entries in the DRAM
499- fd,
500- 0
525+ nullptr , bytes.value (), mmap_permissions (permission_), mmap_flags, fd, 0
501526 );
502527 close (fd);
503528
0 commit comments