Branch data Line data Source code
# 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 <memory>
# 16 : : #include <utility>
# 17 : : #include <vector>
# 18 : :
# 19 : :
# 20 : : /** High-performance cache primitives.
# 21 : : *
# 22 : : * Summary:
# 23 : : *
# 24 : : * 1. @ref bit_packed_atomic_flags is bit-packed atomic flags for garbage collection
# 25 : : *
# 26 : : * 2. @ref cache is a cache which is performant in memory usage and lookup speed. It
# 27 : : * is lockfree for erase operations. Elements are lazily erased on the next insert.
# 28 : : */
# 29 : : namespace CuckooCache
# 30 : : {
# 31 : : /** @ref bit_packed_atomic_flags implements a container for garbage collection flags
# 32 : : * that is only thread unsafe on calls to setup. This class bit-packs collection
# 33 : : * flags for memory efficiency.
# 34 : : *
# 35 : : * All operations are `std::memory_order_relaxed` so external mechanisms must
# 36 : : * ensure that writes and reads are properly synchronized.
# 37 : : *
# 38 : : * On setup(n), all bits up to `n` are marked as collected.
# 39 : : *
# 40 : : * Under the hood, because it is an 8-bit type, it makes sense to use a multiple
# 41 : : * of 8 for setup, but it will be safe if that is not the case as well.
# 42 : : */
# 43 : : class bit_packed_atomic_flags
# 44 : : {
# 45 : : std::unique_ptr<std::atomic<uint8_t>[]> mem;
# 46 : :
# 47 : : public:
# 48 : : /** No default constructor, as there must be some size. */
# 49 : : bit_packed_atomic_flags() = delete;
# 50 : :
# 51 : : /**
# 52 : : * bit_packed_atomic_flags constructor creates memory to sufficiently
# 53 : : * keep track of garbage collection information for `size` entries.
# 54 : : *
# 55 : : * @param size the number of elements to allocate space for
# 56 : : *
# 57 : : * @post bit_set, bit_unset, and bit_is_set function properly forall x. x <
# 58 : : * size
# 59 : : * @post All calls to bit_is_set (without subsequent bit_unset) will return
# 60 : : * true.
# 61 : : */
# 62 : : explicit bit_packed_atomic_flags(uint32_t size)
# 63 : 4952 : {
# 64 : : // pad out the size if needed
# 65 : 4952 : size = (size + 7) / 8;
# 66 : 4952 : mem.reset(new std::atomic<uint8_t>[size]);
# 67 [ + + ]: 213947224 : for (uint32_t i = 0; i < size; ++i)
# 68 : 213942272 : mem[i].store(0xFF);
# 69 : 4952 : };
# 70 : :
# 71 : : /** setup marks all entries and ensures that bit_packed_atomic_flags can store
# 72 : : * at least `b` entries.
# 73 : : *
# 74 : : * @param b the number of elements to allocate space for
# 75 : : * @post bit_set, bit_unset, and bit_is_set function properly forall x. x <
# 76 : : * b
# 77 : : * @post All calls to bit_is_set (without subsequent bit_unset) will return
# 78 : : * true.
# 79 : : */
# 80 : : inline void setup(uint32_t b)
# 81 : 3278 : {
# 82 : 3278 : bit_packed_atomic_flags d(b);
# 83 : 3278 : std::swap(mem, d.mem);
# 84 : 3278 : }
# 85 : :
# 86 : : /** bit_set sets an entry as discardable.
# 87 : : *
# 88 : : * @param s the index of the entry to bit_set
# 89 : : * @post immediately subsequent call (assuming proper external memory
# 90 : : * ordering) to bit_is_set(s) == true.
# 91 : : */
# 92 : : inline void bit_set(uint32_t s)
# 93 : 4413412 : {
# 94 : 4413412 : mem[s >> 3].fetch_or(uint8_t(1 << (s & 7)), std::memory_order_relaxed);
# 95 : 4413412 : }
# 96 : :
# 97 : : /** bit_unset marks an entry as something that should not be overwritten.
# 98 : : *
# 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.
# 102 : : */
# 103 : : inline void bit_unset(uint32_t s)
# 104 : 4261170 : {
# 105 : 4261170 : mem[s >> 3].fetch_and(uint8_t(~(1 << (s & 7))), std::memory_order_relaxed);
# 106 : 4261170 : }
# 107 : :
# 108 : : /** bit_is_set queries the table for discardability at `s`.
# 109 : : *
# 110 : : * @param s the index of the entry to read
# 111 : : * @returns true if the bit at index `s` was set, false otherwise
# 112 : : * */
# 113 : : inline bool bit_is_set(uint32_t s) const
# 114 : 21795375 : {
# 115 : 21795375 : return (1 << (s & 7)) & mem[s >> 3].load(std::memory_order_relaxed);
# 116 : 21795375 : }
# 117 : : };
# 118 : :
# 119 : : /** @ref cache implements a cache with properties similar to a cuckoo-set.
# 120 : : *
# 121 : : * The cache is able to hold up to `(~(uint32_t)0) - 1` elements.
# 122 : : *
# 123 : : * Read Operations:
# 124 : : * - contains() for `erase=false`
# 125 : : *
# 126 : : * Read+Erase Operations:
# 127 : : * - contains() for `erase=true`
# 128 : : *
# 129 : : * Erase Operations:
# 130 : : * - allow_erase()
# 131 : : *
# 132 : : * Write Operations:
# 133 : : * - setup()
# 134 : : * - setup_bytes()
# 135 : : * - insert()
# 136 : : * - please_keep()
# 137 : : *
# 138 : : * Synchronization Free Operations:
# 139 : : * - invalid()
# 140 : : * - compute_hashes()
# 141 : : *
# 142 : : * User Must Guarantee:
# 143 : : *
# 144 : : * 1. Write requires synchronized access (e.g. a lock)
# 145 : : * 2. Read requires no concurrent Write, synchronized with 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.
# 148 : : *
# 149 : : *
# 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.
# 153 : : *
# 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)`.
# 158 : : */
# 159 : : template <typename Element, typename Hash>
# 160 : : class cache
# 161 : : {
# 162 : : private:
# 163 : : /** table stores all the elements */
# 164 : : std::vector<Element> table;
# 165 : :
# 166 : : /** size stores the total available slots in the hash table */
# 167 : : uint32_t size;
# 168 : :
# 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;
# 172 : :
# 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.
# 176 : : */
# 177 : : mutable std::vector<bool> epoch_flags;
# 178 : :
# 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.
# 183 : : */
# 184 : : uint32_t epoch_heuristic_counter;
# 185 : :
# 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.
# 193 : : */
# 194 : : uint32_t epoch_size;
# 195 : :
# 196 : : /** depth_limit determines how many elements insert should try to replace.
# 197 : : * Should be set to log2(n).
# 198 : : */
# 199 : : uint8_t depth_limit;
# 200 : :
# 201 : : /** hash_function is a const instance of the hash function. It cannot be
# 202 : : * static or initialized at call time as it may have internal state (such as
# 203 : : * a nonce).
# 204 : : */
# 205 : : const Hash hash_function;
# 206 : :
# 207 : : /** compute_hashes is convenience for not having to write out this
# 208 : : * expression everywhere we use the hash values of an Element.
# 209 : : *
# 210 : : * We need to map the 32-bit input hash onto a hash bucket in a range [0, size) in a
# 211 : : * manner which preserves as much of the hash's uniformity as possible. Ideally
# 212 : : * this would be done by bitmasking but the size is usually not a power of two.
# 213 : : *
# 214 : : * The naive approach would be to use a mod -- which isn't perfectly uniform but so
# 215 : : * long as the hash is much larger than size it is not that bad. Unfortunately,
# 216 : : * mod/division is fairly slow on ordinary microprocessors (e.g. 90-ish cycles on
# 217 : : * haswell, ARM doesn't even have an instruction for it.); when the divisor is a
# 218 : : * constant the compiler will do clever tricks to turn it into a multiply+add+shift,
# 219 : : * but size is a run-time value so the compiler can't do that here.
# 220 : : *
# 221 : : * One option would be to implement the same trick the compiler uses and compute the
# 222 : : * constants for exact division based on the size, as described in "{N}-bit Unsigned
# 223 : : * Division via {N}-bit Multiply-Add" by Arch D. Robison in 2005. But that code is
# 224 : : * somewhat complicated and the result is still slower than an even simpler option:
# 225 : : * see the FastRange32 function in util/fastrange.h.
# 226 : : *
# 227 : : * The resulting non-uniformity is also more equally distributed which would be
# 228 : : * advantageous for something like linear probing, though it shouldn't matter
# 229 : : * one way or the other for a cuckoo table.
# 230 : : *
# 231 : : * The primary disadvantage of this approach is increased intermediate precision is
# 232 : : * required but for a 32-bit random number we only need the high 32 bits of a
# 233 : : * 32*32->64 multiply, which means the operation is reasonably fast even on a
# 234 : : * typical 32-bit processor.
# 235 : : *
# 236 : : * @param e The element whose hashes will be returned
# 237 : : * @returns Deterministic hashes derived from `e` uniformly mapped onto the range [0, size)
# 238 : : */
# 239 : : inline std::array<uint32_t, 8> compute_hashes(const Element& e) const
# 240 : 7958204 : {
# 241 : 7958204 : return {{FastRange32(hash_function.template operator()<0>(e), size),
# 242 : 7958204 : FastRange32(hash_function.template operator()<1>(e), size),
# 243 : 7958204 : FastRange32(hash_function.template operator()<2>(e), size),
# 244 : 7958204 : FastRange32(hash_function.template operator()<3>(e), size),
# 245 : 7958204 : FastRange32(hash_function.template operator()<4>(e), size),
# 246 : 7958204 : FastRange32(hash_function.template operator()<5>(e), size),
# 247 : 7958204 : FastRange32(hash_function.template operator()<6>(e), size),
# 248 : 7958204 : FastRange32(hash_function.template operator()<7>(e), size)}};
# 249 : 7958204 : }
# 250 : :
# 251 : : /** invalid returns a special index that can never be inserted to
# 252 : : * @returns the special constexpr index that can never be inserted to */
# 253 : : constexpr uint32_t invalid() const
# 254 : 4261170 : {
# 255 : 4261170 : return ~(uint32_t)0;
# 256 : 4261170 : }
# 257 : :
# 258 : : /** allow_erase marks the element at index `n` as discardable. Threadsafe
# 259 : : * without any concurrent insert.
# 260 : : * @param n the index to allow erasure of
# 261 : : */
# 262 : : inline void allow_erase(uint32_t n) const
# 263 : 4413662 : {
# 264 : 4413662 : collection_flags.bit_set(n);
# 265 : 4413662 : }
# 266 : :
# 267 : : /** please_keep marks the element at index `n` as an entry that should be kept.
# 268 : : * Threadsafe without any concurrent insert.
# 269 : : * @param n the index to prioritize keeping
# 270 : : */
# 271 : : inline void please_keep(uint32_t n) const
# 272 : 4261170 : {
# 273 : 4261170 : collection_flags.bit_unset(n);
# 274 : 4261170 : }
# 275 : :
# 276 : : /** epoch_check handles the changing of epochs for elements stored in the
# 277 : : * cache. epoch_check should be run before every insert.
# 278 : : *
# 279 : : * First, epoch_check decrements and checks the cheap heuristic, and then does
# 280 : : * a more expensive scan if the cheap heuristic runs out. If the expensive
# 281 : : * scan succeeds, the epochs are aged and old elements are allow_erased. The
# 282 : : * cheap heuristic is reset to retrigger after the worst case growth of the
# 283 : : * current epoch's elements would exceed the epoch_size.
# 284 : : */
# 285 : : void epoch_check()
# 286 : 4261170 : {
# 287 [ + + ]: 4261170 : if (epoch_heuristic_counter != 0) {
# 288 : 4261002 : --epoch_heuristic_counter;
# 289 : 4261002 : return;
# 290 : 4261002 : }
# 291 : : // count the number of elements from the latest epoch which
# 292 : : // have not been erased.
# 293 : 168 : uint32_t epoch_unused_count = 0;
# 294 [ + + ]: 22020264 : for (uint32_t i = 0; i < size; ++i)
# 295 [ + + ]: 22020096 : epoch_unused_count += epoch_flags[i] &&
# 296 [ + + ]: 22020096 : !collection_flags.bit_is_set(i);
# 297 : : // If there are more non-deleted entries in the current epoch than the
# 298 : : // epoch size, then allow_erase on all elements in the old epoch (marked
# 299 : : // false) and move all elements in the current epoch to the old epoch
# 300 : : // but do not call allow_erase on their indices.
# 301 [ + + ]: 168 : if (epoch_unused_count >= epoch_size) {
# 302 [ + + ]: 6291504 : for (uint32_t i = 0; i < size; ++i)
# 303 [ + + ]: 6291456 : if (epoch_flags[i])
# 304 : 3244652 : epoch_flags[i] = false;
# 305 : 3046804 : else
# 306 : 3046804 : allow_erase(i);
# 307 : 48 : epoch_heuristic_counter = epoch_size;
# 308 : 48 : } else
# 309 : : // reset the epoch_heuristic_counter to next do a scan when worst
# 310 : : // case behavior (no intermittent erases) would exceed epoch size,
# 311 : : // with a reasonable minimum scan size.
# 312 : : // Ordinarily, we would have to sanity check std::min(epoch_size,
# 313 : : // epoch_unused_count), but we already know that `epoch_unused_count
# 314 : : // < epoch_size` in this branch
# 315 : 120 : epoch_heuristic_counter = std::max(1u, std::max(epoch_size / 16,
# 316 : 120 : epoch_size - epoch_unused_count));
# 317 : 168 : }
# 318 : :
# 319 : : public:
# 320 : : /** You must always construct a cache with some elements via a subsequent
# 321 : : * call to setup or setup_bytes, otherwise operations may segfault.
# 322 : : */
# 323 : : cache() : table(), size(), collection_flags(0), epoch_flags(),
# 324 : : epoch_heuristic_counter(), epoch_size(), depth_limit(0), hash_function()
# 325 : 1674 : {
# 326 : 1674 : }
# 327 : :
# 328 : : /** setup initializes the container to store no more than new_size
# 329 : : * elements.
# 330 : : *
# 331 : : * setup should only be called once.
# 332 : : *
# 333 : : * @param new_size the desired number of elements to store
# 334 : : * @returns the maximum number of elements storable
# 335 : : */
# 336 : : uint32_t setup(uint32_t new_size)
# 337 : 3278 : {
# 338 : : // depth_limit must be at least one otherwise errors can occur.
# 339 : 3278 : depth_limit = static_cast<uint8_t>(std::log2(static_cast<float>(std::max((uint32_t)2, new_size))));
# 340 : 3278 : size = std::max<uint32_t>(2, new_size);
# 341 : 3278 : table.resize(size);
# 342 : 3278 : collection_flags.setup(size);
# 343 : 3278 : epoch_flags.resize(size);
# 344 : : // Set to 45% as described above
# 345 : 3278 : epoch_size = std::max((uint32_t)1, (45 * size) / 100);
# 346 : : // Initially set to wait for a whole epoch
# 347 : 3278 : epoch_heuristic_counter = epoch_size;
# 348 : 3278 : return size;
# 349 : 3278 : }
# 350 : :
# 351 : : /** setup_bytes is a convenience function which accounts for internal memory
# 352 : : * usage when deciding how many elements to store. It isn't perfect because
# 353 : : * it doesn't account for any overhead (struct size, MallocUsage, collection
# 354 : : * and epoch flags). This was done to simplify selecting a power of two
# 355 : : * size. In the expected use case, an extra two bits per entry should be
# 356 : : * negligible compared to the size of the elements.
# 357 : : *
# 358 : : * @param bytes the approximate number of bytes to use for this data
# 359 : : * structure
# 360 : : * @returns the maximum number of elements storable (see setup()
# 361 : : * documentation for more detail)
# 362 : : */
# 363 : : uint32_t setup_bytes(size_t bytes)
# 364 : 3278 : {
# 365 : 3278 : return setup(bytes/sizeof(Element));
# 366 : 3278 : }
# 367 : :
# 368 : : /** insert loops at most depth_limit times trying to insert a hash
# 369 : : * at various locations in the table via a variant of the Cuckoo Algorithm
# 370 : : * with eight hash locations.
# 371 : : *
# 372 : : * It drops the last tried element if it runs out of depth before
# 373 : : * encountering an open slot.
# 374 : : *
# 375 : : * Thus:
# 376 : : *
# 377 : : * ```
# 378 : : * insert(x);
# 379 : : * return contains(x, false);
# 380 : : * ```
# 381 : : *
# 382 : : * is not guaranteed to return true.
# 383 : : *
# 384 : : * @param e the element to insert
# 385 : : * @post one of the following: All previously inserted elements and e are
# 386 : : * now in the table, one previously inserted element is evicted from the
# 387 : : * table, the entry attempted to be inserted is evicted.
# 388 : : */
# 389 : : inline void insert(Element e)
# 390 : 4261170 : {
# 391 : 4261170 : epoch_check();
# 392 : 4261170 : uint32_t last_loc = invalid();
# 393 : 4261170 : bool last_epoch = true;
# 394 : 4261170 : std::array<uint32_t, 8> locs = compute_hashes(e);
# 395 : : // Make sure we have not already inserted this element
# 396 : : // If we have, make sure that it does not get deleted
# 397 [ + + ]: 4261170 : for (const uint32_t loc : locs)
# 398 [ - + ]: 34089360 : if (table[loc] == e) {
# 399 : 0 : please_keep(loc);
# 400 : 0 : epoch_flags[loc] = last_epoch;
# 401 : 0 : return;
# 402 : 0 : }
# 403 [ + - ]: 4432774 : for (uint8_t depth = 0; depth < depth_limit; ++depth) {
# 404 : : // First try to insert to an empty slot, if one exists
# 405 [ + + ]: 10793267 : for (const uint32_t loc : locs) {
# 406 [ + + ]: 10793267 : if (!collection_flags.bit_is_set(loc))
# 407 : 6532097 : continue;
# 408 : 4261170 : table[loc] = std::move(e);
# 409 : 4261170 : please_keep(loc);
# 410 : 4261170 : epoch_flags[loc] = last_epoch;
# 411 : 4261170 : return;
# 412 : 10793267 : }
# 413 : : /** Swap with the element at the location that was
# 414 : : * not the last one looked at. Example:
# 415 : : *
# 416 : : * 1. On first iteration, last_loc == invalid(), find returns last, so
# 417 : : * last_loc defaults to locs[0].
# 418 : : * 2. On further iterations, where last_loc == locs[k], last_loc will
# 419 : : * go to locs[k+1 % 8], i.e., next of the 8 indices wrapping around
# 420 : : * to 0 if needed.
# 421 : : *
# 422 : : * This prevents moving the element we just put in.
# 423 : : *
# 424 : : * The swap is not a move -- we must switch onto the evicted element
# 425 : : * for the next iteration.
# 426 : : */
# 427 : 171604 : last_loc = locs[(1 + (std::find(locs.begin(), locs.end(), last_loc) - locs.begin())) & 7];
# 428 : 171604 : std::swap(table[last_loc], e);
# 429 : : // Can't std::swap a std::vector<bool>::reference and a bool&.
# 430 : 171604 : bool epoch = last_epoch;
# 431 : 171604 : last_epoch = epoch_flags[last_loc];
# 432 : 171604 : epoch_flags[last_loc] = epoch;
# 433 : :
# 434 : : // Recompute the locs -- unfortunately happens one too many times!
# 435 : 171604 : locs = compute_hashes(e);
# 436 : 171604 : }
# 437 : 4261170 : }
# 438 : :
# 439 : : /** contains iterates through the hash locations for a given element
# 440 : : * and checks to see if it is present.
# 441 : : *
# 442 : : * contains does not check garbage collected state (in other words,
# 443 : : * garbage is only collected when the space is needed), so:
# 444 : : *
# 445 : : * ```
# 446 : : * insert(x);
# 447 : : * if (contains(x, true))
# 448 : : * return contains(x, false);
# 449 : : * else
# 450 : : * return true;
# 451 : : * ```
# 452 : : *
# 453 : : * executed on a single thread will always return true!
# 454 : : *
# 455 : : * This is a great property for re-org performance for example.
# 456 : : *
# 457 : : * contains returns a bool set true if the element was found.
# 458 : : *
# 459 : : * @param e the element to check
# 460 : : * @param erase whether to attempt setting the garbage collect flag
# 461 : : *
# 462 : : * @post if erase is true and the element is found, then the garbage collect
# 463 : : * flag is set
# 464 : : * @returns true if the element is found, false otherwise
# 465 : : */
# 466 : : inline bool contains(const Element& e, const bool erase) const
# 467 : 3525576 : {
# 468 : 3525576 : std::array<uint32_t, 8> locs = compute_hashes(e);
# 469 [ + + ]: 3525576 : for (const uint32_t loc : locs)
# 470 [ + + ]: 12146525 : if (table[loc] == e) {
# 471 [ + + ]: 2666718 : if (erase)
# 472 : 1366834 : allow_erase(loc);
# 473 : 2666718 : return true;
# 474 : 2666718 : }
# 475 : 858858 : return false;
# 476 : 3525576 : }
# 477 : : };
# 478 : : } // namespace CuckooCache
# 479 : :
# 480 : : #endif // BITCOIN_CUCKOOCACHE_H
|