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>
25 DEFINE_int64(mlock_chunk_size, 1 << 20, // 1MB
26 "Maximum bytes to mlock/munlock/munmap at once "
27 "(will be rounded up to PAGESIZE)");
31 /* protected constructor */
32 MemoryMapping::MemoryMapping()
38 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length)
43 init(std::move(file), offset, length, PROT_READ, false);
46 void MemoryMapping::init(File file,
47 off_t offset, off_t length,
50 off_t pageSize = sysconf(_SC_PAGESIZE);
53 // Round down the start of the mapped region
54 size_t skipStart = offset % pageSize;
57 file_ = std::move(file);
59 if (mapLength_ != -1) {
60 mapLength_ += skipStart;
62 // Round up the end of the mapped region
63 mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
68 CHECK_ERR(fstat(file_.fd(), &st));
69 off_t remaining = st.st_size - offset;
70 if (mapLength_ == -1) {
71 length = mapLength_ = remaining;
73 if (length > remaining) {
75 PCHECK(0 == ftruncate(file_.fd(), offset + length))
76 << "ftructate() failed, couldn't grow file";
82 if (mapLength_ > remaining) mapLength_ = remaining;
89 unsigned char* start = static_cast<unsigned char*>(
90 mmap(nullptr, mapLength_, prot, MAP_SHARED, file_.fd(), offset));
91 PCHECK(start != MAP_FAILED)
92 << " offset=" << offset
93 << " length=" << mapLength_;
95 data_.reset(start + skipStart, length);
101 off_t memOpChunkSize(off_t length) {
102 off_t chunkSize = length;
103 if (FLAGS_mlock_chunk_size <= 0) {
107 chunkSize = FLAGS_mlock_chunk_size;
108 off_t pageSize = sysconf(_SC_PAGESIZE);
109 off_t r = chunkSize % pageSize;
111 chunkSize += (pageSize - r);
117 * Run @op in chunks over the buffer @mem of @bufSize length.
120 * - success: true + amountSucceeded == bufSize (op success on whole buffer)
121 * - failure: false + amountSucceeded == nr bytes on which op succeeded.
123 bool memOpInChunks(std::function<int(void*, size_t)> op,
124 void* mem, size_t bufSize,
125 size_t& amountSucceeded) {
126 // unmap/mlock/munlock take a kernel semaphore and block other threads from
127 // doing other memory operations. If the size of the buffer is big the
128 // semaphore can be down for seconds (for benchmarks see
129 // http://kostja-osipov.livejournal.com/42963.html). Doing the operations in
130 // chunks breaks the locking into intervals and lets other threads do memory
131 // operations of their own.
133 size_t chunkSize = memOpChunkSize(bufSize);
134 size_t chunkCount = bufSize / chunkSize;
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);