Create the sys/mman.h portability header
[folly.git] / folly / detail / AtomicUnorderedMapUtils.h
1 #pragma once
2
3 #include <atomic>
4 #include <stdint.h>
5 #include <unistd.h>
6
7 #include <folly/portability/SysMman.h>
8
9 namespace folly { namespace detail {
10
11 class MMapAlloc {
12  private:
13   size_t computeSize(size_t size) {
14     long pagesize = sysconf(_SC_PAGESIZE);
15     size_t mmapLength = ((size - 1) & ~(pagesize - 1)) + pagesize;
16     assert(size <= mmapLength && mmapLength < size + pagesize);
17     assert((mmapLength % pagesize) == 0);
18     return mmapLength;
19   }
20
21  public:
22   void* allocate(size_t size) {
23     auto len = computeSize(size);
24
25     // MAP_HUGETLB is a perf win, but requires cooperation from the
26     // deployment environment (and a change to computeSize()).
27     void* mem = static_cast<void*>(mmap(
28          nullptr,
29          len,
30          PROT_READ | PROT_WRITE,
31          MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE,
32          -1,
33          0));
34     if (mem == reinterpret_cast<void*>(-1)) {
35       throw std::system_error(errno, std::system_category());
36     }
37
38     return mem;
39   }
40
41   void deallocate(void* p, size_t size) {
42     auto len = computeSize(size);
43     munmap(p, len);
44   }
45 };
46
47 template<typename Allocator>
48 struct GivesZeroFilledMemory : public std::false_type {};
49
50 template<>
51 struct GivesZeroFilledMemory<MMapAlloc> : public std::true_type{};
52
53 }}