Bitcoin Core 28.99.0
P2P Digital Currency
cuckoocache.h
Go to the documentation of this file.
1// Copyright (c) 2016 Jeremy Rubin
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_CUCKOOCACHE_H
6#define BITCOIN_CUCKOOCACHE_H
7
8#include <util/fastrange.h>
9
10#include <algorithm> // std::find
11#include <array>
12#include <atomic>
13#include <cmath>
14#include <cstring>
15#include <limits>
16#include <memory>
17#include <utility>
18#include <vector>
19
20
30namespace CuckooCache
31{
45{
46 std::unique_ptr<std::atomic<uint8_t>[]> mem;
47
48public:
51
63 explicit bit_packed_atomic_flags(uint32_t size)
64 {
65 // pad out the size if needed
66 size = (size + 7) / 8;
67 mem.reset(new std::atomic<uint8_t>[size]);
68 for (uint32_t i = 0; i < size; ++i)
69 mem[i].store(0xFF);
70 };
71
81 inline void setup(uint32_t b)
82 {
84 std::swap(mem, d.mem);
85 }
86
93 inline void bit_set(uint32_t s)
94 {
95 mem[s >> 3].fetch_or(uint8_t(1 << (s & 7)), std::memory_order_relaxed);
96 }
97
104 inline void bit_unset(uint32_t s)
105 {
106 mem[s >> 3].fetch_and(uint8_t(~(1 << (s & 7))), std::memory_order_relaxed);
107 }
108
114 inline bool bit_is_set(uint32_t s) const
115 {
116 return (1 << (s & 7)) & mem[s >> 3].load(std::memory_order_relaxed);
117 }
118};
119
160template <typename Element, typename Hash>
161class cache
162{
163private:
165 std::vector<Element> table;
166
168 uint32_t size{0};
169
173
178 mutable std::vector<bool> epoch_flags;
179
186
195 uint32_t epoch_size{0};
196
200 uint8_t depth_limit{0};
201
207
240 inline std::array<uint32_t, 8> compute_hashes(const Element& e) const
241 {
242 return {{FastRange32(hash_function.template operator()<0>(e), size),
243 FastRange32(hash_function.template operator()<1>(e), size),
244 FastRange32(hash_function.template operator()<2>(e), size),
245 FastRange32(hash_function.template operator()<3>(e), size),
246 FastRange32(hash_function.template operator()<4>(e), size),
247 FastRange32(hash_function.template operator()<5>(e), size),
248 FastRange32(hash_function.template operator()<6>(e), size),
249 FastRange32(hash_function.template operator()<7>(e), size)}};
250 }
251
254 constexpr uint32_t invalid() const
255 {
256 return ~(uint32_t)0;
257 }
258
263 inline void allow_erase(uint32_t n) const
264 {
266 }
267
272 inline void please_keep(uint32_t n) const
273 {
275 }
276
287 {
288 if (epoch_heuristic_counter != 0) {
290 return;
291 }
292 // count the number of elements from the latest epoch which
293 // have not been erased.
294 uint32_t epoch_unused_count = 0;
295 for (uint32_t i = 0; i < size; ++i)
296 epoch_unused_count += epoch_flags[i] &&
298 // If there are more non-deleted entries in the current epoch than the
299 // epoch size, then allow_erase on all elements in the old epoch (marked
300 // false) and move all elements in the current epoch to the old epoch
301 // but do not call allow_erase on their indices.
302 if (epoch_unused_count >= epoch_size) {
303 for (uint32_t i = 0; i < size; ++i)
304 if (epoch_flags[i])
305 epoch_flags[i] = false;
306 else
307 allow_erase(i);
309 } else
310 // reset the epoch_heuristic_counter to next do a scan when worst
311 // case behavior (no intermittent erases) would exceed epoch size,
312 // with a reasonable minimum scan size.
313 // Ordinarily, we would have to sanity check std::min(epoch_size,
314 // epoch_unused_count), but we already know that `epoch_unused_count
315 // < epoch_size` in this branch
316 epoch_heuristic_counter = std::max(1u, std::max(epoch_size / 16,
317 epoch_size - epoch_unused_count));
318 }
319
320public:
325 {
326 }
327
336 uint32_t setup(uint32_t new_size)
337 {
338 // depth_limit must be at least one otherwise errors can occur.
339 size = std::max<uint32_t>(2, new_size);
340 depth_limit = static_cast<uint8_t>(std::log2(static_cast<float>(size)));
341 table.resize(size);
343 epoch_flags.resize(size);
344 // Set to 45% as described above
345 epoch_size = std::max(uint32_t{1}, (45 * size) / 100);
346 // Initially set to wait for a whole epoch
348 return size;
349 }
350
364 std::pair<uint32_t, size_t> setup_bytes(size_t bytes)
365 {
366 uint32_t requested_num_elems(std::min<size_t>(
367 bytes / sizeof(Element),
368 std::numeric_limits<uint32_t>::max()));
369
370 auto num_elems = setup(requested_num_elems);
371
372 size_t approx_size_bytes = num_elems * sizeof(Element);
373 return std::make_pair(num_elems, approx_size_bytes);
374 }
375
397 inline void insert(Element e)
398 {
399 epoch_check();
400 uint32_t last_loc = invalid();
401 bool last_epoch = true;
402 std::array<uint32_t, 8> locs = compute_hashes(e);
403 // Make sure we have not already inserted this element
404 // If we have, make sure that it does not get deleted
405 for (const uint32_t loc : locs)
406 if (table[loc] == e) {
407 please_keep(loc);
408 epoch_flags[loc] = last_epoch;
409 return;
410 }
411 for (uint8_t depth = 0; depth < depth_limit; ++depth) {
412 // First try to insert to an empty slot, if one exists
413 for (const uint32_t loc : locs) {
415 continue;
416 table[loc] = std::move(e);
417 please_keep(loc);
418 epoch_flags[loc] = last_epoch;
419 return;
420 }
435 last_loc = locs[(1 + (std::find(locs.begin(), locs.end(), last_loc) - locs.begin())) & 7];
436 std::swap(table[last_loc], e);
437 // Can't std::swap a std::vector<bool>::reference and a bool&.
438 bool epoch = last_epoch;
439 last_epoch = epoch_flags[last_loc];
440 epoch_flags[last_loc] = epoch;
441
442 // Recompute the locs -- unfortunately happens one too many times!
443 locs = compute_hashes(e);
444 }
445 }
446
474 inline bool contains(const Element& e, const bool erase) const
475 {
476 std::array<uint32_t, 8> locs = compute_hashes(e);
477 for (const uint32_t loc : locs)
478 if (table[loc] == e) {
479 if (erase)
480 allow_erase(loc);
481 return true;
482 }
483 return false;
484 }
485};
486} // namespace CuckooCache
487
488#endif // BITCOIN_CUCKOOCACHE_H
bit_packed_atomic_flags implements a container for garbage collection flags that is only thread unsaf...
Definition: cuckoocache.h:45
void bit_set(uint32_t s)
bit_set sets an entry as discardable.
Definition: cuckoocache.h:93
void setup(uint32_t b)
setup marks all entries and ensures that bit_packed_atomic_flags can store at least b entries.
Definition: cuckoocache.h:81
bit_packed_atomic_flags()=delete
No default constructor, as there must be some size.
bool bit_is_set(uint32_t s) const
bit_is_set queries the table for discardability at s.
Definition: cuckoocache.h:114
void bit_unset(uint32_t s)
bit_unset marks an entry as something that should not be overwritten.
Definition: cuckoocache.h:104
bit_packed_atomic_flags(uint32_t size)
bit_packed_atomic_flags constructor creates memory to sufficiently keep track of garbage collection i...
Definition: cuckoocache.h:63
std::unique_ptr< std::atomic< uint8_t >[]> mem
Definition: cuckoocache.h:46
cache implements a cache with properties similar to a cuckoo-set.
Definition: cuckoocache.h:162
uint32_t size
size stores the total available slots in the hash table
Definition: cuckoocache.h:168
std::pair< uint32_t, size_t > setup_bytes(size_t bytes)
setup_bytes is a convenience function which accounts for internal memory usage when deciding how many...
Definition: cuckoocache.h:364
uint8_t depth_limit
depth_limit determines how many elements insert should try to replace.
Definition: cuckoocache.h:200
std::vector< Element > table
table stores all the elements
Definition: cuckoocache.h:165
uint32_t epoch_heuristic_counter
epoch_heuristic_counter is used to determine when an epoch might be aged & an expensive scan should b...
Definition: cuckoocache.h:185
uint32_t setup(uint32_t new_size)
setup initializes the container to store no more than new_size elements and no less than 2 elements.
Definition: cuckoocache.h:336
void epoch_check()
epoch_check handles the changing of epochs for elements stored in the cache.
Definition: cuckoocache.h:286
std::array< uint32_t, 8 > compute_hashes(const Element &e) const
compute_hashes is convenience for not having to write out this expression everywhere we use the hash ...
Definition: cuckoocache.h:240
uint32_t epoch_size
epoch_size is set to be the number of elements supposed to be in a epoch.
Definition: cuckoocache.h:195
std::vector< bool > epoch_flags
epoch_flags tracks how recently an element was inserted into the cache.
Definition: cuckoocache.h:178
void insert(Element e)
insert loops at most depth_limit times trying to insert a hash at various locations in the table via ...
Definition: cuckoocache.h:397
bit_packed_atomic_flags collection_flags
The bit_packed_atomic_flags array is marked mutable because we want garbage collection to be allowed ...
Definition: cuckoocache.h:172
constexpr uint32_t invalid() const
invalid returns a special index that can never be inserted to
Definition: cuckoocache.h:254
const Hash hash_function
hash_function is a const instance of the hash function.
Definition: cuckoocache.h:206
void allow_erase(uint32_t n) const
allow_erase marks the element at index n as discardable.
Definition: cuckoocache.h:263
bool contains(const Element &e, const bool erase) const
contains iterates through the hash locations for a given element and checks to see if it is present.
Definition: cuckoocache.h:474
void please_keep(uint32_t n) const
please_keep marks the element at index n as an entry that should be kept.
Definition: cuckoocache.h:272
cache()
You must always construct a cache with some elements via a subsequent call to setup or setup_bytes,...
Definition: cuckoocache.h:324
static uint32_t FastRange32(uint32_t x, uint32_t n)
Fast range reduction with 32-bit input and 32-bit range.
Definition: fastrange.h:19
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
Definition: hash.h:75
High-performance cache primitives.
Definition: cuckoocache.h:31