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