2 * Copyright 2015 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>
23 #include <folly/Format.h>
26 #include <folly/experimental/io/HugePages.h>
31 #include <sys/types.h>
32 #include <system_error>
33 #include <gflags/gflags.h>
35 DEFINE_int64(mlock_chunk_size, 1 << 20, // 1MB
36 "Maximum bytes to mlock/munlock/munmap at once "
37 "(will be rounded up to PAGESIZE)");
40 #define MAP_POPULATE 0
45 MemoryMapping::MemoryMapping(MemoryMapping&& other) noexcept {
49 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length,
51 : file_(std::move(file)),
52 options_(std::move(options)) {
57 MemoryMapping::MemoryMapping(const char* name, off_t offset, off_t length,
59 : MemoryMapping(File(name, options.writable ? O_RDWR : O_RDONLY),
64 MemoryMapping::MemoryMapping(int fd, off_t offset, off_t length,
66 : MemoryMapping(File(fd), offset, length, options) { }
68 MemoryMapping::MemoryMapping(AnonymousType, off_t length, Options options)
69 : options_(std::move(options)) {
76 void getDeviceOptions(dev_t device, off_t& pageSize, bool& autoExtend) {
77 auto ps = getHugePageSizeForDevice(device);
84 inline void getDeviceOptions(dev_t device, off_t& pageSize,
90 void MemoryMapping::init(off_t offset, off_t length) {
91 const bool grow = options_.grow;
92 const bool anon = !file_;
93 CHECK(!(grow && anon));
95 off_t& pageSize = options_.pageSize;
99 // On Linux, hugetlbfs file systems don't require ftruncate() to grow the
100 // file, and (on kernels before 2.6.24) don't even allow it. Also, the file
101 // size is always a multiple of the page size.
102 bool autoExtend = false;
106 CHECK_ERR(fstat(file_.fd(), &st));
109 getDeviceOptions(st.st_dev, pageSize, autoExtend);
113 DCHECK_EQ(offset, 0);
114 CHECK_EQ(pageSize, 0);
119 pageSize = sysconf(_SC_PAGESIZE);
122 CHECK_GT(pageSize, 0);
123 CHECK_EQ(pageSize & (pageSize - 1), 0); // power of two
126 // Round down the start of the mapped region
127 size_t skipStart = offset % pageSize;
131 if (mapLength_ != -1) {
132 mapLength_ += skipStart;
134 // Round up the end of the mapped region
135 mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
138 off_t remaining = anon ? length : st.st_size - offset;
140 if (mapLength_ == -1) {
141 length = mapLength_ = remaining;
143 if (length > remaining) {
146 PCHECK(0 == ftruncate(file_.fd(), offset + length))
147 << "ftruncate() failed, couldn't grow file to "
151 // Extend mapping to multiple of page size, don't use ftruncate
152 remaining = mapLength_;
158 if (mapLength_ > remaining) {
159 mapLength_ = remaining;
167 int flags = options_.shared ? MAP_SHARED : MAP_PRIVATE;
168 if (anon) flags |= MAP_ANONYMOUS;
169 if (options_.prefault) flags |= MAP_POPULATE;
171 // The standard doesn't actually require PROT_NONE to be zero...
172 int prot = PROT_NONE;
173 if (options_.readable || options_.writable) {
174 prot = ((options_.readable ? PROT_READ : 0) |
175 (options_.writable ? PROT_WRITE : 0));
178 unsigned char* start = static_cast<unsigned char*>(
179 mmap(options_.address, mapLength_, prot, flags, file_.fd(), offset));
180 PCHECK(start != MAP_FAILED)
181 << " offset=" << offset
182 << " length=" << mapLength_;
184 data_.reset(start + skipStart, length);
190 off_t memOpChunkSize(off_t length, off_t pageSize) {
191 off_t chunkSize = length;
192 if (FLAGS_mlock_chunk_size <= 0) {
196 chunkSize = FLAGS_mlock_chunk_size;
197 off_t r = chunkSize % pageSize;
199 chunkSize += (pageSize - r);
205 * Run @op in chunks over the buffer @mem of @bufSize length.
208 * - success: true + amountSucceeded == bufSize (op success on whole buffer)
209 * - failure: false + amountSucceeded == nr bytes on which op succeeded.
211 bool memOpInChunks(std::function<int(void*, size_t)> op,
212 void* mem, size_t bufSize, off_t pageSize,
213 size_t& amountSucceeded) {
214 // unmap/mlock/munlock take a kernel semaphore and block other threads from
215 // doing other memory operations. If the size of the buffer is big the
216 // semaphore can be down for seconds (for benchmarks see
217 // http://kostja-osipov.livejournal.com/42963.html). Doing the operations in
218 // chunks breaks the locking into intervals and lets other threads do memory
219 // operations of their own.
221 size_t chunkSize = memOpChunkSize(bufSize, pageSize);
223 char* addr = static_cast<char*>(mem);
226 while (amountSucceeded < bufSize) {
227 size_t size = std::min(chunkSize, bufSize - amountSucceeded);
228 if (op(addr + amountSucceeded, size) != 0) {
231 amountSucceeded += size;
237 } // anonymous namespace
239 bool MemoryMapping::mlock(LockMode lock) {
240 size_t amountSucceeded = 0;
241 locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, options_.pageSize,
248 folly::sformat("mlock({}) failed at {}", mapLength_, amountSucceeded);
250 if (lock == LockMode::TRY_LOCK && (errno == EPERM || errno == ENOMEM)) {
251 PLOG(WARNING) << msg;
256 // only part of the buffer was mlocked, unlock it back
257 if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, options_.pageSize,
259 PLOG(WARNING) << "munlock()";
265 void MemoryMapping::munlock(bool dontneed) {
266 if (!locked_) return;
268 size_t amountSucceeded = 0;
269 if (!memOpInChunks(::munlock, mapStart_, mapLength_, options_.pageSize,
271 PLOG(WARNING) << "munlock()";
273 if (mapLength_ && dontneed &&
274 ::madvise(mapStart_, mapLength_, MADV_DONTNEED)) {
275 PLOG(WARNING) << "madvise()";
280 void MemoryMapping::hintLinearScan() {
281 advise(MADV_SEQUENTIAL);
284 MemoryMapping::~MemoryMapping() {
286 size_t amountSucceeded = 0;
287 if (!memOpInChunks(::munmap, mapStart_, mapLength_, options_.pageSize,
289 PLOG(FATAL) << folly::format("munmap({}) failed at {}",
290 mapLength_, amountSucceeded);
295 void MemoryMapping::advise(int advice) const { advise(advice, 0, mapLength_); }
297 void MemoryMapping::advise(int advice, size_t offset, size_t length) const {
298 CHECK_LE(offset + length, mapLength_)
299 << " offset: " << offset
300 << " length: " << length
301 << " mapLength_: " << mapLength_;
303 // Include the entire start page: round down to page boundary.
304 const auto offMisalign = offset % options_.pageSize;
305 offset -= offMisalign;
306 length += offMisalign;
308 // Round the last page down to page boundary.
309 if (offset + length != size_t(mapLength_)) {
310 length -= length % options_.pageSize;
317 char* mapStart = static_cast<char*>(mapStart_) + offset;
318 PLOG_IF(WARNING, ::madvise(mapStart, length, advice)) << "madvise";
321 MemoryMapping& MemoryMapping::operator=(MemoryMapping other) {
326 void MemoryMapping::swap(MemoryMapping& other) noexcept {
328 swap(this->file_, other.file_);
329 swap(this->mapStart_, other.mapStart_);
330 swap(this->mapLength_, other.mapLength_);
331 swap(this->options_, other.options_);
332 swap(this->locked_, other.locked_);
333 swap(this->data_, other.data_);
336 void swap(MemoryMapping& a, MemoryMapping& b) noexcept { a.swap(b); }
338 void alignedForwardMemcpy(void* dst, const void* src, size_t size) {
339 assert(reinterpret_cast<uintptr_t>(src) % alignof(unsigned long) == 0);
340 assert(reinterpret_cast<uintptr_t>(dst) % alignof(unsigned long) == 0);
342 auto srcl = static_cast<const unsigned long*>(src);
343 auto dstl = static_cast<unsigned long*>(dst);
345 while (size >= sizeof(unsigned long)) {
347 size -= sizeof(unsigned long);
350 auto srcc = reinterpret_cast<const unsigned char*>(srcl);
351 auto dstc = reinterpret_cast<unsigned char*>(dstl);
359 void mmapFileCopy(const char* src, const char* dest, mode_t mode) {
360 MemoryMapping srcMap(src);
361 srcMap.hintLinearScan();
363 MemoryMapping destMap(
364 File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
366 srcMap.range().size(),
367 MemoryMapping::writable());
369 alignedForwardMemcpy(destMap.writableRange().data(),
370 srcMap.range().data(),
371 srcMap.range().size());