Merge #11221: Refactor: simpler read
[bitcoinplatinum.git] / src / cuckoocache.h
blob947e1a7185fb0ad992bb492c4eb2ffd0d60657d3
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.
5 #ifndef BITCOIN_CUCKOOCACHE_H
6 #define BITCOIN_CUCKOOCACHE_H
8 #include <array>
9 #include <algorithm>
10 #include <atomic>
11 #include <cstring>
12 #include <cmath>
13 #include <memory>
14 #include <vector>
17 /** namespace CuckooCache provides high performance cache primitives
19 * Summary:
21 * 1) bit_packed_atomic_flags is bit-packed atomic flags for garbage collection
23 * 2) cache is a cache which is performant in memory usage and lookup speed. It
24 * is lockfree for erase operations. Elements are lazily erased on the next
25 * insert.
27 namespace CuckooCache
29 /** bit_packed_atomic_flags implements a container for garbage collection flags
30 * that is only thread unsafe on calls to setup. This class bit-packs collection
31 * flags for memory efficiency.
33 * All operations are std::memory_order_relaxed so external mechanisms must
34 * ensure that writes and reads are properly synchronized.
36 * On setup(n), all bits up to n are marked as collected.
38 * Under the hood, because it is an 8-bit type, it makes sense to use a multiple
39 * of 8 for setup, but it will be safe if that is not the case as well.
42 class bit_packed_atomic_flags
44 std::unique_ptr<std::atomic<uint8_t>[]> mem;
46 public:
47 /** No default constructor as there must be some size */
48 bit_packed_atomic_flags() = delete;
50 /**
51 * bit_packed_atomic_flags constructor creates memory to sufficiently
52 * keep track of garbage collection information for size entries.
54 * @param size the number of elements to allocate space for
56 * @post bit_set, bit_unset, and bit_is_set function properly forall x. x <
57 * size
58 * @post All calls to bit_is_set (without subsequent bit_unset) will return
59 * true.
61 explicit bit_packed_atomic_flags(uint32_t size)
63 // pad out the size if needed
64 size = (size + 7) / 8;
65 mem.reset(new std::atomic<uint8_t>[size]);
66 for (uint32_t i = 0; i < size; ++i)
67 mem[i].store(0xFF);
70 /** setup marks all entries and ensures that bit_packed_atomic_flags can store
71 * at least size entries
73 * @param b the number of elements to allocate space for
74 * @post bit_set, bit_unset, and bit_is_set function properly forall x. x <
75 * b
76 * @post All calls to bit_is_set (without subsequent bit_unset) will return
77 * true.
79 inline void setup(uint32_t b)
81 bit_packed_atomic_flags d(b);
82 std::swap(mem, d.mem);
85 /** bit_set sets an entry as discardable.
87 * @param s the index of the entry to bit_set.
88 * @post immediately subsequent call (assuming proper external memory
89 * ordering) to bit_is_set(s) == true.
92 inline void bit_set(uint32_t s)
94 mem[s >> 3].fetch_or(1 << (s & 7), std::memory_order_relaxed);
97 /** bit_unset marks an entry as something that should not be overwritten
99 * @param s the index of the entry to bit_unset.
100 * @post immediately subsequent call (assuming proper external memory
101 * ordering) to bit_is_set(s) == false.
103 inline void bit_unset(uint32_t s)
105 mem[s >> 3].fetch_and(~(1 << (s & 7)), std::memory_order_relaxed);
108 /** bit_is_set queries the table for discardability at s
110 * @param s the index of the entry to read.
111 * @returns if the bit at index s was set.
112 * */
113 inline bool bit_is_set(uint32_t s) const
115 return (1 << (s & 7)) & mem[s >> 3].load(std::memory_order_relaxed);
119 /** cache implements a cache with properties similar to a cuckoo-set
121 * The cache is able to hold up to (~(uint32_t)0) - 1 elements.
123 * Read Operations:
124 * - contains(*, false)
126 * Read+Erase Operations:
127 * - contains(*, true)
129 * Erase Operations:
130 * - allow_erase()
132 * Write Operations:
133 * - setup()
134 * - setup_bytes()
135 * - insert()
136 * - please_keep()
138 * Synchronization Free Operations:
139 * - invalid()
140 * - compute_hashes()
142 * User Must Guarantee:
144 * 1) Write Requires synchronized access (e.g., a lock)
145 * 2) Read Requires no concurrent Write, synchronized with the last insert.
146 * 3) Erase requires no concurrent Write, synchronized with last insert.
147 * 4) An Erase caller must release all memory before allowing a new Writer.
150 * Note on function names:
151 * - The name "allow_erase" is used because the real discard happens later.
152 * - The name "please_keep" is used because elements may be erased anyways on insert.
154 * @tparam Element should be a movable and copyable type
155 * @tparam Hash should be a function/callable which takes a template parameter
156 * hash_select and an Element and extracts a hash from it. Should return
157 * high-entropy uint32_t hashes for `Hash h; h<0>(e) ... h<7>(e)`.
159 template <typename Element, typename Hash>
160 class cache
162 private:
163 /** table stores all the elements */
164 std::vector<Element> table;
166 /** size stores the total available slots in the hash table */
167 uint32_t size;
169 /** The bit_packed_atomic_flags array is marked mutable because we want
170 * garbage collection to be allowed to occur from const methods */
171 mutable bit_packed_atomic_flags collection_flags;
173 /** epoch_flags tracks how recently an element was inserted into
174 * the cache. true denotes recent, false denotes not-recent. See insert()
175 * method for full semantics.
177 mutable std::vector<bool> epoch_flags;
179 /** epoch_heuristic_counter is used to determine when an epoch might be aged
180 * & an expensive scan should be done. epoch_heuristic_counter is
181 * decremented on insert and reset to the new number of inserts which would
182 * cause the epoch to reach epoch_size when it reaches zero.
184 uint32_t epoch_heuristic_counter;
186 /** epoch_size is set to be the number of elements supposed to be in a
187 * epoch. When the number of non-erased elements in an epoch
188 * exceeds epoch_size, a new epoch should be started and all
189 * current entries demoted. epoch_size is set to be 45% of size because
190 * we want to keep load around 90%, and we support 3 epochs at once --
191 * one "dead" which has been erased, one "dying" which has been marked to be
192 * erased next, and one "living" which new inserts add to.
194 uint32_t epoch_size;
196 /** depth_limit determines how many elements insert should try to replace.
197 * Should be set to log2(n)*/
198 uint8_t depth_limit;
200 /** hash_function is a const instance of the hash function. It cannot be
201 * static or initialized at call time as it may have internal state (such as
202 * a nonce).
203 * */
204 const Hash hash_function;
206 /** compute_hashes is convenience for not having to write out this
207 * expression everywhere we use the hash values of an Element.
209 * We need to map the 32-bit input hash onto a hash bucket in a range [0, size) in a
210 * manner which preserves as much of the hash's uniformity as possible. Ideally
211 * this would be done by bitmasking but the size is usually not a power of two.
213 * The naive approach would be to use a mod -- which isn't perfectly uniform but so
214 * long as the hash is much larger than size it is not that bad. Unfortunately,
215 * mod/division is fairly slow on ordinary microprocessors (e.g. 90-ish cycles on
216 * haswell, ARM doesn't even have an instruction for it.); when the divisor is a
217 * constant the compiler will do clever tricks to turn it into a multiply+add+shift,
218 * but size is a run-time value so the compiler can't do that here.
220 * One option would be to implement the same trick the compiler uses and compute the
221 * constants for exact division based on the size, as described in "{N}-bit Unsigned
222 * Division via {N}-bit Multiply-Add" by Arch D. Robison in 2005. But that code is
223 * somewhat complicated and the result is still slower than other options:
225 * Instead we treat the 32-bit random number as a Q32 fixed-point number in the range
226 * [0,1) and simply multiply it by the size. Then we just shift the result down by
227 * 32-bits to get our bucket number. The results has non-uniformity the same as a
228 * mod, but it is much faster to compute. More about this technique can be found at
229 * http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
231 * The resulting non-uniformity is also more equally distributed which would be
232 * advantageous for something like linear probing, though it shouldn't matter
233 * one way or the other for a cuckoo table.
235 * The primary disadvantage of this approach is increased intermediate precision is
236 * required but for a 32-bit random number we only need the high 32 bits of a
237 * 32*32->64 multiply, which means the operation is reasonably fast even on a
238 * typical 32-bit processor.
240 * @param e the element whose hashes will be returned
241 * @returns std::array<uint32_t, 8> of deterministic hashes derived from e
243 inline std::array<uint32_t, 8> compute_hashes(const Element& e) const
245 return {{(uint32_t)((hash_function.template operator()<0>(e) * (uint64_t)size) >> 32),
246 (uint32_t)((hash_function.template operator()<1>(e) * (uint64_t)size) >> 32),
247 (uint32_t)((hash_function.template operator()<2>(e) * (uint64_t)size) >> 32),
248 (uint32_t)((hash_function.template operator()<3>(e) * (uint64_t)size) >> 32),
249 (uint32_t)((hash_function.template operator()<4>(e) * (uint64_t)size) >> 32),
250 (uint32_t)((hash_function.template operator()<5>(e) * (uint64_t)size) >> 32),
251 (uint32_t)((hash_function.template operator()<6>(e) * (uint64_t)size) >> 32),
252 (uint32_t)((hash_function.template operator()<7>(e) * (uint64_t)size) >> 32)}};
255 /* end
256 * @returns a constexpr index that can never be inserted to */
257 constexpr uint32_t invalid() const
259 return ~(uint32_t)0;
262 /** allow_erase marks the element at index n as discardable. Threadsafe
263 * without any concurrent insert.
264 * @param n the index to allow erasure of
266 inline void allow_erase(uint32_t n) const
268 collection_flags.bit_set(n);
271 /** please_keep marks the element at index n as an entry that should be kept.
272 * Threadsafe without any concurrent insert.
273 * @param n the index to prioritize keeping
275 inline void please_keep(uint32_t n) const
277 collection_flags.bit_unset(n);
280 /** epoch_check handles the changing of epochs for elements stored in the
281 * cache. epoch_check should be run before every insert.
283 * First, epoch_check decrements and checks the cheap heuristic, and then does
284 * a more expensive scan if the cheap heuristic runs out. If the expensive
285 * scan succeeds, the epochs are aged and old elements are allow_erased. The
286 * cheap heuristic is reset to retrigger after the worst case growth of the
287 * current epoch's elements would exceed the epoch_size.
289 void epoch_check()
291 if (epoch_heuristic_counter != 0) {
292 --epoch_heuristic_counter;
293 return;
295 // count the number of elements from the latest epoch which
296 // have not been erased.
297 uint32_t epoch_unused_count = 0;
298 for (uint32_t i = 0; i < size; ++i)
299 epoch_unused_count += epoch_flags[i] &&
300 !collection_flags.bit_is_set(i);
301 // If there are more non-deleted entries in the current epoch than the
302 // epoch size, then allow_erase on all elements in the old epoch (marked
303 // false) and move all elements in the current epoch to the old epoch
304 // but do not call allow_erase on their indices.
305 if (epoch_unused_count >= epoch_size) {
306 for (uint32_t i = 0; i < size; ++i)
307 if (epoch_flags[i])
308 epoch_flags[i] = false;
309 else
310 allow_erase(i);
311 epoch_heuristic_counter = epoch_size;
312 } else
313 // reset the epoch_heuristic_counter to next do a scan when worst
314 // case behavior (no intermittent erases) would exceed epoch size,
315 // with a reasonable minimum scan size.
316 // Ordinarily, we would have to sanity check std::min(epoch_size,
317 // epoch_unused_count), but we already know that `epoch_unused_count
318 // < epoch_size` in this branch
319 epoch_heuristic_counter = std::max(1u, std::max(epoch_size / 16,
320 epoch_size - epoch_unused_count));
323 public:
324 /** You must always construct a cache with some elements via a subsequent
325 * call to setup or setup_bytes, otherwise operations may segfault.
327 cache() : table(), size(), collection_flags(0), epoch_flags(),
328 epoch_heuristic_counter(), epoch_size(), depth_limit(0), hash_function()
332 /** setup initializes the container to store no more than new_size
333 * elements.
335 * setup should only be called once.
337 * @param new_size the desired number of elements to store
338 * @returns the maximum number of elements storable
340 uint32_t setup(uint32_t new_size)
342 // depth_limit must be at least one otherwise errors can occur.
343 depth_limit = static_cast<uint8_t>(std::log2(static_cast<float>(std::max((uint32_t)2, new_size))));
344 size = std::max<uint32_t>(2, new_size);
345 table.resize(size);
346 collection_flags.setup(size);
347 epoch_flags.resize(size);
348 // Set to 45% as described above
349 epoch_size = std::max((uint32_t)1, (45 * size) / 100);
350 // Initially set to wait for a whole epoch
351 epoch_heuristic_counter = epoch_size;
352 return size;
355 /** setup_bytes is a convenience function which accounts for internal memory
356 * usage when deciding how many elements to store. It isn't perfect because
357 * it doesn't account for any overhead (struct size, MallocUsage, collection
358 * and epoch flags). This was done to simplify selecting a power of two
359 * size. In the expected use case, an extra two bits per entry should be
360 * negligible compared to the size of the elements.
362 * @param bytes the approximate number of bytes to use for this data
363 * structure.
364 * @returns the maximum number of elements storable (see setup()
365 * documentation for more detail)
367 uint32_t setup_bytes(size_t bytes)
369 return setup(bytes/sizeof(Element));
372 /** insert loops at most depth_limit times trying to insert a hash
373 * at various locations in the table via a variant of the Cuckoo Algorithm
374 * with eight hash locations.
376 * It drops the last tried element if it runs out of depth before
377 * encountering an open slot.
379 * Thus
381 * insert(x);
382 * return contains(x, false);
384 * is not guaranteed to return true.
386 * @param e the element to insert
387 * @post one of the following: All previously inserted elements and e are
388 * now in the table, one previously inserted element is evicted from the
389 * table, the entry attempted to be inserted is evicted.
392 inline void insert(Element e)
394 epoch_check();
395 uint32_t last_loc = invalid();
396 bool last_epoch = true;
397 std::array<uint32_t, 8> locs = compute_hashes(e);
398 // Make sure we have not already inserted this element
399 // If we have, make sure that it does not get deleted
400 for (uint32_t loc : locs)
401 if (table[loc] == e) {
402 please_keep(loc);
403 epoch_flags[loc] = last_epoch;
404 return;
406 for (uint8_t depth = 0; depth < depth_limit; ++depth) {
407 // First try to insert to an empty slot, if one exists
408 for (uint32_t loc : locs) {
409 if (!collection_flags.bit_is_set(loc))
410 continue;
411 table[loc] = std::move(e);
412 please_keep(loc);
413 epoch_flags[loc] = last_epoch;
414 return;
416 /** Swap with the element at the location that was
417 * not the last one looked at. Example:
419 * 1) On first iteration, last_loc == invalid(), find returns last, so
420 * last_loc defaults to locs[0].
421 * 2) On further iterations, where last_loc == locs[k], last_loc will
422 * go to locs[k+1 % 8], i.e., next of the 8 indices wrapping around
423 * to 0 if needed.
425 * This prevents moving the element we just put in.
427 * The swap is not a move -- we must switch onto the evicted element
428 * for the next iteration.
430 last_loc = locs[(1 + (std::find(locs.begin(), locs.end(), last_loc) - locs.begin())) & 7];
431 std::swap(table[last_loc], e);
432 // Can't std::swap a std::vector<bool>::reference and a bool&.
433 bool epoch = last_epoch;
434 last_epoch = epoch_flags[last_loc];
435 epoch_flags[last_loc] = epoch;
437 // Recompute the locs -- unfortunately happens one too many times!
438 locs = compute_hashes(e);
442 /* contains iterates through the hash locations for a given element
443 * and checks to see if it is present.
445 * contains does not check garbage collected state (in other words,
446 * garbage is only collected when the space is needed), so:
448 * insert(x);
449 * if (contains(x, true))
450 * return contains(x, false);
451 * else
452 * return true;
454 * executed on a single thread will always return true!
456 * This is a great property for re-org performance for example.
458 * contains returns a bool set true if the element was found.
460 * @param e the element to check
461 * @param erase
463 * @post if erase is true and the element is found, then the garbage collect
464 * flag is set
465 * @returns true if the element is found, false otherwise
467 inline bool contains(const Element& e, const bool erase) const
469 std::array<uint32_t, 8> locs = compute_hashes(e);
470 for (uint32_t loc : locs)
471 if (table[loc] == e) {
472 if (erase)
473 allow_erase(loc);
474 return true;
476 return false;
479 } // namespace CuckooCache
481 #endif // BITCOIN_CUCKOOCACHE_H