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