2 * Copyright 2013 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"
22 #include <sys/types.h>
23 #include <system_error>
24 #include <gflags/gflags.h>
26 DEFINE_int64(mlock_chunk_size, 1 << 20, // 1MB
27 "Maximum bytes to mlock/munlock/munmap at once "
28 "(will be rounded up to PAGESIZE)");
32 /* protected constructor */
33 MemoryMapping::MemoryMapping()
39 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length)
44 init(std::move(file), offset, length, PROT_READ, false);
47 void MemoryMapping::init(File file,
48 off_t offset, off_t length,
51 off_t pageSize = sysconf(_SC_PAGESIZE);
54 // Round down the start of the mapped region
55 size_t skipStart = offset % pageSize;
58 file_ = std::move(file);
60 if (mapLength_ != -1) {
61 mapLength_ += skipStart;
63 // Round up the end of the mapped region
64 mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
69 CHECK_ERR(fstat(file_.fd(), &st));
70 off_t remaining = st.st_size - offset;
71 if (mapLength_ == -1) {
72 length = mapLength_ = remaining;
74 if (length > remaining) {
76 PCHECK(0 == ftruncate(file_.fd(), offset + length))
77 << "ftructate() failed, couldn't grow file";
83 if (mapLength_ > remaining) mapLength_ = remaining;
90 unsigned char* start = static_cast<unsigned char*>(
91 mmap(nullptr, mapLength_, prot, MAP_SHARED, file_.fd(), offset));
92 PCHECK(start != MAP_FAILED)
93 << " offset=" << offset
94 << " length=" << mapLength_;
96 data_.reset(start + skipStart, length);
102 off_t memOpChunkSize(off_t length) {
103 off_t chunkSize = length;
104 if (FLAGS_mlock_chunk_size <= 0) {
108 chunkSize = FLAGS_mlock_chunk_size;
109 off_t pageSize = sysconf(_SC_PAGESIZE);
110 off_t r = chunkSize % pageSize;
112 chunkSize += (pageSize - r);
118 * Run @op in chunks over the buffer @mem of @bufSize length.
121 * - success: true + amountSucceeded == bufSize (op success on whole buffer)
122 * - failure: false + amountSucceeded == nr bytes on which op succeeded.
124 bool memOpInChunks(std::function<int(void*, size_t)> op,
125 void* mem, size_t bufSize,
126 size_t& amountSucceeded) {
127 // unmap/mlock/munlock take a kernel semaphore and block other threads from
128 // doing other memory operations. If the size of the buffer is big the
129 // semaphore can be down for seconds (for benchmarks see
130 // http://kostja-osipov.livejournal.com/42963.html). Doing the operations in
131 // chunks breaks the locking into intervals and lets other threads do memory
132 // operations of their own.
134 size_t chunkSize = memOpChunkSize(bufSize);
136 char* addr = static_cast<char*>(mem);
139 while (amountSucceeded < bufSize) {
140 size_t size = std::min(chunkSize, bufSize - amountSucceeded);
141 if (op(addr + amountSucceeded, size) != 0) {
144 amountSucceeded += size;
150 } // anonymous namespace
152 bool MemoryMapping::mlock(LockMode lock) {
153 size_t amountSucceeded = 0;
154 locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, amountSucceeded);
159 auto msg(folly::format(
160 "mlock({}) failed at {}",
161 mapLength_, amountSucceeded).str());
163 if (lock == LockMode::TRY_LOCK && (errno == EPERM || errno == ENOMEM)) {
164 PLOG(WARNING) << msg;
169 // only part of the buffer was mlocked, unlock it back
170 if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, amountSucceeded)) {
171 PLOG(WARNING) << "munlock()";
177 void MemoryMapping::munlock(bool dontneed) {
178 if (!locked_) return;
180 size_t amountSucceeded = 0;
181 if (!memOpInChunks(::munlock, mapStart_, mapLength_, amountSucceeded)) {
182 PLOG(WARNING) << "munlock()";
184 if (mapLength_ && dontneed &&
185 ::madvise(mapStart_, mapLength_, MADV_DONTNEED)) {
186 PLOG(WARNING) << "madvise()";
191 void MemoryMapping::hintLinearScan() {
192 advise(MADV_SEQUENTIAL);
195 MemoryMapping::~MemoryMapping() {
197 size_t amountSucceeded = 0;
198 if (!memOpInChunks(::munmap, mapStart_, mapLength_, amountSucceeded)) {
199 PLOG(FATAL) << folly::format(
200 "munmap({}) failed at {}",
201 mapLength_, amountSucceeded).str();
206 void MemoryMapping::advise(int advice) const {
207 if (mapLength_ && ::madvise(mapStart_, mapLength_, advice)) {
208 PLOG(WARNING) << "madvise()";
212 WritableMemoryMapping::WritableMemoryMapping(File file, off_t offset, off_t length) {
213 init(std::move(file), offset, length, PROT_READ | PROT_WRITE, true);