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