Adding a unit test for HHWheelTimer exercising the default timeout functionality.
[folly.git] / folly / MemoryMapping.cpp
1 /*
2  * Copyright 2015 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
19 #include <algorithm>
20 #include <functional>
21 #include <utility>
22
23 #include <folly/Format.h>
24
25 #ifdef __linux__
26 #include <folly/experimental/io/HugePages.h>
27 #endif
28
29 #include <fcntl.h>
30 #include <sys/mman.h>
31 #include <sys/types.h>
32 #include <system_error>
33 #include <gflags/gflags.h>
34
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)");
38
39 #ifndef MAP_POPULATE
40 #define MAP_POPULATE 0
41 #endif
42
43 namespace folly {
44
45 MemoryMapping::MemoryMapping(MemoryMapping&& other) noexcept {
46   swap(other);
47 }
48
49 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length,
50                              Options options)
51   : file_(std::move(file)),
52     options_(std::move(options)) {
53   CHECK(file_);
54   init(offset, length);
55 }
56
57 MemoryMapping::MemoryMapping(const char* name, off_t offset, off_t length,
58                              Options options)
59     : MemoryMapping(File(name, options.writable ? O_RDWR : O_RDONLY),
60                     offset,
61                     length,
62                     options) { }
63
64 MemoryMapping::MemoryMapping(int fd, off_t offset, off_t length,
65                              Options options)
66   : MemoryMapping(File(fd), offset, length, options) { }
67
68 MemoryMapping::MemoryMapping(AnonymousType, off_t length, Options options)
69   : options_(std::move(options)) {
70   init(0, length);
71 }
72
73 namespace {
74
75 #ifdef __linux__
76 void getDeviceOptions(dev_t device, off_t& pageSize, bool& autoExtend) {
77   auto ps = getHugePageSizeForDevice(device);
78   if (ps) {
79     pageSize = ps->size;
80     autoExtend = true;
81   }
82 }
83 #else
84 inline void getDeviceOptions(dev_t device, off_t& pageSize,
85                              bool& autoExtend) { }
86 #endif
87
88 }  // namespace
89
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));
94
95   off_t& pageSize = options_.pageSize;
96
97   struct stat st;
98
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;
103
104   if (!anon) {
105     // Stat the file
106     CHECK_ERR(fstat(file_.fd(), &st));
107
108     if (pageSize == 0) {
109       getDeviceOptions(st.st_dev, pageSize, autoExtend);
110     }
111   } else {
112     DCHECK(!file_);
113     DCHECK_EQ(offset, 0);
114     CHECK_EQ(pageSize, 0);
115     CHECK_GE(length, 0);
116   }
117
118   if (pageSize == 0) {
119     pageSize = sysconf(_SC_PAGESIZE);
120   }
121
122   CHECK_GT(pageSize, 0);
123   CHECK_EQ(pageSize & (pageSize - 1), 0);  // power of two
124   CHECK_GE(offset, 0);
125
126   // Round down the start of the mapped region
127   size_t skipStart = offset % pageSize;
128   offset -= skipStart;
129
130   mapLength_ = length;
131   if (mapLength_ != -1) {
132     mapLength_ += skipStart;
133
134     // Round up the end of the mapped region
135     mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
136   }
137
138   off_t remaining = anon ? length : st.st_size - offset;
139
140   if (mapLength_ == -1) {
141     length = mapLength_ = remaining;
142   } else {
143     if (length > remaining) {
144       if (grow) {
145         if (!autoExtend) {
146           PCHECK(0 == ftruncate(file_.fd(), offset + length))
147             << "ftruncate() failed, couldn't grow file to "
148             << offset + length;
149           remaining = length;
150         } else {
151           // Extend mapping to multiple of page size, don't use ftruncate
152           remaining = mapLength_;
153         }
154       } else {
155         length = remaining;
156       }
157     }
158     if (mapLength_ > remaining) {
159       mapLength_ = remaining;
160     }
161   }
162
163   if (length == 0) {
164     mapLength_ = 0;
165     mapStart_ = nullptr;
166   } else {
167     int flags = options_.shared ? MAP_SHARED : MAP_PRIVATE;
168     if (anon) flags |= MAP_ANONYMOUS;
169     if (options_.prefault) flags |= MAP_POPULATE;
170
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));
176     }
177
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_;
183     mapStart_ = start;
184     data_.reset(start + skipStart, length);
185   }
186 }
187
188 namespace {
189
190 off_t memOpChunkSize(off_t length, off_t pageSize) {
191   off_t chunkSize = length;
192   if (FLAGS_mlock_chunk_size <= 0) {
193     return chunkSize;
194   }
195
196   chunkSize = FLAGS_mlock_chunk_size;
197   off_t r = chunkSize % pageSize;
198   if (r) {
199     chunkSize += (pageSize - r);
200   }
201   return chunkSize;
202 }
203
204 /**
205  * Run @op in chunks over the buffer @mem of @bufSize length.
206  *
207  * Return:
208  * - success: true + amountSucceeded == bufSize (op success on whole buffer)
209  * - failure: false + amountSucceeded == nr bytes on which op succeeded.
210  */
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.
220
221   size_t chunkSize = memOpChunkSize(bufSize, pageSize);
222
223   char* addr = static_cast<char*>(mem);
224   amountSucceeded = 0;
225
226   while (amountSucceeded < bufSize) {
227     size_t size = std::min(chunkSize, bufSize - amountSucceeded);
228     if (op(addr + amountSucceeded, size) != 0) {
229       return false;
230     }
231     amountSucceeded += size;
232   }
233
234   return true;
235 }
236
237 }  // anonymous namespace
238
239 bool MemoryMapping::mlock(LockMode lock) {
240   size_t amountSucceeded = 0;
241   locked_ = memOpInChunks(::mlock, mapStart_, mapLength_, options_.pageSize,
242                           amountSucceeded);
243   if (locked_) {
244     return true;
245   }
246
247   auto msg =
248     folly::sformat("mlock({}) failed at {}", mapLength_, amountSucceeded);
249
250   if (lock == LockMode::TRY_LOCK && (errno == EPERM || errno == ENOMEM)) {
251     PLOG(WARNING) << msg;
252   } else {
253     PLOG(FATAL) << msg;
254   }
255
256   // only part of the buffer was mlocked, unlock it back
257   if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, options_.pageSize,
258                      amountSucceeded)) {
259     PLOG(WARNING) << "munlock()";
260   }
261
262   return false;
263 }
264
265 void MemoryMapping::munlock(bool dontneed) {
266   if (!locked_) return;
267
268   size_t amountSucceeded = 0;
269   if (!memOpInChunks(::munlock, mapStart_, mapLength_, options_.pageSize,
270                      amountSucceeded)) {
271     PLOG(WARNING) << "munlock()";
272   }
273   if (mapLength_ && dontneed &&
274       ::madvise(mapStart_, mapLength_, MADV_DONTNEED)) {
275     PLOG(WARNING) << "madvise()";
276   }
277   locked_ = false;
278 }
279
280 void MemoryMapping::hintLinearScan() {
281   advise(MADV_SEQUENTIAL);
282 }
283
284 MemoryMapping::~MemoryMapping() {
285   if (mapLength_) {
286     size_t amountSucceeded = 0;
287     if (!memOpInChunks(::munmap, mapStart_, mapLength_, options_.pageSize,
288                        amountSucceeded)) {
289       PLOG(FATAL) << folly::format("munmap({}) failed at {}",
290                                    mapLength_, amountSucceeded);
291     }
292   }
293 }
294
295 void MemoryMapping::advise(int advice) const { advise(advice, 0, mapLength_); }
296
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_;
302
303   // Include the entire start page: round down to page boundary.
304   const auto offMisalign = offset % options_.pageSize;
305   offset -= offMisalign;
306   length += offMisalign;
307
308   // Round the last page down to page boundary.
309   if (offset + length != size_t(mapLength_)) {
310     length -= length % options_.pageSize;
311   }
312
313   if (length == 0) {
314     return;
315   }
316
317   char* mapStart = static_cast<char*>(mapStart_) + offset;
318   PLOG_IF(WARNING, ::madvise(mapStart, length, advice)) << "madvise";
319 }
320
321 MemoryMapping& MemoryMapping::operator=(MemoryMapping other) {
322   swap(other);
323   return *this;
324 }
325
326 void MemoryMapping::swap(MemoryMapping& other) noexcept {
327   using std::swap;
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_);
334 }
335
336 void swap(MemoryMapping& a, MemoryMapping& b) noexcept { a.swap(b); }
337
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);
341
342   auto srcl = static_cast<const unsigned long*>(src);
343   auto dstl = static_cast<unsigned long*>(dst);
344
345   while (size >= sizeof(unsigned long)) {
346     *dstl++ = *srcl++;
347     size -= sizeof(unsigned long);
348   }
349
350   auto srcc = reinterpret_cast<const unsigned char*>(srcl);
351   auto dstc = reinterpret_cast<unsigned char*>(dstl);
352
353   while (size != 0) {
354     *dstc++ = *srcc++;
355     --size;
356   }
357 }
358
359 void mmapFileCopy(const char* src, const char* dest, mode_t mode) {
360   MemoryMapping srcMap(src);
361   srcMap.hintLinearScan();
362
363   MemoryMapping destMap(
364       File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
365       0,
366       srcMap.range().size(),
367       MemoryMapping::writable());
368
369   alignedForwardMemcpy(destMap.writableRange().data(),
370                        srcMap.range().data(),
371                        srcMap.range().size());
372 }
373
374 }  // namespace folly