2 * Copyright 2014 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.
17 #include "folly/MemoryMapping.h"
18 #include "folly/Format.h"
19 #include "folly/Portability.h"
22 #include "folly/experimental/io/HugePages.h"
27 #include <sys/types.h>
28 #include <system_error>
29 #include <gflags/gflags.h>
31 DEFINE_int64(mlock_chunk_size, 1 << 20, // 1MB
32 "Maximum bytes to mlock/munlock/munmap at once "
33 "(will be rounded up to PAGESIZE)");
36 #define MAP_POPULATE 0
41 MemoryMapping::MemoryMapping(MemoryMapping&& other) {
45 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length,
47 : file_(std::move(file)),
48 options_(std::move(options)) {
53 MemoryMapping::MemoryMapping(const char* name, off_t offset, off_t length,
55 : MemoryMapping(File(name), offset, length, options) { }
57 MemoryMapping::MemoryMapping(int fd, off_t offset, off_t length,
59 : MemoryMapping(File(fd), offset, length, options) { }
61 MemoryMapping::MemoryMapping(AnonymousType, off_t length, Options options)
62 : options_(std::move(options)) {
69 void getDeviceOptions(dev_t device, off_t& pageSize, bool& autoExtend) {
70 auto ps = getHugePageSizeForDevice(device);
77 inline void getDeviceOptions(dev_t device, off_t& pageSize,
83 void MemoryMapping::init(off_t offset, off_t length) {
84 const bool grow = options_.grow;
85 const bool anon = !file_;
86 CHECK(!(grow && anon));
88 off_t& pageSize = options_.pageSize;
92 // On Linux, hugetlbfs file systems don't require ftruncate() to grow the
93 // file, and (on kernels before 2.6.24) don't even allow it. Also, the file
94 // size is always a multiple of the page size.
95 bool autoExtend = false;
99 CHECK_ERR(fstat(file_.fd(), &st));
102 getDeviceOptions(st.st_dev, pageSize, autoExtend);
106 DCHECK_EQ(offset, 0);
107 CHECK_EQ(pageSize, 0);
112 pageSize = sysconf(_SC_PAGESIZE);
115 CHECK_GT(pageSize, 0);
116 CHECK_EQ(pageSize & (pageSize - 1), 0); // power of two
119 // Round down the start of the mapped region
120 size_t skipStart = offset % pageSize;
124 if (mapLength_ != -1) {
125 mapLength_ += skipStart;
127 // Round up the end of the mapped region
128 mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
131 off_t remaining = anon ? length : st.st_size - offset;
133 if (mapLength_ == -1) {
134 length = mapLength_ = remaining;
136 if (length > remaining) {
139 PCHECK(0 == ftruncate(file_.fd(), offset + length))
140 << "ftruncate() failed, couldn't grow file to "
144 // Extend mapping to multiple of page size, don't use ftruncate
145 remaining = mapLength_;
151 if (mapLength_ > remaining) {
152 mapLength_ = remaining;
160 int flags = options_.shared ? MAP_SHARED : MAP_PRIVATE;
161 if (anon) flags |= MAP_ANONYMOUS;
162 if (options_.prefault) flags |= MAP_POPULATE;
164 // The standard doesn't actually require PROT_NONE to be zero...
165 int prot = PROT_NONE;
166 if (options_.readable || options_.writable) {
167 prot = ((options_.readable ? PROT_READ : 0) |
168 (options_.writable ? PROT_WRITE : 0));
171 unsigned char* start = static_cast<unsigned char*>(
172 mmap(options_.address, mapLength_, prot, flags, file_.fd(), offset));
173 PCHECK(start != MAP_FAILED)
174 << " offset=" << offset
175 << " length=" << mapLength_;
177 data_.reset(start + skipStart, length);
183 off_t memOpChunkSize(off_t length, off_t pageSize) {
184 off_t chunkSize = length;
185 if (FLAGS_mlock_chunk_size <= 0) {
189 chunkSize = FLAGS_mlock_chunk_size;
190 off_t r = chunkSize % pageSize;
192 chunkSize += (pageSize - r);
198 * Run @op in chunks over the buffer @mem of @bufSize length.
201 * - success: true + amountSucceeded == bufSize (op success on whole buffer)
202 * - failure: false + amountSucceeded == nr bytes on which op succeeded.
204 bool memOpInChunks(std::function<int(void*, size_t)> op,
205 void* mem, size_t bufSize, off_t pageSize,
206 size_t& amountSucceeded) {
207 // unmap/mlock/munlock take a kernel semaphore and block other threads from
208 // doing other memory operations. If the size of the buffer is big the
209 // semaphore can be down for seconds (for benchmarks see
210 // http://kostja-osipov.livejournal.com/42963.html). Doing the operations in
211 // chunks breaks the locking into intervals and lets other threads do memory
212 // operations of their own.
214 size_t chunkSize = memOpChunkSize(bufSize, pageSize);
216 char* addr = static_cast<char*>(mem);
219 while (amountSucceeded < bufSize) {
220 size_t size = std::min(chunkSize, bufSize - amountSucceeded);
221 if (op(addr + amountSucceeded, size) != 0) {
224 amountSucceeded += size;
230 } // anonymous namespace
232 bool MemoryMapping::mlock(LockMode lock) {
233 size_t amountSucceeded = 0;
234 locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, options_.pageSize,
240 auto msg(folly::format(
241 "mlock({}) failed at {}",
242 mapLength_, amountSucceeded).str());
244 if (lock == LockMode::TRY_LOCK && (errno == EPERM || errno == ENOMEM)) {
245 PLOG(WARNING) << msg;
250 // only part of the buffer was mlocked, unlock it back
251 if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, options_.pageSize,
253 PLOG(WARNING) << "munlock()";
259 void MemoryMapping::munlock(bool dontneed) {
260 if (!locked_) return;
262 size_t amountSucceeded = 0;
263 if (!memOpInChunks(::munlock, mapStart_, mapLength_, options_.pageSize,
265 PLOG(WARNING) << "munlock()";
267 if (mapLength_ && dontneed &&
268 ::madvise(mapStart_, mapLength_, MADV_DONTNEED)) {
269 PLOG(WARNING) << "madvise()";
274 void MemoryMapping::hintLinearScan() {
275 advise(MADV_SEQUENTIAL);
278 MemoryMapping::~MemoryMapping() {
280 size_t amountSucceeded = 0;
281 if (!memOpInChunks(::munmap, mapStart_, mapLength_, options_.pageSize,
283 PLOG(FATAL) << folly::format(
284 "munmap({}) failed at {}",
285 mapLength_, amountSucceeded).str();
290 void MemoryMapping::advise(int advice) const {
291 if (mapLength_ && ::madvise(mapStart_, mapLength_, advice)) {
292 PLOG(WARNING) << "madvise()";
296 MemoryMapping& MemoryMapping::operator=(MemoryMapping other) {
301 void MemoryMapping::swap(MemoryMapping& other) {
303 swap(this->file_, other.file_);
304 swap(this->mapStart_, other.mapStart_);
305 swap(this->mapLength_, other.mapLength_);
306 swap(this->options_, other.options_);
307 swap(this->locked_, other.locked_);
308 swap(this->data_, other.data_);
311 void swap(MemoryMapping& a, MemoryMapping& b) { a.swap(b); }
313 void alignedForwardMemcpy(void* dst, const void* src, size_t size) {
314 assert(reinterpret_cast<uintptr_t>(src) % alignof(unsigned long) == 0);
315 assert(reinterpret_cast<uintptr_t>(dst) % alignof(unsigned long) == 0);
317 auto srcl = static_cast<const unsigned long*>(src);
318 auto dstl = static_cast<unsigned long*>(dst);
320 while (size >= sizeof(unsigned long)) {
322 size -= sizeof(unsigned long);
325 auto srcc = reinterpret_cast<const unsigned char*>(srcl);
326 auto dstc = reinterpret_cast<unsigned char*>(dstl);
334 void mmapFileCopy(const char* src, const char* dest, mode_t mode) {
335 MemoryMapping srcMap(src);
336 srcMap.hintLinearScan();
338 MemoryMapping destMap(
339 File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
341 srcMap.range().size(),
342 MemoryMapping::writable());
344 alignedForwardMemcpy(destMap.writableRange().data(),
345 srcMap.range().data(),
346 srcMap.range().size());