Fix copyright lines
[folly.git] / folly / detail / AtomicUnorderedMapUtils.h
1 /*
2  * Copyright 2015-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <atomic>
20 #include <cstdint>
21
22 #include <folly/portability/SysMman.h>
23 #include <folly/portability/Unistd.h>
24
25 namespace folly { namespace detail {
26
27 class MMapAlloc {
28  private:
29   size_t computeSize(size_t size) {
30     long pagesize = sysconf(_SC_PAGESIZE);
31     size_t mmapLength = ((size - 1) & ~(pagesize - 1)) + pagesize;
32     assert(size <= mmapLength && mmapLength < size + pagesize);
33     assert((mmapLength % pagesize) == 0);
34     return mmapLength;
35   }
36
37  public:
38   void* allocate(size_t size) {
39     auto len = computeSize(size);
40
41     // MAP_HUGETLB is a perf win, but requires cooperation from the
42     // deployment environment (and a change to computeSize()).
43     void* mem = static_cast<void*>(mmap(
44         nullptr,
45         len,
46         PROT_READ | PROT_WRITE,
47         MAP_PRIVATE | MAP_ANONYMOUS
48 #ifdef MAP_POPULATE
49             |
50             MAP_POPULATE
51 #endif
52         ,
53         -1,
54         0));
55     if (mem == reinterpret_cast<void*>(-1)) {
56       throw std::system_error(errno, std::system_category());
57     }
58 #if !defined(MAP_POPULATE) && defined(MADV_WILLNEED)
59     madvise(mem, size, MADV_WILLNEED);
60 #endif
61
62     return mem;
63   }
64
65   void deallocate(void* p, size_t size) {
66     auto len = computeSize(size);
67     munmap(p, len);
68   }
69 };
70
71 template <typename Allocator>
72 struct GivesZeroFilledMemory : public std::false_type {};
73
74 template <>
75 struct GivesZeroFilledMemory<MMapAlloc> : public std::true_type{};
76
77 } // namespace detail
78 } // namespace folly