2 * Copyright 2004-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
22 #include <folly/portability/SysMman.h>
23 #include <folly/portability/Unistd.h>
25 namespace folly { namespace detail {
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);
38 void* allocate(size_t size) {
39 auto len = computeSize(size);
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(
46 PROT_READ | PROT_WRITE,
47 MAP_PRIVATE | MAP_ANONYMOUS
55 if (mem == reinterpret_cast<void*>(-1)) {
56 throw std::system_error(errno, std::system_category());
58 #if !defined(MAP_POPULATE) && defined(MADV_WILLNEED)
59 madvise(mem, size, MADV_WILLNEED);
65 void deallocate(void* p, size_t size) {
66 auto len = computeSize(size);
71 template<typename Allocator>
72 struct GivesZeroFilledMemory : public std::false_type {};
75 struct GivesZeroFilledMemory<MMapAlloc> : public std::true_type{};