2 * Copyright 2017 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>
24 #include <folly/portability/GFlags.h>
25 #include <folly/portability/SysMman.h>
28 #include <folly/experimental/io/HugePages.h>
32 #include <sys/types.h>
33 #include <system_error>
35 static constexpr ssize_t kDefaultMlockChunkSize =
37 // Linux implementations of unmap/mlock/munlock take a kernel
38 // semaphore and block other threads from doing other memory
39 // operations. Split the operations in chunks.
42 // MSVC doesn't have this problem, and calling munmap many times
43 // with the same address is a bad idea with the windows implementation.
48 DEFINE_int64(mlock_chunk_size, kDefaultMlockChunkSize,
49 "Maximum bytes to mlock/munlock/munmap at once "
50 "(will be rounded up to PAGESIZE). Ignored if negative.");
53 #define MAP_POPULATE 0
58 MemoryMapping::MemoryMapping(MemoryMapping&& other) noexcept {
62 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length,
64 : file_(std::move(file)),
65 options_(std::move(options)) {
70 MemoryMapping::MemoryMapping(const char* name, off_t offset, off_t length,
72 : MemoryMapping(File(name, options.writable ? O_RDWR : O_RDONLY),
77 MemoryMapping::MemoryMapping(int fd, off_t offset, off_t length,
79 : MemoryMapping(File(fd), offset, length, options) { }
81 MemoryMapping::MemoryMapping(AnonymousType, off_t length, Options options)
82 : options_(std::move(options)) {
89 void getDeviceOptions(dev_t device, off_t& pageSize, bool& autoExtend) {
90 auto ps = getHugePageSizeForDevice(device);
97 inline void getDeviceOptions(dev_t, off_t&, bool&) {}
102 void MemoryMapping::init(off_t offset, off_t length) {
103 const bool grow = options_.grow;
104 const bool anon = !file_;
105 CHECK(!(grow && anon));
107 off_t& pageSize = options_.pageSize;
111 // On Linux, hugetlbfs file systems don't require ftruncate() to grow the
112 // file, and (on kernels before 2.6.24) don't even allow it. Also, the file
113 // size is always a multiple of the page size.
114 bool autoExtend = false;
118 CHECK_ERR(fstat(file_.fd(), &st));
121 getDeviceOptions(st.st_dev, pageSize, autoExtend);
125 DCHECK_EQ(offset, 0);
126 CHECK_EQ(pageSize, 0);
131 pageSize = off_t(sysconf(_SC_PAGESIZE));
134 CHECK_GT(pageSize, 0);
135 CHECK_EQ(pageSize & (pageSize - 1), 0); // power of two
138 // Round down the start of the mapped region
139 off_t skipStart = offset % pageSize;
143 if (mapLength_ != -1) {
144 mapLength_ += skipStart;
146 // Round up the end of the mapped region
147 mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
150 off_t remaining = anon ? length : st.st_size - offset;
152 if (mapLength_ == -1) {
153 length = mapLength_ = remaining;
155 if (length > remaining) {
158 PCHECK(0 == ftruncate(file_.fd(), offset + length))
159 << "ftruncate() failed, couldn't grow file to "
163 // Extend mapping to multiple of page size, don't use ftruncate
164 remaining = mapLength_;
170 if (mapLength_ > remaining) {
171 mapLength_ = remaining;
179 int flags = options_.shared ? MAP_SHARED : MAP_PRIVATE;
181 flags |= MAP_ANONYMOUS;
183 if (options_.prefault) {
184 flags |= MAP_POPULATE;
187 // The standard doesn't actually require PROT_NONE to be zero...
188 int prot = PROT_NONE;
189 if (options_.readable || options_.writable) {
190 prot = ((options_.readable ? PROT_READ : 0) |
191 (options_.writable ? PROT_WRITE : 0));
194 unsigned char* start = static_cast<unsigned char*>(mmap(
195 options_.address, size_t(mapLength_), prot, flags, file_.fd(), offset));
196 PCHECK(start != MAP_FAILED)
197 << " offset=" << offset
198 << " length=" << mapLength_;
200 data_.reset(start + skipStart, size_t(length));
206 off_t memOpChunkSize(off_t length, off_t pageSize) {
207 off_t chunkSize = length;
208 if (FLAGS_mlock_chunk_size <= 0) {
212 chunkSize = off_t(FLAGS_mlock_chunk_size);
213 off_t r = chunkSize % pageSize;
215 chunkSize += (pageSize - r);
221 * Run @op in chunks over the buffer @mem of @bufSize length.
224 * - success: true + amountSucceeded == bufSize (op success on whole buffer)
225 * - failure: false + amountSucceeded == nr bytes on which op succeeded.
227 bool memOpInChunks(std::function<int(void*, size_t)> op,
228 void* mem, size_t bufSize, off_t pageSize,
229 size_t& amountSucceeded) {
230 // Linux' unmap/mlock/munlock take a kernel semaphore and block other threads
231 // from doing other memory operations. If the size of the buffer is big the
232 // semaphore can be down for seconds (for benchmarks see
233 // http://kostja-osipov.livejournal.com/42963.html). Doing the operations in
234 // chunks breaks the locking into intervals and lets other threads do memory
235 // operations of their own.
237 size_t chunkSize = size_t(memOpChunkSize(off_t(bufSize), pageSize));
239 char* addr = static_cast<char*>(mem);
242 while (amountSucceeded < bufSize) {
243 size_t size = std::min(chunkSize, bufSize - amountSucceeded);
244 if (op(addr + amountSucceeded, size) != 0) {
247 amountSucceeded += size;
255 bool MemoryMapping::mlock(LockMode lock) {
256 size_t amountSucceeded = 0;
257 locked_ = memOpInChunks(
268 folly::format("mlock({}) failed at {}", mapLength_, amountSucceeded);
269 if (lock == LockMode::TRY_LOCK && errno == EPERM) {
270 PLOG(WARNING) << msg;
271 } else if (lock == LockMode::TRY_LOCK && errno == ENOMEM) {
277 // only part of the buffer was mlocked, unlock it back
278 if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, options_.pageSize,
280 PLOG(WARNING) << "munlock()";
286 void MemoryMapping::munlock(bool dontneed) {
291 size_t amountSucceeded = 0;
298 PLOG(WARNING) << "munlock()";
300 if (mapLength_ && dontneed &&
301 ::madvise(mapStart_, size_t(mapLength_), MADV_DONTNEED)) {
302 PLOG(WARNING) << "madvise()";
307 void MemoryMapping::hintLinearScan() {
308 advise(MADV_SEQUENTIAL);
311 MemoryMapping::~MemoryMapping() {
313 size_t amountSucceeded = 0;
320 PLOG(FATAL) << folly::format("munmap({}) failed at {}",
321 mapLength_, amountSucceeded);
326 void MemoryMapping::advise(int advice) const {
327 advise(advice, 0, size_t(mapLength_));
330 void MemoryMapping::advise(int advice, size_t offset, size_t length) const {
331 CHECK_LE(offset + length, size_t(mapLength_))
332 << " offset: " << offset
333 << " length: " << length
334 << " mapLength_: " << mapLength_;
336 // Include the entire start page: round down to page boundary.
337 const auto offMisalign = offset % options_.pageSize;
338 offset -= offMisalign;
339 length += offMisalign;
341 // Round the last page down to page boundary.
342 if (offset + length != size_t(mapLength_)) {
343 length -= length % options_.pageSize;
350 char* mapStart = static_cast<char*>(mapStart_) + offset;
351 PLOG_IF(WARNING, ::madvise(mapStart, length, advice)) << "madvise";
354 MemoryMapping& MemoryMapping::operator=(MemoryMapping other) {
359 void MemoryMapping::swap(MemoryMapping& other) noexcept {
361 swap(this->file_, other.file_);
362 swap(this->mapStart_, other.mapStart_);
363 swap(this->mapLength_, other.mapLength_);
364 swap(this->options_, other.options_);
365 swap(this->locked_, other.locked_);
366 swap(this->data_, other.data_);
369 void swap(MemoryMapping& a, MemoryMapping& b) noexcept { a.swap(b); }
371 void alignedForwardMemcpy(void* dst, const void* src, size_t size) {
372 assert(reinterpret_cast<uintptr_t>(src) % alignof(unsigned long) == 0);
373 assert(reinterpret_cast<uintptr_t>(dst) % alignof(unsigned long) == 0);
375 auto srcl = static_cast<const unsigned long*>(src);
376 auto dstl = static_cast<unsigned long*>(dst);
378 while (size >= sizeof(unsigned long)) {
380 size -= sizeof(unsigned long);
383 auto srcc = reinterpret_cast<const unsigned char*>(srcl);
384 auto dstc = reinterpret_cast<unsigned char*>(dstl);
392 void mmapFileCopy(const char* src, const char* dest, mode_t mode) {
393 MemoryMapping srcMap(src);
394 srcMap.hintLinearScan();
396 MemoryMapping destMap(
397 File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
399 off_t(srcMap.range().size()),
400 MemoryMapping::writable());
402 alignedForwardMemcpy(destMap.writableRange().data(),
403 srcMap.range().data(),
404 srcMap.range().size());