Make most implicit integer truncations and sign conversions explicit
[folly.git] / folly / MemoryMapping.cpp
1 /*
2  * Copyright 2017 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 #include <folly/portability/GFlags.h>
25 #include <folly/portability/SysMman.h>
26
27 #ifdef __linux__
28 #include <folly/experimental/io/HugePages.h>
29 #endif
30
31 #include <fcntl.h>
32 #include <sys/types.h>
33 #include <system_error>
34
35 static constexpr ssize_t kDefaultMlockChunkSize =
36 #ifndef _MSC_VER
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.
40     (1 << 20) // 1MB
41 #else // _MSC_VER
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.
44     (-1)
45 #endif // _MSC_VER
46     ;
47
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.");
51
52 #ifndef MAP_POPULATE
53 #define MAP_POPULATE 0
54 #endif
55
56 namespace folly {
57
58 MemoryMapping::MemoryMapping(MemoryMapping&& other) noexcept {
59   swap(other);
60 }
61
62 MemoryMapping::MemoryMapping(File file, off_t offset, off_t length,
63                              Options options)
64   : file_(std::move(file)),
65     options_(std::move(options)) {
66   CHECK(file_);
67   init(offset, length);
68 }
69
70 MemoryMapping::MemoryMapping(const char* name, off_t offset, off_t length,
71                              Options options)
72     : MemoryMapping(File(name, options.writable ? O_RDWR : O_RDONLY),
73                     offset,
74                     length,
75                     options) { }
76
77 MemoryMapping::MemoryMapping(int fd, off_t offset, off_t length,
78                              Options options)
79   : MemoryMapping(File(fd), offset, length, options) { }
80
81 MemoryMapping::MemoryMapping(AnonymousType, off_t length, Options options)
82   : options_(std::move(options)) {
83   init(0, length);
84 }
85
86 namespace {
87
88 #ifdef __linux__
89 void getDeviceOptions(dev_t device, off_t& pageSize, bool& autoExtend) {
90   auto ps = getHugePageSizeForDevice(device);
91   if (ps) {
92     pageSize = ps->size;
93     autoExtend = true;
94   }
95 }
96 #else
97 inline void getDeviceOptions(dev_t device, off_t& pageSize,
98                              bool& autoExtend) { }
99 #endif
100
101 }  // namespace
102
103 void MemoryMapping::init(off_t offset, off_t length) {
104   const bool grow = options_.grow;
105   const bool anon = !file_;
106   CHECK(!(grow && anon));
107
108   off_t& pageSize = options_.pageSize;
109
110   struct stat st;
111
112   // On Linux, hugetlbfs file systems don't require ftruncate() to grow the
113   // file, and (on kernels before 2.6.24) don't even allow it. Also, the file
114   // size is always a multiple of the page size.
115   bool autoExtend = false;
116
117   if (!anon) {
118     // Stat the file
119     CHECK_ERR(fstat(file_.fd(), &st));
120
121     if (pageSize == 0) {
122       getDeviceOptions(st.st_dev, pageSize, autoExtend);
123     }
124   } else {
125     DCHECK(!file_);
126     DCHECK_EQ(offset, 0);
127     CHECK_EQ(pageSize, 0);
128     CHECK_GE(length, 0);
129   }
130
131   if (pageSize == 0) {
132     pageSize = off_t(sysconf(_SC_PAGESIZE));
133   }
134
135   CHECK_GT(pageSize, 0);
136   CHECK_EQ(pageSize & (pageSize - 1), 0);  // power of two
137   CHECK_GE(offset, 0);
138
139   // Round down the start of the mapped region
140   off_t skipStart = offset % pageSize;
141   offset -= skipStart;
142
143   mapLength_ = length;
144   if (mapLength_ != -1) {
145     mapLength_ += skipStart;
146
147     // Round up the end of the mapped region
148     mapLength_ = (mapLength_ + pageSize - 1) / pageSize * pageSize;
149   }
150
151   off_t remaining = anon ? length : st.st_size - offset;
152
153   if (mapLength_ == -1) {
154     length = mapLength_ = remaining;
155   } else {
156     if (length > remaining) {
157       if (grow) {
158         if (!autoExtend) {
159           PCHECK(0 == ftruncate(file_.fd(), offset + length))
160             << "ftruncate() failed, couldn't grow file to "
161             << offset + length;
162           remaining = length;
163         } else {
164           // Extend mapping to multiple of page size, don't use ftruncate
165           remaining = mapLength_;
166         }
167       } else {
168         length = remaining;
169       }
170     }
171     if (mapLength_ > remaining) {
172       mapLength_ = remaining;
173     }
174   }
175
176   if (length == 0) {
177     mapLength_ = 0;
178     mapStart_ = nullptr;
179   } else {
180     int flags = options_.shared ? MAP_SHARED : MAP_PRIVATE;
181     if (anon) flags |= MAP_ANONYMOUS;
182     if (options_.prefault) flags |= MAP_POPULATE;
183
184     // The standard doesn't actually require PROT_NONE to be zero...
185     int prot = PROT_NONE;
186     if (options_.readable || options_.writable) {
187       prot = ((options_.readable ? PROT_READ : 0) |
188               (options_.writable ? PROT_WRITE : 0));
189     }
190
191     unsigned char* start = static_cast<unsigned char*>(mmap(
192         options_.address, size_t(mapLength_), prot, flags, file_.fd(), offset));
193     PCHECK(start != MAP_FAILED)
194       << " offset=" << offset
195       << " length=" << mapLength_;
196     mapStart_ = start;
197     data_.reset(start + skipStart, size_t(length));
198   }
199 }
200
201 namespace {
202
203 off_t memOpChunkSize(off_t length, off_t pageSize) {
204   off_t chunkSize = length;
205   if (FLAGS_mlock_chunk_size <= 0) {
206     return chunkSize;
207   }
208
209   chunkSize = off_t(FLAGS_mlock_chunk_size);
210   off_t r = chunkSize % pageSize;
211   if (r) {
212     chunkSize += (pageSize - r);
213   }
214   return chunkSize;
215 }
216
217 /**
218  * Run @op in chunks over the buffer @mem of @bufSize length.
219  *
220  * Return:
221  * - success: true + amountSucceeded == bufSize (op success on whole buffer)
222  * - failure: false + amountSucceeded == nr bytes on which op succeeded.
223  */
224 bool memOpInChunks(std::function<int(void*, size_t)> op,
225                    void* mem, size_t bufSize, off_t pageSize,
226                    size_t& amountSucceeded) {
227   // Linux' unmap/mlock/munlock take a kernel semaphore and block other threads
228   // from doing other memory operations. If the size of the buffer is big the
229   // semaphore can be down for seconds (for benchmarks see
230   // http://kostja-osipov.livejournal.com/42963.html).  Doing the operations in
231   // chunks breaks the locking into intervals and lets other threads do memory
232   // operations of their own.
233
234   size_t chunkSize = size_t(memOpChunkSize(off_t(bufSize), pageSize));
235
236   char* addr = static_cast<char*>(mem);
237   amountSucceeded = 0;
238
239   while (amountSucceeded < bufSize) {
240     size_t size = std::min(chunkSize, bufSize - amountSucceeded);
241     if (op(addr + amountSucceeded, size) != 0) {
242       return false;
243     }
244     amountSucceeded += size;
245   }
246
247   return true;
248 }
249
250 }  // anonymous namespace
251
252 bool MemoryMapping::mlock(LockMode lock) {
253   size_t amountSucceeded = 0;
254   locked_ = memOpInChunks(
255       ::mlock,
256       mapStart_,
257       size_t(mapLength_),
258       options_.pageSize,
259       amountSucceeded);
260   if (locked_) {
261     return true;
262   }
263
264   auto msg =
265       folly::format("mlock({}) failed at {}", mapLength_, amountSucceeded);
266   if (lock == LockMode::TRY_LOCK && errno == EPERM) {
267     PLOG(WARNING) << msg;
268   } else if (lock == LockMode::TRY_LOCK && errno == ENOMEM) {
269     VLOG(1) << msg;
270   } else {
271     PLOG(FATAL) << msg;
272   }
273
274   // only part of the buffer was mlocked, unlock it back
275   if (!memOpInChunks(::munlock, mapStart_, amountSucceeded, options_.pageSize,
276                      amountSucceeded)) {
277     PLOG(WARNING) << "munlock()";
278   }
279
280   return false;
281 }
282
283 void MemoryMapping::munlock(bool dontneed) {
284   if (!locked_) return;
285
286   size_t amountSucceeded = 0;
287   if (!memOpInChunks(
288           ::munlock,
289           mapStart_,
290           size_t(mapLength_),
291           options_.pageSize,
292           amountSucceeded)) {
293     PLOG(WARNING) << "munlock()";
294   }
295   if (mapLength_ && dontneed &&
296       ::madvise(mapStart_, size_t(mapLength_), MADV_DONTNEED)) {
297     PLOG(WARNING) << "madvise()";
298   }
299   locked_ = false;
300 }
301
302 void MemoryMapping::hintLinearScan() {
303   advise(MADV_SEQUENTIAL);
304 }
305
306 MemoryMapping::~MemoryMapping() {
307   if (mapLength_) {
308     size_t amountSucceeded = 0;
309     if (!memOpInChunks(
310             ::munmap,
311             mapStart_,
312             size_t(mapLength_),
313             options_.pageSize,
314             amountSucceeded)) {
315       PLOG(FATAL) << folly::format("munmap({}) failed at {}",
316                                    mapLength_, amountSucceeded);
317     }
318   }
319 }
320
321 void MemoryMapping::advise(int advice) const {
322   advise(advice, 0, size_t(mapLength_));
323 }
324
325 void MemoryMapping::advise(int advice, size_t offset, size_t length) const {
326   CHECK_LE(offset + length, size_t(mapLength_))
327     << " offset: " << offset
328     << " length: " << length
329     << " mapLength_: " << mapLength_;
330
331   // Include the entire start page: round down to page boundary.
332   const auto offMisalign = offset % options_.pageSize;
333   offset -= offMisalign;
334   length += offMisalign;
335
336   // Round the last page down to page boundary.
337   if (offset + length != size_t(mapLength_)) {
338     length -= length % options_.pageSize;
339   }
340
341   if (length == 0) {
342     return;
343   }
344
345   char* mapStart = static_cast<char*>(mapStart_) + offset;
346   PLOG_IF(WARNING, ::madvise(mapStart, length, advice)) << "madvise";
347 }
348
349 MemoryMapping& MemoryMapping::operator=(MemoryMapping other) {
350   swap(other);
351   return *this;
352 }
353
354 void MemoryMapping::swap(MemoryMapping& other) noexcept {
355   using std::swap;
356   swap(this->file_, other.file_);
357   swap(this->mapStart_, other.mapStart_);
358   swap(this->mapLength_, other.mapLength_);
359   swap(this->options_, other.options_);
360   swap(this->locked_, other.locked_);
361   swap(this->data_, other.data_);
362 }
363
364 void swap(MemoryMapping& a, MemoryMapping& b) noexcept { a.swap(b); }
365
366 void alignedForwardMemcpy(void* dst, const void* src, size_t size) {
367   assert(reinterpret_cast<uintptr_t>(src) % alignof(unsigned long) == 0);
368   assert(reinterpret_cast<uintptr_t>(dst) % alignof(unsigned long) == 0);
369
370   auto srcl = static_cast<const unsigned long*>(src);
371   auto dstl = static_cast<unsigned long*>(dst);
372
373   while (size >= sizeof(unsigned long)) {
374     *dstl++ = *srcl++;
375     size -= sizeof(unsigned long);
376   }
377
378   auto srcc = reinterpret_cast<const unsigned char*>(srcl);
379   auto dstc = reinterpret_cast<unsigned char*>(dstl);
380
381   while (size != 0) {
382     *dstc++ = *srcc++;
383     --size;
384   }
385 }
386
387 void mmapFileCopy(const char* src, const char* dest, mode_t mode) {
388   MemoryMapping srcMap(src);
389   srcMap.hintLinearScan();
390
391   MemoryMapping destMap(
392       File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
393       0,
394       off_t(srcMap.range().size()),
395       MemoryMapping::writable());
396
397   alignedForwardMemcpy(destMap.writableRange().data(),
398                        srcMap.range().data(),
399                        srcMap.range().size());
400 }
401
402 }  // namespace folly