Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

lockedpool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2016 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)
9 #include <config/dash-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 #include <memory>
31 
33 std::once_flag LockedPoolManager::init_flag;
34 
35 /*******************************************************************************/
36 // Utilities
37 //
39 static inline size_t align_up(size_t x, size_t align)
40 {
41  return (x + align - 1) & ~(align - 1);
42 }
43 
44 /*******************************************************************************/
45 // Implementation: Arena
46 
47 Arena::Arena(void *base_in, size_t size_in, size_t alignment_in):
48  base(static_cast<char*>(base_in)), end(static_cast<char*>(base_in) + size_in), alignment(alignment_in)
49 {
50  // Start with one free chunk that covers the entire arena
51  chunks_free.emplace(base, size_in);
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
68  auto it = std::find_if(chunks_free.begin(), chunks_free.end(),
69  [=](const std::map<char*, size_t>::value_type& chunk){ return chunk.second >= size; });
70  if (it == chunks_free.end())
71  return nullptr;
72 
73  // Create the used-chunk, taking its space from the end of the free-chunk
74  auto alloced = chunks_used.emplace(it->first + it->second - size, size).first;
75  if (!(it->second -= size))
76  chunks_free.erase(it);
77  return reinterpret_cast<void*>(alloced->first);
78 }
79 
80 /* extend the Iterator if other begins at its end */
81 template <class Iterator, class Pair> bool extend(Iterator it, const Pair& other) {
82  if (it->first + it->second == other.first) {
83  it->second += other.second;
84  return true;
85  }
86  return false;
87 }
88 
89 void Arena::free(void *ptr)
90 {
91  // Freeing the nullptr pointer is OK.
92  if (ptr == nullptr) {
93  return;
94  }
95 
96  // Remove chunk from used map
97  auto i = chunks_used.find(static_cast<char*>(ptr));
98  if (i == chunks_used.end()) {
99  throw std::runtime_error("Arena: invalid or double free");
100  }
101  auto freed = *i;
102  chunks_used.erase(i);
103 
104  // Add space to free map, coalescing contiguous chunks
105  auto next = chunks_free.upper_bound(freed.first);
106  auto prev = (next == chunks_free.begin()) ? chunks_free.end() : std::prev(next);
107  if (prev == chunks_free.end() || !extend(prev, freed))
108  prev = chunks_free.emplace_hint(next, freed);
109  if (next != chunks_free.end() && extend(prev, *next))
110  chunks_free.erase(next);
111 }
112 
114 {
115  Arena::Stats r{ 0, 0, 0, chunks_used.size(), chunks_free.size() };
116  for (const auto& chunk: chunks_used)
117  r.used += chunk.second;
118  for (const auto& chunk: chunks_free)
119  r.free += chunk.second;
120  r.total = r.used + r.free;
121  return r;
122 }
123 
124 #ifdef ARENA_DEBUG
125 void printchunk(char* base, size_t sz, bool used) {
126  std::cout <<
127  "0x" << std::hex << std::setw(16) << std::setfill('0') << base <<
128  " 0x" << std::hex << std::setw(16) << std::setfill('0') << sz <<
129  " 0x" << used << std::endl;
130 }
131 void Arena::walk() const
132 {
133  for (const auto& chunk: chunks_used)
134  printchunk(chunk.first, chunk.second, true);
135  std::cout << std::endl;
136  for (const auto& chunk: chunks_free)
137  printchunk(chunk.first, chunk.second, false);
138  std::cout << std::endl;
139 }
140 #endif
141 
142 /*******************************************************************************/
143 // Implementation: Win32LockedPageAllocator
144 
145 #ifdef WIN32
146 
148 class Win32LockedPageAllocator: public LockedPageAllocator
149 {
150 public:
151  Win32LockedPageAllocator();
152  void* AllocateLocked(size_t len, bool *lockingSuccess) override;
153  void FreeLocked(void* addr, size_t len) override;
154  size_t GetLimit() override;
155 private:
156  size_t page_size;
157 };
158 
159 Win32LockedPageAllocator::Win32LockedPageAllocator()
160 {
161  // Determine system page size in bytes
162  SYSTEM_INFO sSysInfo;
163  GetSystemInfo(&sSysInfo);
164  page_size = sSysInfo.dwPageSize;
165 }
166 void *Win32LockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)
167 {
168  len = align_up(len, page_size);
169  void *addr = VirtualAlloc(nullptr, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
170  if (addr) {
171  // VirtualLock is used to attempt to keep keying material out of swap. Note
172  // that it does not provide this as a guarantee, but, in practice, memory
173  // that has been VirtualLock'd almost never gets written to the pagefile
174  // except in rare circumstances where memory is extremely low.
175  *lockingSuccess = VirtualLock(const_cast<void*>(addr), len) != 0;
176  }
177  return addr;
178 }
179 void Win32LockedPageAllocator::FreeLocked(void* addr, size_t len)
180 {
181  len = align_up(len, page_size);
182  memory_cleanse(addr, len);
183  VirtualUnlock(const_cast<void*>(addr), len);
184 }
185 
186 size_t Win32LockedPageAllocator::GetLimit()
187 {
188  // TODO is there a limit on windows, how to get it?
189  return std::numeric_limits<size_t>::max();
190 }
191 #endif
192 
193 /*******************************************************************************/
194 // Implementation: PosixLockedPageAllocator
195 
196 #ifndef WIN32
197 
201 {
202 public:
204  void* AllocateLocked(size_t len, bool *lockingSuccess) override;
205  void FreeLocked(void* addr, size_t len) override;
206  size_t GetLimit() override;
207 private:
208  size_t page_size;
209 };
210 
212 {
213  // Determine system page size in bytes
214 #if defined(PAGESIZE) // defined in limits.h
215  page_size = PAGESIZE;
216 #else // assume some POSIX OS
217  page_size = sysconf(_SC_PAGESIZE);
218 #endif
219 }
220 
221 // Some systems (at least OS X) do not define MAP_ANONYMOUS yet and define
222 // MAP_ANON which is deprecated
223 #ifndef MAP_ANONYMOUS
224 #define MAP_ANONYMOUS MAP_ANON
225 #endif
226 
227 void *PosixLockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess)
228 {
229  void *addr;
230  len = align_up(len, page_size);
231  addr = mmap(nullptr, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
232  if (addr) {
233  *lockingSuccess = mlock(addr, len) == 0;
234  }
235  return addr;
236 }
237 void PosixLockedPageAllocator::FreeLocked(void* addr, size_t len)
238 {
239  len = align_up(len, page_size);
240  memory_cleanse(addr, len);
241  munlock(addr, len);
242  munmap(addr, len);
243 }
245 {
246 #ifdef RLIMIT_MEMLOCK
247  struct rlimit rlim;
248  if (getrlimit(RLIMIT_MEMLOCK, &rlim) == 0) {
249  if (rlim.rlim_cur != RLIM_INFINITY) {
250  return rlim.rlim_cur;
251  }
252  }
253 #endif
254  return std::numeric_limits<size_t>::max();
255 }
256 #endif
257 
258 /*******************************************************************************/
259 // Implementation: LockedPool
260 
261 LockedPool::LockedPool(std::unique_ptr<LockedPageAllocator> allocator_in, LockingFailed_Callback lf_cb_in):
262  allocator(std::move(allocator_in)), lf_cb(lf_cb_in), cumulative_bytes_locked(0)
263 {
264 }
265 
267 {
268 }
269 void* LockedPool::alloc(size_t size)
270 {
271  std::lock_guard<std::mutex> lock(mutex);
272 
273  // Don't handle impossible sizes
274  if (size == 0 || size > ARENA_SIZE)
275  return nullptr;
276 
277  // Try allocating from each current arena
278  for (auto &arena: arenas) {
279  void *addr = arena.alloc(size);
280  if (addr) {
281  return addr;
282  }
283  }
284  // If that fails, create a new one
286  return arenas.back().alloc(size);
287  }
288  return nullptr;
289 }
290 
291 void LockedPool::free(void *ptr)
292 {
293  std::lock_guard<std::mutex> lock(mutex);
294  // TODO we can do better than this linear search by keeping a map of arena
295  // extents to arena, and looking up the address.
296  for (auto &arena: arenas) {
297  if (arena.addressInArena(ptr)) {
298  arena.free(ptr);
299  return;
300  }
301  }
302  throw std::runtime_error("LockedPool: invalid address not pointing to any arena");
303 }
304 
306 {
307  std::lock_guard<std::mutex> lock(mutex);
308  LockedPool::Stats r{0, 0, 0, cumulative_bytes_locked, 0, 0};
309  for (const auto &arena: arenas) {
310  Arena::Stats i = arena.stats();
311  r.used += i.used;
312  r.free += i.free;
313  r.total += i.total;
314  r.chunks_used += i.chunks_used;
315  r.chunks_free += i.chunks_free;
316  }
317  return r;
318 }
319 
320 bool LockedPool::new_arena(size_t size, size_t align)
321 {
322  bool locked;
323  // If this is the first arena, handle this specially: Cap the upper size
324  // by the process limit. This makes sure that the first arena will at least
325  // be locked. An exception to this is if the process limit is 0:
326  // in this case no memory can be locked at all so we'll skip past this logic.
327  if (arenas.empty()) {
328  size_t limit = allocator->GetLimit();
329  if (limit > 0) {
330  size = std::min(size, limit);
331  }
332  }
333  void *addr = allocator->AllocateLocked(size, &locked);
334  if (!addr) {
335  return false;
336  }
337  if (locked) {
338  cumulative_bytes_locked += size;
339  } else if (lf_cb) { // Call the locking-failed callback if locking failed
340  if (!lf_cb()) { // If the callback returns false, free the memory and fail, otherwise consider the user warned and proceed.
341  allocator->FreeLocked(addr, size);
342  return false;
343  }
344  }
345  arenas.emplace_back(allocator.get(), addr, size, align);
346  return true;
347 }
348 
349 LockedPool::LockedPageArena::LockedPageArena(LockedPageAllocator *allocator_in, void *base_in, size_t size_in, size_t align_in):
350  Arena(base_in, size_in, align_in), base(base_in), size(size_in), allocator(allocator_in)
351 {
352 }
354 {
355  allocator->FreeLocked(base, size);
356 }
357 
358 /*******************************************************************************/
359 // Implementation: LockedPoolManager
360 //
361 LockedPoolManager::LockedPoolManager(std::unique_ptr<LockedPageAllocator> allocator_in):
362  LockedPool(std::move(allocator_in), &LockedPoolManager::LockingFailed)
363 {
364 }
365 
367 {
368  // TODO: log something but how? without including util.h
369  return true;
370 }
371 
373 {
374  // Using a local static instance guarantees that the object is initialized
375  // when it's first needed and also deinitialized after all objects that use
376  // it are done with it. I can think of one unlikely scenario where we may
377  // have a static deinitialization order/problem, but the check in
378  // LockedPoolManagerBase's destructor helps us detect if that ever happens.
379 #ifdef WIN32
380  std::unique_ptr<LockedPageAllocator> allocator(new Win32LockedPageAllocator());
381 #else
382  std::unique_ptr<LockedPageAllocator> allocator(new PosixLockedPageAllocator());
383 #endif
384  static LockedPoolManager instance(std::move(allocator));
385  LockedPoolManager::_instance = &instance;
386 }
size_t chunks_free
Definition: lockedpool.h:63
size_t chunks_used
Definition: lockedpool.h:62
static std::once_flag init_flag
Definition: lockedpool.h:228
size_t used
Definition: lockedpool.h:59
size_t alignment
Minimum chunk alignment.
Definition: lockedpool.h:101
std::mutex mutex
Mutex protects access to this pool&#39;s data structures, including arenas.
Definition: lockedpool.h:195
void * AllocateLocked(size_t len, bool *lockingSuccess) override
Allocate and lock memory pages.
Definition: lockedpool.cpp:227
std::list< LockedPageArena > arenas
Definition: lockedpool.h:190
static const size_t ARENA_ALIGN
Chunk alignment.
Definition: lockedpool.h:129
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:261
bool extend(Iterator it, const Pair &other)
Definition: lockedpool.cpp:81
LockingFailed_Callback lf_cb
Definition: lockedpool.h:191
size_t total
Definition: lockedpool.h:61
Definition: box.hpp:161
LockedPageArena(LockedPageAllocator *alloc_in, void *base_in, size_t size, size_t align)
Definition: lockedpool.cpp:349
OS-dependent allocation and deallocation of locked/pinned memory pages.
Definition: lockedpool.h:18
Singleton class to keep track of locked (ie, non-swappable) memory, for use in std::allocator templat...
Definition: lockedpool.h:209
void * alloc(size_t size)
Allocate size bytes from this arena.
Definition: lockedpool.cpp:58
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:237
Stats stats() const
Get arena usage statistics.
Definition: lockedpool.cpp:113
static LockedPoolManager * _instance
Definition: lockedpool.h:227
void * alloc(size_t size)
Allocate size bytes from this arena.
Definition: lockedpool.cpp:269
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:39
static const size_t ARENA_SIZE
Size of one arena of locked memory.
Definition: lockedpool.h:125
static std::pair< std::string, UniValue > Pair(const char *cKey, const char *cVal)
Definition: univalue.h:185
std::map< char *, size_t > chunks_used
Definition: lockedpool.h:95
static bool LockingFailed()
Called when locking fails, warn the user here.
Definition: lockedpool.cpp:366
size_t free
Definition: lockedpool.h:60
Pool for locked memory chunks.
Definition: lockedpool.h:117
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:244
void free(void *ptr)
Free a previously allocated chunk of memory.
Definition: lockedpool.cpp:89
void free(void *ptr)
Free a previously allocated chunk of memory.
Definition: lockedpool.cpp:291
char * base
Base address of arena.
Definition: lockedpool.h:97
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:200
bool new_arena(size_t size, size_t align)
Definition: lockedpool.cpp:320
Memory statistics.
Definition: lockedpool.h:57
LockedPoolManager(std::unique_ptr< LockedPageAllocator > allocator)
Definition: lockedpool.cpp:361
Stats stats() const
Get pool usage statistics.
Definition: lockedpool.cpp:305
static void CreateInstance()
Create a new LockedPoolManager specialized to the OS.
Definition: lockedpool.cpp:372
size_t cumulative_bytes_locked
Definition: lockedpool.h:192
std::map< char *, size_t > chunks_free
Map of chunk address to chunk information.
Definition: lockedpool.h:94
Arena(void *base, size_t size, size_t alignment)
Definition: lockedpool.cpp:47
#define MAP_ANONYMOUS
Definition: lockedpool.cpp:224
std::unique_ptr< LockedPageAllocator > allocator
Definition: lockedpool.h:174
Memory statistics.
Definition: lockedpool.h:136
Released under the MIT license