Add missing include
[folly.git] / folly / MemoryMapping.cpp
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "folly/MemoryMapping.h"
18 #include "folly/Format.h"
19
20 #include <fcntl.h>
21 #include <sys/mman.h>
22 #include <sys/types.h>
23 #include <system_error>
24 #include <gflags/gflags.h>
25
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)");
29
30 namespace folly {
31
32 /* protected constructor */
33 MemoryMapping::MemoryMapping()
34   : mapStart_(nullptr)
35   , mapLength_(0)
36   , locked_(false) {
37 }
38
39 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length)
40   : mapStart_(nullptr)
41   , mapLength_(0)
42   , locked_(false) {
43
44   init(std::move(file), offset, length, PROT_READ, false);
45 }
46
47 void MemoryMapping::init(File file,
48                          off_t offset, off_t length,
49                          int prot,
50                          bool grow) {
51   off_t pageSize = sysconf(_SC_PAGESIZE);
52   CHECK_GE(offset, 0);
53
54   // Round down the start of the mapped region
55   size_t skipStart = offset % pageSize;
56   offset -= skipStart;
57
58   file_ = std::move(file);
59   mapLength_ = length;
60   if (mapLength_ != -1) {
61     mapLength_ += skipStart;
62
63     // Round up the end of the mapped region
64     mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
65   }
66
67   // stat the file
68   struct stat st;
69   CHECK_ERR(fstat(file_.fd(), &st));
70   off_t remaining = st.st_size - offset;
71   if (mapLength_ == -1) {
72     length = mapLength_ = remaining;
73   } else {
74     if (length > remaining) {
75       if (grow) {
76         PCHECK(0 == ftruncate(file_.fd(), offset + length))
77           << "ftructate() failed, couldn't grow file";
78         remaining = length;
79       } else {
80         length = remaining;
81       }
82     }
83     if (mapLength_ > remaining) mapLength_ = remaining;
84   }
85
86   if (length == 0) {
87     mapLength_ = 0;
88     mapStart_ = nullptr;
89   } else {
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_;
95     mapStart_ = start;
96     data_.reset(start + skipStart, length);
97   }
98 }
99
100 namespace {
101
102 off_t memOpChunkSize(off_t length) {
103   off_t chunkSize = length;
104   if (FLAGS_mlock_chunk_size <= 0) {
105     return chunkSize;
106   }
107
108   chunkSize = FLAGS_mlock_chunk_size;
109   off_t pageSize = sysconf(_SC_PAGESIZE);
110   off_t r = chunkSize % pageSize;
111   if (r) {
112     chunkSize += (pageSize - r);
113   }
114   return chunkSize;
115 }
116
117 /**
118  * Run @op in chunks over the buffer @mem of @bufSize length.
119  *
120  * Return:
121  * - success: true + amountSucceeded == bufSize (op success on whole buffer)
122  * - failure: false + amountSucceeded == nr bytes on which op succeeded.
123  */
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.
133
134   size_t chunkSize = memOpChunkSize(bufSize);
135
136   char* addr = static_cast<char*>(mem);
137   amountSucceeded = 0;
138
139   while (amountSucceeded < bufSize) {
140     size_t size = std::min(chunkSize, bufSize - amountSucceeded);
141     if (op(addr + amountSucceeded, size) != 0) {
142       return false;
143     }
144     amountSucceeded += size;
145   }
146
147   return true;
148 }
149
150 }  // anonymous namespace
151
152 bool MemoryMapping::mlock(LockMode lock) {
153   size_t amountSucceeded = 0;
154   locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, amountSucceeded);
155   if (locked_) {
156     return true;
157   }
158
159   auto msg(folly::format(
160     "mlock({}) failed at {}",
161     mapLength_, amountSucceeded).str());
162
163   if (lock == LockMode::TRY_LOCK && (errno == EPERM || errno == ENOMEM)) {
164     PLOG(WARNING) << msg;
165   } else {
166     PLOG(FATAL) << msg;
167   }
168
169   // only part of the buffer was mlocked, unlock it back
170   if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, amountSucceeded)) {
171     PLOG(WARNING) << "munlock()";
172   }
173
174   return false;
175 }
176
177 void MemoryMapping::munlock(bool dontneed) {
178   if (!locked_) return;
179
180   size_t amountSucceeded = 0;
181   if (!memOpInChunks(::munlock, mapStart_, mapLength_, amountSucceeded)) {
182     PLOG(WARNING) << "munlock()";
183   }
184   if (mapLength_ && dontneed &&
185       ::madvise(mapStart_, mapLength_, MADV_DONTNEED)) {
186     PLOG(WARNING) << "madvise()";
187   }
188   locked_ = false;
189 }
190
191 void MemoryMapping::hintLinearScan() {
192   advise(MADV_SEQUENTIAL);
193 }
194
195 MemoryMapping::~MemoryMapping() {
196   if (mapLength_) {
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();
202     }
203   }
204 }
205
206 void MemoryMapping::advise(int advice) const {
207   if (mapLength_ && ::madvise(mapStart_, mapLength_, advice)) {
208     PLOG(WARNING) << "madvise()";
209   }
210 }
211
212 WritableMemoryMapping::WritableMemoryMapping(File file, off_t offset, off_t length) {
213   init(std::move(file), offset, length, PROT_READ | PROT_WRITE, true);
214 }
215
216 }  // namespace folly