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