Bitcoin Core  0.18.99
P2P Digital Currency
lockedpool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016-2018 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <support/lockedpool.h>
6 #include <support/cleanse.h>
7 
8 #if defined(HAVE_CONFIG_H)
10 #endif
11 
12 #ifdef WIN32
13 #define WIN32_LEAN_AND_MEAN 1
14 #ifndef NOMINMAX
15 #define NOMINMAX
16 #endif
17 #include <windows.h>
18 #else
19 #include <sys/mman.h> // for mmap
20 #include <sys/resource.h> // for getrlimit
21 #include <limits.h> // for PAGESIZE
22 #include <unistd.h> // for sysconf
23 #endif
24 
25 #include <algorithm>
26 
28 std::once_flag LockedPoolManager::init_flag;
29 
30 /*******************************************************************************/
31 // Utilities
32 //
34 static inline size_t align_up(size_t x, size_t align)
35 {
36  return (x + align - 1) & ~(align - 1);
37 }
38 
39 /*******************************************************************************/
40 // Implementation: Arena
41 
42 Arena::Arena(void *base_in, size_t size_in, size_t alignment_in):
43  base(static_cast<char*>(base_in)), end(static_cast<char*>(base_in) + size_in), alignment(alignment_in)
44 {
45  // Start with one free chunk that covers the entire arena
46  auto it = size_to_free_chunk.emplace(size_in, base);
47  chunks_free.emplace(base, it);
48  chunks_free_end.emplace(base + size_in, it);
49 }
50 
52 {
53 }
54 
55 void* Arena::alloc(size_t size)
56 {
57  // Round to next multiple of alignment
58  size = align_up(size, alignment);
59 
60  // Don't handle zero-sized chunks
61  if (size == 0)
62  return nullptr;
63 
64  // Pick a large enough free-chunk. Returns an iterator pointing to the first element that is not less than key.
65  // This allocation strategy is best-fit. According to "Dynamic Storage Allocation: A Survey and Critical Review",
66  // Wilson et. al. 1995, http://www.scs.stanford.edu/14wi-cs140/sched/readings/wilson.pdf, best-fit and first-fit
67  // policies seem to work well in practice.
68  auto size_ptr_it = size_to_free_chunk.lower_bound(size);
69  if (size_ptr_it == size_to_free_chunk.end())
70  return nullptr;
71 
72  // Create the used-chunk, taking its space from the end of the free-chunk
73  const size_t size_remaining = size_ptr_it->first - size;
74  auto allocated = chunks_used.emplace(size_ptr_it->second + size_remaining, size).first;
75  chunks_free_end.erase(size_ptr_it->second + size_ptr_it->first);
76  if (size_ptr_it->first == size) {
77  // whole chunk is used up
78  chunks_free.erase(size_ptr_it->second);
79  } else {
80  // still some memory left in the chunk
81  auto it_remaining = size_to_free_chunk.emplace(size_remaining, size_ptr_it->second);
82  chunks_free[size_ptr_it->second] = it_remaining;
83  chunks_free_end.emplace(size_ptr_it->second + size_remaining, it_remaining);
84  }
85  size_to_free_chunk.erase(size_ptr_it);
86 
87  return reinterpret_cast<void*>(allocated->first);
88 }
89 
90 void Arena::free(void *ptr)
91 {
92  // Freeing the nullptr pointer is OK.
93  if (ptr == nullptr) {
94  return;
95  }
96 
97  // Remove chunk from used map
98  auto i = chunks_used.find(static_cast<char*>(ptr));
99  if (i == chunks_used.end()) {
100  throw std::runtime_error("Arena: invalid or double free");
101  }
102  std::pair<char*, size_t> freed = *i;
103  chunks_used.erase(i);
104 
105  // coalesce freed with previous chunk
106  auto prev = chunks_free_end.find(freed.first);
107  if (prev != chunks_free_end.end()) {
108  freed.first -= prev->second->first;
109  freed.second += prev->second->first;
110  size_to_free_chunk.erase(prev->second);
111  chunks_free_end.erase(prev);
112  }
113 
114  // coalesce freed with chunk after freed
115  auto next = chunks_free.find(freed.first + freed.second);
116  if (next != chunks_free.end()) {
117  freed.second += next->second->first;
118  size_to_free_chunk.erase(next->second);
119  chunks_free.erase(next);
120  }
121 
122  // Add/set space with coalesced free chunk
123  auto it = size_to_free_chunk.emplace(freed.second, freed.first);
124  chunks_free[freed.first] = it;
125  chunks_free_end[freed.first + freed.second] = it;
126 }
127 
129 {
130  Arena::Stats r{ 0, 0, 0, chunks_used.size(), chunks_free.size() };
131  for (const auto& chunk: chunks_used)
132  r.used += chunk.second;
133  for (const auto& chunk: chunks_free)
134  r.free += chunk.second->first;
135  r.total = r.used + r.free;
136  return r;
137 }
138 
139 #ifdef ARENA_DEBUG
140 static void printchunk(char* base, size_t sz, bool used) {
141  std::cout <<
142  "0x" << std::hex << std::setw(16) << std::setfill('0') << base <<
143  " 0x" << std::hex << std::setw(16) << std::setfill('0') << sz <<
144  " 0x" << used << std::endl;
145 }
146 void Arena::walk() const
147 {
148  for (const auto& chunk: chunks_used)
149  printchunk(chunk.first, chunk.second, true);
150  std::cout << std::endl;
151  for (const auto& chunk: chunks_free)
152  printchunk(chunk.first, chunk.second, false);
153  std::cout << std::endl;
154 }
155 #endif
156 
157 /*******************************************************************************/
158 // Implementation: Win32LockedPageAllocator
159 
160 #ifdef WIN32
161 
163 class Win32LockedPageAllocator: public LockedPageAllocator
164 {
165 public:
166  Win32LockedPageAllocator();
167  void* AllocateLocked(size_t len, bool *lockingSuccess) override;
168  void FreeLocked(void* addr, size_t len) override;
169  size_t GetLimit() override;
170 private:
171  size_t page_size;
172 };
173 
174 Win32LockedPageAllocator::Win32LockedPageAllocator()
175 {
176  // Determine system page size in bytes
177  SYSTEM_INFO sSysInfo;
178  GetSystemInfo(&sSysInfo);
179  page_size = sSysInfo.dwPageSize;
180 }
181 void *Win32LockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)
182 {
183  len = align_up(len, page_size);
184  void *addr = VirtualAlloc(nullptr, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
185  if (addr) {
186  // VirtualLock is used to attempt to keep keying material out of swap. Note
187  // that it does not provide this as a guarantee, but, in practice, memory
188  // that has been VirtualLock'd almost never gets written to the pagefile
189  // except in rare circumstances where memory is extremely low.
190  *lockingSuccess = VirtualLock(const_cast<void*>(addr), len) != 0;
191  }
192  return addr;
193 }
194 void Win32LockedPageAllocator::FreeLocked(void* addr, size_t len)
195 {
196  len = align_up(len, page_size);
197  memory_cleanse(addr, len);
198  VirtualUnlock(const_cast<void*>(addr), len);
199 }
200 
201 size_t Win32LockedPageAllocator::GetLimit()
202 {
203  // TODO is there a limit on Windows, how to get it?
204  return std::numeric_limits<size_t>::max();
205 }
206 #endif
207 
208 /*******************************************************************************/
209 // Implementation: PosixLockedPageAllocator
210 
211 #ifndef WIN32
212 
216 {
217 public:
219  void* AllocateLocked(size_t len, bool *lockingSuccess) override;
220  void FreeLocked(void* addr, size_t len) override;
221  size_t GetLimit() override;
222 private:
223  size_t page_size;
224 };
225 
227 {
228  // Determine system page size in bytes
229 #if defined(PAGESIZE) // defined in limits.h
230  page_size = PAGESIZE;
231 #else // assume some POSIX OS
232  page_size = sysconf(_SC_PAGESIZE);
233 #endif
234 }
235 
236 // Some systems (at least OS X) do not define MAP_ANONYMOUS yet and define
237 // MAP_ANON which is deprecated
238 #ifndef MAP_ANONYMOUS
239 #define MAP_ANONYMOUS MAP_ANON
240 #endif
241 
242 void *PosixLockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)
243 {
244  void *addr;
245  len = align_up(len, page_size);
246  addr = mmap(nullptr, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
247  if (addr == MAP_FAILED) {
248  return nullptr;
249  }
250  if (addr) {
251  *lockingSuccess = mlock(addr, len) == 0;
252  }
253  return addr;
254 }
255 void PosixLockedPageAllocator::FreeLocked(void* addr, size_t len)
256 {
257  len = align_up(len, page_size);
258  memory_cleanse(addr, len);
259  munlock(addr, len);
260  munmap(addr, len);
261 }
263 {
264 #ifdef RLIMIT_MEMLOCK
265  struct rlimit rlim;
266  if (getrlimit(RLIMIT_MEMLOCK, &rlim) == 0) {
267  if (rlim.rlim_cur != RLIM_INFINITY) {
268  return rlim.rlim_cur;
269  }
270  }
271 #endif
272  return std::numeric_limits<size_t>::max();
273 }
274 #endif
275 
276 /*******************************************************************************/
277 // Implementation: LockedPool
278 
279 LockedPool::LockedPool(std::unique_ptr<LockedPageAllocator> allocator_in, LockingFailed_Callback lf_cb_in):
280  allocator(std::move(allocator_in)), lf_cb(lf_cb_in), cumulative_bytes_locked(0)
281 {
282 }
283 
285 {
286 }
287 void* LockedPool::alloc(size_t size)
288 {
289  std::lock_guard<std::mutex> lock(mutex);
290 
291  // Don't handle impossible sizes
292  if (size == 0 || size > ARENA_SIZE)
293  return nullptr;
294 
295  // Try allocating from each current arena
296  for (auto &arena: arenas) {
297  void *addr = arena.alloc(size);
298  if (addr) {
299  return addr;
300  }
301  }
302  // If that fails, create a new one
304  return arenas.back().alloc(size);
305  }
306  return nullptr;
307 }
308 
309 void LockedPool::free(void *ptr)
310 {
311  std::lock_guard<std::mutex> lock(mutex);
312  // TODO we can do better than this linear search by keeping a map of arena
313  // extents to arena, and looking up the address.
314  for (auto &arena: arenas) {
315  if (arena.addressInArena(ptr)) {
316  arena.free(ptr);
317  return;
318  }
319  }
320  throw std::runtime_error("LockedPool: invalid address not pointing to any arena");
321 }
322 
324 {
325  std::lock_guard<std::mutex> lock(mutex);
326  LockedPool::Stats r{0, 0, 0, cumulative_bytes_locked, 0, 0};
327  for (const auto &arena: arenas) {
328  Arena::Stats i = arena.stats();
329  r.used += i.used;
330  r.free += i.free;
331  r.total += i.total;
332  r.chunks_used += i.chunks_used;
333  r.chunks_free += i.chunks_free;
334  }
335  return r;
336 }
337 
338 bool LockedPool::new_arena(size_t size, size_t align)
339 {
340  bool locked;
341  // If this is the first arena, handle this specially: Cap the upper size
342  // by the process limit. This makes sure that the first arena will at least
343  // be locked. An exception to this is if the process limit is 0:
344  // in this case no memory can be locked at all so we'll skip past this logic.
345  if (arenas.empty()) {
346  size_t limit = allocator->GetLimit();
347  if (limit > 0) {
348  size = std::min(size, limit);
349  }
350  }
351  void *addr = allocator->AllocateLocked(size, &locked);
352  if (!addr) {
353  return false;
354  }
355  if (locked) {
356  cumulative_bytes_locked += size;
357  } else if (lf_cb) { // Call the locking-failed callback if locking failed
358  if (!lf_cb()) { // If the callback returns false, free the memory and fail, otherwise consider the user warned and proceed.
359  allocator->FreeLocked(addr, size);
360  return false;
361  }
362  }
363  arenas.emplace_back(allocator.get(), addr, size, align);
364  return true;
365 }
366 
367 LockedPool::LockedPageArena::LockedPageArena(LockedPageAllocator *allocator_in, void *base_in, size_t size_in, size_t align_in):
368  Arena(base_in, size_in, align_in), base(base_in), size(size_in), allocator(allocator_in)
369 {
370 }
372 {
373  allocator->FreeLocked(base, size);
374 }
375 
376 /*******************************************************************************/
377 // Implementation: LockedPoolManager
378 //
379 LockedPoolManager::LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator_in):
380  LockedPool(std::move(allocator_in), &LockedPoolManager::LockingFailed)
381 {
382 }
383 
385 {
386  // TODO: log something but how? without including util.h
387  return true;
388 }
389 
391 {
392  // Using a local static instance guarantees that the object is initialized
393  // when it's first needed and also deinitialized after all objects that use
394  // it are done with it. I can think of one unlikely scenario where we may
395  // have a static deinitialization order/problem, but the check in
396  // LockedPoolManagerBase's destructor helps us detect if that ever happens.
397 #ifdef WIN32
398  std::unique_ptr<LockedPageAllocator> allocator(new Win32LockedPageAllocator());
399 #else
400  std::unique_ptr<LockedPageAllocator> allocator(new PosixLockedPageAllocator());
401 #endif
402  static LockedPoolManager instance(std::move(allocator));
403  LockedPoolManager::_instance = &instance;
404 }
size_t chunks_free
Definition: lockedpool.h:64
size_t chunks_used
Definition: lockedpool.h:63
static std::once_flag init_flag
Definition: lockedpool.h:237
size_t used
Definition: lockedpool.h:60
size_t alignment
Minimum chunk alignment.
Definition: lockedpool.h:110
std::mutex mutex
Mutex protects access to this pool&#39;s data structures, including arenas.
Definition: lockedpool.h:204
void * AllocateLocked(size_t len, bool *lockingSuccess) override
Allocate and lock memory pages.
Definition: lockedpool.cpp:242
std::list< LockedPageArena > arenas
Definition: lockedpool.h:199
static const size_t ARENA_ALIGN
Chunk alignment.
Definition: lockedpool.h:138
LockedPool(std::unique_ptr< LockedPageAllocator > allocator, LockingFailed_Callback lf_cb_in=nullptr)
Create a new LockedPool.
Definition: lockedpool.cpp:279
ChunkToSizeMap chunks_free
Map from begin of free chunk to its node in size_to_free_chunk.
Definition: lockedpool.h:98
LockingFailed_Callback lf_cb
Definition: lockedpool.h:200
size_t total
Definition: lockedpool.h:62
SizeToChunkSortedMap size_to_free_chunk
Map to enable O(log(n)) best-fit allocation, as it&#39;s sorted by size.
Definition: lockedpool.h:94
LockedPageArena(LockedPageAllocator *alloc_in, void *base_in, size_t size, size_t align)
Definition: lockedpool.cpp:367
std::unordered_map< char *, size_t > chunks_used
Map from begin of used chunk to its size.
Definition: lockedpool.h:103
OS-dependent allocation and deallocation of locked/pinned memory pages.
Definition: lockedpool.h:19
LockedPageAllocator * allocator
Definition: lockedpool.h:194
Singleton class to keep track of locked (ie, non-swappable) memory, for use in std::allocator templat...
Definition: lockedpool.h:218
void * alloc(size_t size)
Allocate size bytes from this arena.
Definition: lockedpool.cpp:55
void memory_cleanse(void *ptr, size_t len)
Definition: cleanse.cpp:31
void FreeLocked(void *addr, size_t len) override
Unlock and free memory pages.
Definition: lockedpool.cpp:255
Stats stats() const
Get arena usage statistics.
Definition: lockedpool.cpp:128
static LockedPoolManager * _instance
Definition: lockedpool.h:236
void * alloc(size_t size)
Allocate size bytes from this arena.
Definition: lockedpool.cpp:287
virtual ~Arena()
Definition: lockedpool.cpp:51
virtual void FreeLocked(void *addr, size_t len)=0
Unlock and free memory pages.
static const size_t ARENA_SIZE
Size of one arena of locked memory.
Definition: lockedpool.h:134
static bool LockingFailed()
Called when locking fails, warn the user here.
Definition: lockedpool.cpp:384
size_t free
Definition: lockedpool.h:61
Pool for locked memory chunks.
Definition: lockedpool.h:126
size_t GetLimit() override
Get the total limit on the amount of memory that may be locked by this process, in bytes...
Definition: lockedpool.cpp:262
void free(void *ptr)
Free a previously allocated chunk of memory.
Definition: lockedpool.cpp:90
void free(void *ptr)
Free a previously allocated chunk of memory.
Definition: lockedpool.cpp:309
char * base
Base address of arena.
Definition: lockedpool.h:106
LockedPageAllocator specialized for OSes that don&#39;t try to be special snowflakes. ...
Definition: lockedpool.cpp:215
bool new_arena(size_t size, size_t align)
Definition: lockedpool.cpp:338
Memory statistics.
Definition: lockedpool.h:58
LockedPoolManager(std::unique_ptr< LockedPageAllocator > allocator)
Definition: lockedpool.cpp:379
Stats stats() const
Get pool usage statistics.
Definition: lockedpool.cpp:323
static void CreateInstance()
Create a new LockedPoolManager specialized to the OS.
Definition: lockedpool.cpp:390
size_t cumulative_bytes_locked
Definition: lockedpool.h:201
Arena(void *base, size_t size, size_t alignment)
Definition: lockedpool.cpp:42
ChunkToSizeMap chunks_free_end
Map from end of free chunk to its node in size_to_free_chunk.
Definition: lockedpool.h:100
#define MAP_ANONYMOUS
Definition: lockedpool.cpp:239
std::unique_ptr< LockedPageAllocator > allocator
Definition: lockedpool.h:183
Memory statistics.
Definition: lockedpool.h:145