clock_cache.cc 48.0 KB
Newer Older
Y
Yi Wu 已提交
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
Y
Yi Wu 已提交
5 6 7 8 9
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

10
#include "cache/clock_cache.h"
Y
Yi Wu 已提交
11

G
Guido Tagliavini Ponce 已提交
12 13
#include <cassert>
#include <functional>
Y
Yi Wu 已提交
14

15
#include "cache/cache_key.h"
G
Guido Tagliavini Ponce 已提交
16 17 18 19 20 21
#include "monitoring/perf_context_imp.h"
#include "monitoring/statistics.h"
#include "port/lang.h"
#include "util/hash.h"
#include "util/math.h"
#include "util/random.h"
Y
Yi Wu 已提交
22

G
Guido Tagliavini Ponce 已提交
23
namespace ROCKSDB_NAMESPACE {
Y
Yi Wu 已提交
24

25
namespace hyper_clock_cache {
Y
Yi Wu 已提交
26

27 28 29 30 31 32
inline uint64_t GetRefcount(uint64_t meta) {
  return ((meta >> ClockHandle::kAcquireCounterShift) -
          (meta >> ClockHandle::kReleaseCounterShift)) &
         ClockHandle::kCounterMask;
}

33 34 35 36 37 38 39
void ClockHandleBasicData::FreeData() const {
  if (deleter) {
    UniqueId64x2 unhashed;
    (*deleter)(ClockCacheShard::ReverseHash(hashed_key, &unhashed), value);
  }
}

40 41 42 43
static_assert(sizeof(ClockHandle) == 64U,
              "Expecting size / alignment with common cache line size");

ClockHandleTable::ClockHandleTable(int hash_bits, bool initial_charge_metadata)
G
Guido Tagliavini Ponce 已提交
44
    : length_bits_(hash_bits),
45 46 47
      length_bits_mask_((size_t{1} << length_bits_) - 1),
      occupancy_limit_(static_cast<size_t>((uint64_t{1} << length_bits_) *
                                           kStrictLoadFactor)),
48 49 50 51
      array_(new ClockHandle[size_t{1} << length_bits_]) {
  if (initial_charge_metadata) {
    usage_ += size_t{GetTableSize()} * sizeof(ClockHandle);
  }
G
Guido Tagliavini Ponce 已提交
52
}
Y
Yi Wu 已提交
53

G
Guido Tagliavini Ponce 已提交
54
ClockHandleTable::~ClockHandleTable() {
55 56
  // Assumes there are no references or active operations on any slot/element
  // in the table.
57
  for (size_t i = 0; i < GetTableSize(); i++) {
58 59 60 61 62 63 64
    ClockHandle& h = array_[i];
    switch (h.meta >> ClockHandle::kStateShift) {
      case ClockHandle::kStateEmpty:
        // noop
        break;
      case ClockHandle::kStateInvisible:  // rare but possible
      case ClockHandle::kStateVisible:
65
        assert(GetRefcount(h.meta) == 0);
66 67
        h.FreeData();
#ifndef NDEBUG
68
        Rollback(h.hashed_key, &h);
69 70 71 72 73 74 75 76
        usage_.fetch_sub(h.total_charge, std::memory_order_relaxed);
        occupancy_.fetch_sub(1U, std::memory_order_relaxed);
#endif
        break;
      // otherwise
      default:
        assert(false);
        break;
77 78
    }
  }
79 80

#ifndef NDEBUG
81
  for (size_t i = 0; i < GetTableSize(); i++) {
82 83 84 85 86 87 88
    assert(array_[i].displacements.load() == 0);
  }
#endif

  assert(usage_.load() == 0 ||
         usage_.load() == size_t{GetTableSize()} * sizeof(ClockHandle));
  assert(occupancy_ == 0);
G
Guido Tagliavini Ponce 已提交
89
}
Y
Yi Wu 已提交
90

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
// If an entry doesn't receive clock updates but is repeatedly referenced &
// released, the acquire and release counters could overflow without some
// intervention. This is that intervention, which should be inexpensive
// because it only incurs a simple, very predictable check. (Applying a bit
// mask in addition to an increment to every Release likely would be
// relatively expensive, because it's an extra atomic update.)
//
// We do have to assume that we never have many millions of simultaneous
// references to a cache handle, because we cannot represent so many
// references with the difference in counters, masked to the number of
// counter bits. Similarly, we assume there aren't millions of threads
// holding transient references (which might be "undone" rather than
// released by the way).
//
// Consider these possible states for each counter:
// low: less than kMaxCountdown
// medium: kMaxCountdown to half way to overflow + kMaxCountdown
// high: half way to overflow + kMaxCountdown, or greater
//
// And these possible states for the combination of counters:
// acquire / release
// -------   -------
// low       low       - Normal / common, with caveats (see below)
// medium    low       - Can happen while holding some refs
// high      low       - Violates assumptions (too many refs)
// low       medium    - Violates assumptions (refs underflow, etc.)
// medium    medium    - Normal (very read heavy cache)
// high      medium    - Can happen while holding some refs
// low       high      - This function is supposed to prevent
// medium    high      - Violates assumptions (refs underflow, etc.)
// high      high      - Needs CorrectNearOverflow
//
// Basically, this function detects (high, high) state (inferred from
// release alone being high) and bumps it back down to (medium, medium)
// state with the same refcount and the same logical countdown counter
// (everything > kMaxCountdown is logically the same). Note that bumping
// down to (low, low) would modify the countdown counter, so is "reserved"
// in a sense.
//
// If near-overflow correction is triggered here, there's no guarantee
// that another thread hasn't freed the entry and replaced it with another.
// Therefore, it must be the case that the correction does not affect
// entries unless they are very old (many millions of acquire-release cycles).
// (Our bit manipulation is indeed idempotent and only affects entries in
// exceptional cases.) We assume a pre-empted thread will not stall that long.
// If it did, the state could be corrupted in the (unlikely) case that the top
// bit of the acquire counter is set but not the release counter, and thus
// we only clear the top bit of the acquire counter on resumption. It would
// then appear that there are too many refs and the entry would be permanently
// pinned (which is not terrible for an exceptionally rare occurrence), unless
// it is referenced enough (at least kMaxCountdown more times) for the release
// counter to reach "high" state again and bumped back to "medium." (This
// motivates only checking for release counter in high state, not both in high
// state.)
inline void CorrectNearOverflow(uint64_t old_meta,
                                std::atomic<uint64_t>& meta) {
  // We clear both top-most counter bits at the same time.
  constexpr uint64_t kCounterTopBit = uint64_t{1}
                                      << (ClockHandle::kCounterNumBits - 1);
  constexpr uint64_t kClearBits =
      (kCounterTopBit << ClockHandle::kAcquireCounterShift) |
      (kCounterTopBit << ClockHandle::kReleaseCounterShift);
  // A simple check that allows us to initiate clearing the top bits for
  // a large portion of the "high" state space on release counter.
  constexpr uint64_t kCheckBits =
      (kCounterTopBit | (ClockHandle::kMaxCountdown + 1))
      << ClockHandle::kReleaseCounterShift;

  if (UNLIKELY(old_meta & kCheckBits)) {
    meta.fetch_and(~kClearBits, std::memory_order_relaxed);
  }
}

164
Status ClockHandleTable::Insert(const ClockHandleBasicData& proto,
165 166 167 168
                                ClockHandle** handle, Cache::Priority priority,
                                size_t capacity, bool strict_capacity_limit) {
  // Do we have the available occupancy? Optimistically assume we do
  // and deal with it if we don't.
169
  size_t old_occupancy = occupancy_.fetch_add(1, std::memory_order_acquire);
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  auto revert_occupancy_fn = [&]() {
    occupancy_.fetch_sub(1, std::memory_order_relaxed);
  };
  // Whether we over-committed and need an eviction to make up for it
  bool need_evict_for_occupancy = old_occupancy >= occupancy_limit_;

  // Usage/capacity handling is somewhat different depending on
  // strict_capacity_limit, but mostly pessimistic.
  bool use_detached_insert = false;
  const size_t total_charge = proto.total_charge;
  if (strict_capacity_limit) {
    if (total_charge > capacity) {
      assert(!use_detached_insert);
      revert_occupancy_fn();
      return Status::MemoryLimit(
          "Cache entry too large for a single cache shard: " +
          std::to_string(total_charge) + " > " + std::to_string(capacity));
    }
    // Grab any available capacity, and free up any more required.
    size_t old_usage = usage_.load(std::memory_order_relaxed);
    size_t new_usage;
    if (LIKELY(old_usage != capacity)) {
      do {
        new_usage = std::min(capacity, old_usage + total_charge);
      } while (!usage_.compare_exchange_weak(old_usage, new_usage,
                                             std::memory_order_relaxed));
    } else {
      new_usage = old_usage;
    }
    // How much do we need to evict then?
    size_t need_evict_charge = old_usage + total_charge - new_usage;
    size_t request_evict_charge = need_evict_charge;
    if (UNLIKELY(need_evict_for_occupancy) && request_evict_charge == 0) {
      // Require at least 1 eviction.
      request_evict_charge = 1;
    }
    if (request_evict_charge > 0) {
      size_t evicted_charge = 0;
208
      size_t evicted_count = 0;
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
      Evict(request_evict_charge, &evicted_charge, &evicted_count);
      occupancy_.fetch_sub(evicted_count, std::memory_order_release);
      if (LIKELY(evicted_charge > need_evict_charge)) {
        assert(evicted_count > 0);
        // Evicted more than enough
        usage_.fetch_sub(evicted_charge - need_evict_charge,
                         std::memory_order_relaxed);
      } else if (evicted_charge < need_evict_charge ||
                 (UNLIKELY(need_evict_for_occupancy) && evicted_count == 0)) {
        // Roll back to old usage minus evicted
        usage_.fetch_sub(evicted_charge + (new_usage - old_usage),
                         std::memory_order_relaxed);
        assert(!use_detached_insert);
        revert_occupancy_fn();
        if (evicted_charge < need_evict_charge) {
          return Status::MemoryLimit(
              "Insert failed because unable to evict entries to stay within "
              "capacity limit.");
        } else {
          return Status::MemoryLimit(
              "Insert failed because unable to evict entries to stay within "
              "table occupancy limit.");
        }
      }
      // If we needed to evict something and we are proceeding, we must have
      // evicted something.
      assert(evicted_count > 0);
    }
  } else {
    // Case strict_capacity_limit == false

    // For simplicity, we consider that either the cache can accept the insert
    // with no evictions, or we must evict enough to make (at least) enough
    // space. It could lead to unnecessary failures or excessive evictions in
    // some extreme cases, but allows a fast, simple protocol. If we allow a
    // race to get us over capacity, then we might never get back to capacity
    // limit if the sizes of entries allow each insertion to evict the minimum
    // charge. Thus, we should evict some extra if it's not a signifcant
    // portion of the shard capacity. This can have the side benefit of
    // involving fewer threads in eviction.
    size_t old_usage = usage_.load(std::memory_order_relaxed);
    size_t need_evict_charge;
    // NOTE: if total_charge > old_usage, there isn't yet enough to evict
    // `total_charge` amount. Even if we only try to evict `old_usage` amount,
    // there's likely something referenced and we would eat CPU looking for
    // enough to evict.
    if (old_usage + total_charge <= capacity || total_charge > old_usage) {
      // Good enough for me (might run over with a race)
      need_evict_charge = 0;
    } else {
      // Try to evict enough space, and maybe some extra
      need_evict_charge = total_charge;
      if (old_usage > capacity) {
        // Not too much to avoid thundering herd while avoiding strict
        // synchronization
        need_evict_charge += std::min(capacity / 1024, total_charge) + 1;
      }
    }
    if (UNLIKELY(need_evict_for_occupancy) && need_evict_charge == 0) {
      // Special case: require at least 1 eviction if we only have to
      // deal with occupancy
      need_evict_charge = 1;
    }
    size_t evicted_charge = 0;
273
    size_t evicted_count = 0;
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    if (need_evict_charge > 0) {
      Evict(need_evict_charge, &evicted_charge, &evicted_count);
      // Deal with potential occupancy deficit
      if (UNLIKELY(need_evict_for_occupancy) && evicted_count == 0) {
        assert(evicted_charge == 0);
        revert_occupancy_fn();
        if (handle == nullptr) {
          // Don't insert the entry but still return ok, as if the entry
          // inserted into cache and evicted immediately.
          proto.FreeData();
          return Status::OK();
        } else {
          use_detached_insert = true;
        }
      } else {
        // Update occupancy for evictions
        occupancy_.fetch_sub(evicted_count, std::memory_order_release);
      }
    }
    // Track new usage even if we weren't able to evict enough
    usage_.fetch_add(total_charge - evicted_charge, std::memory_order_relaxed);
    // No underflow
    assert(usage_.load(std::memory_order_relaxed) < SIZE_MAX / 2);
  }
  auto revert_usage_fn = [&]() {
    usage_.fetch_sub(total_charge, std::memory_order_relaxed);
    // No underflow
    assert(usage_.load(std::memory_order_relaxed) < SIZE_MAX / 2);
  };

  if (!use_detached_insert) {
    // Attempt a table insert, but abort if we find an existing entry for the
    // key. If we were to overwrite old entries, we would either
    // * Have to gain ownership over an existing entry to overwrite it, which
    // would only work if there are no outstanding (read) references and would
    // create a small gap in availability of the entry (old or new) to lookups.
    // * Have to insert into a suboptimal location (more probes) so that the
    // old entry can be kept around as well.

    // Set initial clock data from priority
    // TODO: configuration parameters for priority handling and clock cycle
    // count?
    uint64_t initial_countdown;
    switch (priority) {
      case Cache::Priority::HIGH:
        initial_countdown = ClockHandle::kHighCountdown;
        break;
      default:
        assert(false);
        FALLTHROUGH_INTENDED;
      case Cache::Priority::LOW:
        initial_countdown = ClockHandle::kLowCountdown;
        break;
      case Cache::Priority::BOTTOM:
        initial_countdown = ClockHandle::kBottomCountdown;
        break;
    }
    assert(initial_countdown > 0);

333
    size_t probe = 0;
334
    ClockHandle* e = FindSlot(
335
        proto.hashed_key,
336 337 338 339 340 341 342 343 344 345 346 347
        [&](ClockHandle* h) {
          // Optimistically transition the slot from "empty" to
          // "under construction" (no effect on other states)
          uint64_t old_meta =
              h->meta.fetch_or(uint64_t{ClockHandle::kStateOccupiedBit}
                                   << ClockHandle::kStateShift,
                               std::memory_order_acq_rel);
          uint64_t old_state = old_meta >> ClockHandle::kStateShift;

          if (old_state == ClockHandle::kStateEmpty) {
            // We've started inserting into an available slot, and taken
            // ownership Save data fields
348
            ClockHandleBasicData* h_alias = h;
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
            *h_alias = proto;

            // Transition from "under construction" state to "visible" state
            uint64_t new_meta = uint64_t{ClockHandle::kStateVisible}
                                << ClockHandle::kStateShift;

            // Maybe with an outstanding reference
            new_meta |= initial_countdown << ClockHandle::kAcquireCounterShift;
            new_meta |= (initial_countdown - (handle != nullptr))
                        << ClockHandle::kReleaseCounterShift;

#ifndef NDEBUG
            // Save the state transition, with assertion
            old_meta = h->meta.exchange(new_meta, std::memory_order_release);
            assert(old_meta >> ClockHandle::kStateShift ==
                   ClockHandle::kStateConstruction);
#else
            // Save the state transition
            h->meta.store(new_meta, std::memory_order_release);
#endif
            return true;
          } else if (old_state != ClockHandle::kStateVisible) {
            // Slot not usable / touchable now
            return false;
          }
          // Existing, visible entry, which might be a match.
          // But first, we need to acquire a ref to read it. In fact, number of
          // refs for initial countdown, so that we boost the clock state if
          // this is a match.
          old_meta = h->meta.fetch_add(
              ClockHandle::kAcquireIncrement * initial_countdown,
              std::memory_order_acq_rel);
          // Like Lookup
          if ((old_meta >> ClockHandle::kStateShift) ==
              ClockHandle::kStateVisible) {
            // Acquired a read reference
385
            if (h->hashed_key == proto.hashed_key) {
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
              // Match. Release in a way that boosts the clock state
              old_meta = h->meta.fetch_add(
                  ClockHandle::kReleaseIncrement * initial_countdown,
                  std::memory_order_acq_rel);
              // Correct for possible (but rare) overflow
              CorrectNearOverflow(old_meta, h->meta);
              // Insert detached instead (only if return handle needed)
              use_detached_insert = true;
              return true;
            } else {
              // Mismatch. Pretend we never took the reference
              old_meta = h->meta.fetch_sub(
                  ClockHandle::kAcquireIncrement * initial_countdown,
                  std::memory_order_acq_rel);
            }
          } else if (UNLIKELY((old_meta >> ClockHandle::kStateShift) ==
                              ClockHandle::kStateInvisible)) {
            // Pretend we never took the reference
            // WART: there's a tiny chance we release last ref to invisible
            // entry here. If that happens, we let eviction take care of it.
            old_meta = h->meta.fetch_sub(
                ClockHandle::kAcquireIncrement * initial_countdown,
                std::memory_order_acq_rel);
          } else {
            // For other states, incrementing the acquire counter has no effect
            // so we don't need to undo it.
            // Slot not usable / touchable now.
          }
          (void)old_meta;
          return false;
        },
        [&](ClockHandle* /*h*/) { return false; },
        [&](ClockHandle* h) {
          h->displacements.fetch_add(1, std::memory_order_relaxed);
        },
        probe);
    if (e == nullptr) {
      // Occupancy check and never abort FindSlot above should generally
      // prevent this, except it's theoretically possible for other threads
      // to evict and replace entries in the right order to hit every slot
      // when it is populated. Assuming random hashing, the chance of that
      // should be no higher than pow(kStrictLoadFactor, n) for n slots.
      // That should be infeasible for roughly n >= 256, so if this assertion
      // fails, that suggests something is going wrong.
      assert(GetTableSize() < 256);
      use_detached_insert = true;
    }
    if (!use_detached_insert) {
      // Successfully inserted
      if (handle) {
        *handle = e;
      }
      return Status::OK();
    }
    // Roll back table insertion
441
    Rollback(proto.hashed_key, e);
442 443 444 445 446 447 448 449 450 451 452 453 454 455
    revert_occupancy_fn();
    // Maybe fall back on detached insert
    if (handle == nullptr) {
      revert_usage_fn();
      // As if unrefed entry immdiately evicted
      proto.FreeData();
      return Status::OK();
    }
  }

  // Run detached insert
  assert(use_detached_insert);

  ClockHandle* h = new ClockHandle();
456
  ClockHandleBasicData* h_alias = h;
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  *h_alias = proto;
  h->detached = true;
  // Single reference (detached entries only created if returning a refed
  // Handle back to user)
  uint64_t meta = uint64_t{ClockHandle::kStateInvisible}
                  << ClockHandle::kStateShift;
  meta |= uint64_t{1} << ClockHandle::kAcquireCounterShift;
  h->meta.store(meta, std::memory_order_release);
  // Keep track of usage
  detached_usage_.fetch_add(total_charge, std::memory_order_relaxed);

  *handle = h;
  // The OkOverwritten status is used to count "redundant" insertions into
  // block cache. This implementation doesn't strictly check for redundant
  // insertions, but we instead are probably interested in how many insertions
  // didn't go into the table (instead "detached"), which could be redundant
  // Insert or some other reason (use_detached_insert reasons above).
  return Status::OkOverwritten();
}

477 478
ClockHandle* ClockHandleTable::Lookup(const UniqueId64x2& hashed_key) {
  size_t probe = 0;
479
  ClockHandle* e = FindSlot(
480
      hashed_key,
481
      [&](ClockHandle* h) {
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        // Mostly branch-free version (similar performance)
        /*
        uint64_t old_meta = h->meta.fetch_add(ClockHandle::kAcquireIncrement,
                                     std::memory_order_acquire);
        bool Shareable = (old_meta >> (ClockHandle::kStateShift + 1)) & 1U;
        bool visible = (old_meta >> ClockHandle::kStateShift) & 1U;
        bool match = (h->key == key) & visible;
        h->meta.fetch_sub(static_cast<uint64_t>(Shareable & !match) <<
        ClockHandle::kAcquireCounterShift, std::memory_order_release); return
        match;
        */
        // Optimistic lookup should pay off when the table is relatively
        // sparse.
        constexpr bool kOptimisticLookup = true;
        uint64_t old_meta;
        if (!kOptimisticLookup) {
          old_meta = h->meta.load(std::memory_order_acquire);
          if ((old_meta >> ClockHandle::kStateShift) !=
              ClockHandle::kStateVisible) {
            return false;
          }
        }
        // (Optimistically) increment acquire counter
        old_meta = h->meta.fetch_add(ClockHandle::kAcquireIncrement,
                                     std::memory_order_acquire);
        // Check if it's an entry visible to lookups
        if ((old_meta >> ClockHandle::kStateShift) ==
            ClockHandle::kStateVisible) {
          // Acquired a read reference
511
          if (h->hashed_key == hashed_key) {
512
            // Match
513
            return true;
514 515 516 517
          } else {
            // Mismatch. Pretend we never took the reference
            old_meta = h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                                         std::memory_order_release);
518
          }
519 520 521 522 523 524 525 526 527 528 529 530
        } else if (UNLIKELY((old_meta >> ClockHandle::kStateShift) ==
                            ClockHandle::kStateInvisible)) {
          // Pretend we never took the reference
          // WART: there's a tiny chance we release last ref to invisible
          // entry here. If that happens, we let eviction take care of it.
          old_meta = h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                                       std::memory_order_release);
        } else {
          // For other states, incrementing the acquire counter has no effect
          // so we don't need to undo it. Furthermore, we cannot safely undo
          // it because we did not acquire a read reference to lock the
          // entry in a Shareable state.
531
        }
532
        (void)old_meta;
533 534
        return false;
      },
535 536 537
      [&](ClockHandle* h) {
        return h->displacements.load(std::memory_order_relaxed) == 0;
      },
538 539 540
      [&](ClockHandle* /*h*/) {}, probe);

  return e;
G
Guido Tagliavini Ponce 已提交
541
}
Y
Yi Wu 已提交
542

543 544 545 546 547 548
bool ClockHandleTable::Release(ClockHandle* h, bool useful,
                               bool erase_if_last_ref) {
  // In contrast with LRUCache's Release, this function won't delete the handle
  // when the cache is above capacity and the reference is the last one. Space
  // is only freed up by EvictFromClock (called by Insert when space is needed)
  // and Erase. We do this to avoid an extra atomic read of the variable usage_.
549

550 551 552 553 554
  uint64_t old_meta;
  if (useful) {
    // Increment release counter to indicate was used
    old_meta = h->meta.fetch_add(ClockHandle::kReleaseIncrement,
                                 std::memory_order_release);
555
  } else {
556 557 558
    // Decrement acquire counter to pretend it never happened
    old_meta = h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                                 std::memory_order_release);
559
  }
Y
Yi Wu 已提交
560

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
  assert((old_meta >> ClockHandle::kStateShift) &
         ClockHandle::kStateShareableBit);
  // No underflow
  assert(((old_meta >> ClockHandle::kAcquireCounterShift) &
          ClockHandle::kCounterMask) !=
         ((old_meta >> ClockHandle::kReleaseCounterShift) &
          ClockHandle::kCounterMask));

  if (erase_if_last_ref || UNLIKELY(old_meta >> ClockHandle::kStateShift ==
                                    ClockHandle::kStateInvisible)) {
    // Update for last fetch_add op
    if (useful) {
      old_meta += ClockHandle::kReleaseIncrement;
    } else {
      old_meta -= ClockHandle::kAcquireIncrement;
    }
    // Take ownership if no refs
    do {
579
      if (GetRefcount(old_meta) != 0) {
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
        // Not last ref at some point in time during this Release call
        // Correct for possible (but rare) overflow
        CorrectNearOverflow(old_meta, h->meta);
        return false;
      }
      if ((old_meta & (uint64_t{ClockHandle::kStateShareableBit}
                       << ClockHandle::kStateShift)) == 0) {
        // Someone else took ownership
        return false;
      }
      // Note that there's a small chance that we release, another thread
      // replaces this entry with another, reaches zero refs, and then we end
      // up erasing that other entry. That's an acceptable risk / imprecision.
    } while (!h->meta.compare_exchange_weak(
        old_meta,
        uint64_t{ClockHandle::kStateConstruction} << ClockHandle::kStateShift,
        std::memory_order_acquire));
    // Took ownership
    // TODO? Delay freeing?
    h->FreeData();
    size_t total_charge = h->total_charge;
    if (UNLIKELY(h->detached)) {
      // Delete detached handle
      delete h;
      detached_usage_.fetch_sub(total_charge, std::memory_order_relaxed);
    } else {
606
      UniqueId64x2 hashed_key = h->hashed_key;
607 608 609 610 611 612 613 614 615 616
#ifndef NDEBUG
      // Mark slot as empty, with assertion
      old_meta = h->meta.exchange(0, std::memory_order_release);
      assert(old_meta >> ClockHandle::kStateShift ==
             ClockHandle::kStateConstruction);
#else
      // Mark slot as empty
      h->meta.store(0, std::memory_order_release);
#endif
      occupancy_.fetch_sub(1U, std::memory_order_release);
617
      Rollback(hashed_key, h);
618
    }
619 620 621 622 623 624 625
    usage_.fetch_sub(total_charge, std::memory_order_relaxed);
    assert(usage_.load(std::memory_order_relaxed) < SIZE_MAX / 2);
    return true;
  } else {
    // Correct for possible (but rare) overflow
    CorrectNearOverflow(old_meta, h->meta);
    return false;
626 627 628
  }
}

629 630 631 632 633 634 635
void ClockHandleTable::Ref(ClockHandle& h) {
  // Increment acquire counter
  uint64_t old_meta = h.meta.fetch_add(ClockHandle::kAcquireIncrement,
                                       std::memory_order_acquire);

  assert((old_meta >> ClockHandle::kStateShift) &
         ClockHandle::kStateShareableBit);
636 637
  // Must have already had a reference
  assert(GetRefcount(old_meta) > 0);
638
  (void)old_meta;
639 640
}

641 642 643 644 645 646 647 648
void ClockHandleTable::TEST_RefN(ClockHandle& h, size_t n) {
  // Increment acquire counter
  uint64_t old_meta = h.meta.fetch_add(n * ClockHandle::kAcquireIncrement,
                                       std::memory_order_acquire);

  assert((old_meta >> ClockHandle::kStateShift) &
         ClockHandle::kStateShareableBit);
  (void)old_meta;
649 650
}

651 652 653 654 655 656 657 658 659 660 661
void ClockHandleTable::TEST_ReleaseN(ClockHandle* h, size_t n) {
  if (n > 0) {
    // Split into n - 1 and 1 steps.
    uint64_t old_meta = h->meta.fetch_add(
        (n - 1) * ClockHandle::kReleaseIncrement, std::memory_order_acquire);
    assert((old_meta >> ClockHandle::kStateShift) &
           ClockHandle::kStateShareableBit);
    (void)old_meta;

    Release(h, /*useful*/ true, /*erase_if_last_ref*/ false);
  }
662 663
}

664 665
void ClockHandleTable::Erase(const UniqueId64x2& hashed_key) {
  size_t probe = 0;
666
  (void)FindSlot(
667
      hashed_key,
668
      [&](ClockHandle* h) {
669 670 671 672 673 674 675 676
        // Could be multiple entries in rare cases. Erase them all.
        // Optimistically increment acquire counter
        uint64_t old_meta = h->meta.fetch_add(ClockHandle::kAcquireIncrement,
                                              std::memory_order_acquire);
        // Check if it's an entry visible to lookups
        if ((old_meta >> ClockHandle::kStateShift) ==
            ClockHandle::kStateVisible) {
          // Acquired a read reference
677
          if (h->hashed_key == hashed_key) {
678 679 680 681 682 683 684 685 686
            // Match. Set invisible.
            old_meta =
                h->meta.fetch_and(~(uint64_t{ClockHandle::kStateVisibleBit}
                                    << ClockHandle::kStateShift),
                                  std::memory_order_acq_rel);
            // Apply update to local copy
            old_meta &= ~(uint64_t{ClockHandle::kStateVisibleBit}
                          << ClockHandle::kStateShift);
            for (;;) {
687
              uint64_t refcount = GetRefcount(old_meta);
688 689 690 691 692 693 694 695
              assert(refcount > 0);
              if (refcount > 1) {
                // Not last ref at some point in time during this Erase call
                // Pretend we never took the reference
                h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                                  std::memory_order_release);
                break;
              } else if (h->meta.compare_exchange_weak(
696 697 698 699
                             old_meta,
                             uint64_t{ClockHandle::kStateConstruction}
                                 << ClockHandle::kStateShift,
                             std::memory_order_acq_rel)) {
700
                // Took ownership
701
                assert(hashed_key == h->hashed_key);
702 703 704 705 706 707 708 709 710 711 712 713 714 715
                // TODO? Delay freeing?
                h->FreeData();
                usage_.fetch_sub(h->total_charge, std::memory_order_relaxed);
                assert(usage_.load(std::memory_order_relaxed) < SIZE_MAX / 2);
#ifndef NDEBUG
                // Mark slot as empty, with assertion
                old_meta = h->meta.exchange(0, std::memory_order_release);
                assert(old_meta >> ClockHandle::kStateShift ==
                       ClockHandle::kStateConstruction);
#else
                // Mark slot as empty
                h->meta.store(0, std::memory_order_release);
#endif
                occupancy_.fetch_sub(1U, std::memory_order_release);
716
                Rollback(hashed_key, h);
717 718
                break;
              }
719
            }
720 721 722 723
          } else {
            // Mismatch. Pretend we never took the reference
            h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                              std::memory_order_release);
724
          }
725 726 727 728 729 730 731 732 733 734
        } else if (UNLIKELY((old_meta >> ClockHandle::kStateShift) ==
                            ClockHandle::kStateInvisible)) {
          // Pretend we never took the reference
          // WART: there's a tiny chance we release last ref to invisible
          // entry here. If that happens, we let eviction take care of it.
          h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                            std::memory_order_release);
        } else {
          // For other states, incrementing the acquire counter has no effect
          // so we don't need to undo it.
735 736 737
        }
        return false;
      },
738 739 740
      [&](ClockHandle* h) {
        return h->displacements.load(std::memory_order_relaxed) == 0;
      },
741
      [&](ClockHandle* /*h*/) {}, probe);
G
Guido Tagliavini Ponce 已提交
742
}
Y
Yi Wu 已提交
743

744
void ClockHandleTable::ConstApplyToEntriesRange(
745 746
    std::function<void(const ClockHandle&)> func, size_t index_begin,
    size_t index_end, bool apply_if_will_be_deleted) const {
747 748 749
  uint64_t check_state_mask = ClockHandle::kStateShareableBit;
  if (!apply_if_will_be_deleted) {
    check_state_mask |= ClockHandle::kStateVisibleBit;
750 751
  }

752
  for (size_t i = index_begin; i < index_end; i++) {
753 754
    ClockHandle& h = array_[i];

755
    // Note: to avoid using compare_exchange, we have to be extra careful.
756 757 758
    uint64_t old_meta = h.meta.load(std::memory_order_relaxed);
    // Check if it's an entry visible to lookups
    if ((old_meta >> ClockHandle::kStateShift) & check_state_mask) {
759 760 761
      // Increment acquire counter. Note: it's possible that the entry has
      // completely changed since we loaded old_meta, but incrementing acquire
      // count is always safe. (Similar to optimistic Lookup here.)
762 763
      old_meta = h.meta.fetch_add(ClockHandle::kAcquireIncrement,
                                  std::memory_order_acquire);
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
      // Check whether we actually acquired a reference.
      if ((old_meta >> ClockHandle::kStateShift) &
          ClockHandle::kStateShareableBit) {
        // Apply func if appropriate
        if ((old_meta >> ClockHandle::kStateShift) & check_state_mask) {
          func(h);
        }
        // Pretend we never took the reference
        h.meta.fetch_sub(ClockHandle::kAcquireIncrement,
                         std::memory_order_release);
        // No net change, so don't need to check for overflow
      } else {
        // For other states, incrementing the acquire counter has no effect
        // so we don't need to undo it. Furthermore, we cannot safely undo
        // it because we did not acquire a read reference to lock the
        // entry in a Shareable state.
780 781
      }
    }
782
  }
G
Guido Tagliavini Ponce 已提交
783
}
Y
Yi Wu 已提交
784

785
void ClockHandleTable::EraseUnRefEntries() {
786
  for (size_t i = 0; i <= this->length_bits_mask_; i++) {
787 788 789 790 791
    ClockHandle& h = array_[i];

    uint64_t old_meta = h.meta.load(std::memory_order_relaxed);
    if (old_meta & (uint64_t{ClockHandle::kStateShareableBit}
                    << ClockHandle::kStateShift) &&
792
        GetRefcount(old_meta) == 0 &&
793 794 795 796 797
        h.meta.compare_exchange_strong(old_meta,
                                       uint64_t{ClockHandle::kStateConstruction}
                                           << ClockHandle::kStateShift,
                                       std::memory_order_acquire)) {
      // Took ownership
798
      UniqueId64x2 hashed_key = h.hashed_key;
799 800 801 802 803 804 805 806 807 808 809 810
      h.FreeData();
      usage_.fetch_sub(h.total_charge, std::memory_order_relaxed);
#ifndef NDEBUG
      // Mark slot as empty, with assertion
      old_meta = h.meta.exchange(0, std::memory_order_release);
      assert(old_meta >> ClockHandle::kStateShift ==
             ClockHandle::kStateConstruction);
#else
      // Mark slot as empty
      h.meta.store(0, std::memory_order_release);
#endif
      occupancy_.fetch_sub(1U, std::memory_order_release);
811
      Rollback(hashed_key, &h);
812
    }
813
  }
G
Guido Tagliavini Ponce 已提交
814 815
}

816
ClockHandle* ClockHandleTable::FindSlot(
817
    const UniqueId64x2& hashed_key, std::function<bool(ClockHandle*)> match_fn,
818
    std::function<bool(ClockHandle*)> abort_fn,
819 820 821
    std::function<void(ClockHandle*)> update_fn, size_t& probe) {
  // NOTE: upper 32 bits of hashed_key[0] is used for sharding
  //
822 823 824 825
  // We use double-hashing probing. Every probe in the sequence is a
  // pseudorandom integer, computed as a linear function of two random hashes,
  // which we call base and increment. Specifically, the i-th probe is base + i
  // * increment modulo the table size.
826
  size_t base = static_cast<size_t>(hashed_key[1]);
827 828 829
  // We use an odd increment, which is relatively prime with the power-of-two
  // table size. This implies that we cycle back to the first probe only
  // after probing every slot exactly once.
830 831
  // TODO: we could also reconsider linear probing, though locality benefits
  // are limited because each slot is a full cache line
832 833
  size_t increment = static_cast<size_t>(hashed_key[0]) | 1U;
  size_t current = ModTableSize(base + probe * increment);
834
  while (probe <= length_bits_mask_) {
G
Guido Tagliavini Ponce 已提交
835
    ClockHandle* h = &array_[current];
836
    if (match_fn(h)) {
837
      probe++;
838
      return h;
G
Guido Tagliavini Ponce 已提交
839
    }
840
    if (abort_fn(h)) {
841
      return nullptr;
Y
Yi Wu 已提交
842
    }
843
    probe++;
844
    update_fn(h);
845 846
    current = ModTableSize(current + increment);
  }
847 848
  // We looped back.
  return nullptr;
849 850
}

851 852 853 854 855
void ClockHandleTable::Rollback(const UniqueId64x2& hashed_key,
                                const ClockHandle* h) {
  size_t current = ModTableSize(hashed_key[1]);
  size_t increment = static_cast<size_t>(hashed_key[0]) | 1U;
  for (size_t i = 0; &array_[current] != h; i++) {
856
    array_[current].displacements.fetch_sub(1, std::memory_order_relaxed);
G
Guido Tagliavini Ponce 已提交
857
    current = ModTableSize(current + increment);
Y
Yi Wu 已提交
858 859 860
  }
}

861
void ClockHandleTable::Evict(size_t requested_charge, size_t* freed_charge,
862
                             size_t* freed_count) {
863 864 865 866
  // precondition
  assert(requested_charge > 0);

  // TODO: make a tuning parameter?
867
  constexpr size_t step_size = 4;
868 869 870 871 872 873 874 875 876 877 878 879 880 881

  // First (concurrent) increment clock pointer
  uint64_t old_clock_pointer =
      clock_pointer_.fetch_add(step_size, std::memory_order_relaxed);

  // Cap the eviction effort at this thread (along with those operating in
  // parallel) circling through the whole structure kMaxCountdown times.
  // In other words, this eviction run must find something/anything that is
  // unreferenced at start of and during the eviction run that isn't reclaimed
  // by a concurrent eviction run.
  uint64_t max_clock_pointer =
      old_clock_pointer + (ClockHandle::kMaxCountdown << length_bits_);

  for (;;) {
882
    for (size_t i = 0; i < step_size; i++) {
883 884 885 886 887 888 889 890 891 892 893
      ClockHandle& h = array_[ModTableSize(Lower32of64(old_clock_pointer + i))];
      uint64_t meta = h.meta.load(std::memory_order_relaxed);

      uint64_t acquire_count = (meta >> ClockHandle::kAcquireCounterShift) &
                               ClockHandle::kCounterMask;
      uint64_t release_count = (meta >> ClockHandle::kReleaseCounterShift) &
                               ClockHandle::kCounterMask;
      if (acquire_count != release_count) {
        // Only clock update entries with no outstanding refs
        continue;
      }
894
      if (!((meta >> ClockHandle::kStateShift) &
895 896 897 898
            ClockHandle::kStateShareableBit)) {
        // Only clock update Shareable entries
        continue;
      }
899
      if ((meta >> ClockHandle::kStateShift == ClockHandle::kStateVisible) &&
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
          acquire_count > 0) {
        // Decrement clock
        uint64_t new_count = std::min(acquire_count - 1,
                                      uint64_t{ClockHandle::kMaxCountdown} - 1);
        // Compare-exchange in the decremented clock info, but
        // not aggressively
        uint64_t new_meta =
            (uint64_t{ClockHandle::kStateVisible} << ClockHandle::kStateShift) |
            (new_count << ClockHandle::kReleaseCounterShift) |
            (new_count << ClockHandle::kAcquireCounterShift);
        h.meta.compare_exchange_strong(meta, new_meta,
                                       std::memory_order_relaxed);
        continue;
      }
      // Otherwise, remove entry (either unreferenced invisible or
      // unreferenced and expired visible). Compare-exchange failing probably
      // indicates the entry was used, so skip it in that case.
      if (h.meta.compare_exchange_strong(
              meta,
              uint64_t{ClockHandle::kStateConstruction}
                  << ClockHandle::kStateShift,
              std::memory_order_acquire)) {
922 923 924 925 926
        // Took ownership.
        // Save info about h to minimize dependences between atomic updates
        // (e.g. fully relaxed Rollback after h released by marking empty)
        const UniqueId64x2 h_hashed_key = h.hashed_key;
        size_t h_total_charge = h.total_charge;
927 928 929 930 931 932 933 934 935 936 937 938
        // TODO? Delay freeing?
        h.FreeData();
#ifndef NDEBUG
        // Mark slot as empty, with assertion
        meta = h.meta.exchange(0, std::memory_order_release);
        assert(meta >> ClockHandle::kStateShift ==
               ClockHandle::kStateConstruction);
#else
        // Mark slot as empty
        h.meta.store(0, std::memory_order_release);
#endif
        *freed_count += 1;
939 940
        *freed_charge += h_total_charge;
        Rollback(h_hashed_key, &h);
941 942 943
      }
    }

944 945 946 947 948 949 950 951 952 953 954 955
    // Loop exit condition
    if (*freed_charge >= requested_charge) {
      return;
    }
    if (old_clock_pointer >= max_clock_pointer) {
      return;
    }

    // Advance clock pointer (concurrently)
    old_clock_pointer =
        clock_pointer_.fetch_add(step_size, std::memory_order_relaxed);
  }
956 957
}

G
Guido Tagliavini Ponce 已提交
958 959 960
ClockCacheShard::ClockCacheShard(
    size_t capacity, size_t estimated_value_size, bool strict_capacity_limit,
    CacheMetadataChargePolicy metadata_charge_policy)
961
    : CacheShardBase(metadata_charge_policy),
962 963 964 965 966 967 968 969
      table_(
          CalcHashBits(capacity, estimated_value_size, metadata_charge_policy),
          /*initial_charge_metadata*/ metadata_charge_policy ==
              kFullChargeCacheMetadata),
      capacity_(capacity),
      strict_capacity_limit_(strict_capacity_limit) {
  // Initial charge metadata should not exceed capacity
  assert(table_.GetUsage() <= capacity_ || capacity_ < sizeof(ClockHandle));
Y
Yi Wu 已提交
970 971
}

972
void ClockCacheShard::EraseUnRefEntries() { table_.EraseUnRefEntries(); }
Y
Yi Wu 已提交
973

974 975 976
void ClockCacheShard::ApplyToSomeEntries(
    const std::function<void(const Slice& key, void* value, size_t charge,
                             DeleterFn deleter)>& callback,
977
    size_t average_entries_per_lock, size_t* state) {
G
Guido Tagliavini Ponce 已提交
978 979 980
  // The state is essentially going to be the starting hash, which works
  // nicely even if we resize between calls because we use upper-most
  // hash bits for table indexes.
981 982
  size_t length_bits = table_.GetLengthBits();
  size_t length = table_.GetTableSize();
983

G
Guido Tagliavini Ponce 已提交
984 985 986 987 988
  assert(average_entries_per_lock > 0);
  // Assuming we are called with same average_entries_per_lock repeatedly,
  // this simplifies some logic (index_end will not overflow).
  assert(average_entries_per_lock < length || *state == 0);

989 990
  size_t index_begin = *state >> (sizeof(size_t) * 8u - length_bits);
  size_t index_end = index_begin + average_entries_per_lock;
G
Guido Tagliavini Ponce 已提交
991
  if (index_end >= length) {
992
    // Going to end.
G
Guido Tagliavini Ponce 已提交
993
    index_end = length;
994
    *state = SIZE_MAX;
995
  } else {
996
    *state = index_end << (sizeof(size_t) * 8u - length_bits);
Y
Yi Wu 已提交
997
  }
998

999
  table_.ConstApplyToEntriesRange(
1000
      [callback](const ClockHandle& h) {
1001 1002 1003
        UniqueId64x2 unhashed;
        callback(ReverseHash(h.hashed_key, &unhashed), h.value, h.total_charge,
                 h.deleter);
G
Guido Tagliavini Ponce 已提交
1004
      },
1005
      index_begin, index_end, false);
Y
Yi Wu 已提交
1006 1007
}

G
Guido Tagliavini Ponce 已提交
1008 1009 1010
int ClockCacheShard::CalcHashBits(
    size_t capacity, size_t estimated_value_size,
    CacheMetadataChargePolicy metadata_charge_policy) {
1011 1012 1013 1014 1015 1016 1017 1018
  double average_slot_charge = estimated_value_size * kLoadFactor;
  if (metadata_charge_policy == kFullChargeCacheMetadata) {
    average_slot_charge += sizeof(ClockHandle);
  }
  assert(average_slot_charge > 0.0);
  uint64_t num_slots =
      static_cast<uint64_t>(capacity / average_slot_charge + 0.999999);

1019
  int hash_bits = FloorLog2((num_slots << 1) - 1);
1020 1021 1022 1023 1024 1025 1026 1027
  if (metadata_charge_policy == kFullChargeCacheMetadata) {
    // For very small estimated value sizes, it's possible to overshoot
    while (hash_bits > 0 &&
           uint64_t{sizeof(ClockHandle)} << hash_bits > capacity) {
      hash_bits--;
    }
  }
  return hash_bits;
Y
Yi Wu 已提交
1028 1029
}

1030
void ClockCacheShard::SetCapacity(size_t capacity) {
1031 1032
  capacity_.store(capacity, std::memory_order_relaxed);
  // next Insert will take care of any necessary evictions
Y
Yi Wu 已提交
1033 1034
}

1035
void ClockCacheShard::SetStrictCapacityLimit(bool strict_capacity_limit) {
1036 1037 1038
  strict_capacity_limit_.store(strict_capacity_limit,
                               std::memory_order_relaxed);
  // next Insert will take care of any necessary evictions
Y
Yi Wu 已提交
1039 1040
}

1041 1042 1043
Status ClockCacheShard::Insert(const Slice& key, const UniqueId64x2& hashed_key,
                               void* value, size_t charge,
                               Cache::DeleterFn deleter, ClockHandle** handle,
1044
                               Cache::Priority priority) {
1045
  if (UNLIKELY(key.size() != kCacheKeySize)) {
G
Guido Tagliavini Ponce 已提交
1046 1047 1048
    return Status::NotSupported("ClockCache only supports key size " +
                                std::to_string(kCacheKeySize) + "B");
  }
1049 1050
  ClockHandleBasicData proto;
  proto.hashed_key = hashed_key;
1051 1052 1053 1054 1055 1056 1057
  proto.value = value;
  proto.deleter = deleter;
  proto.total_charge = charge;
  Status s =
      table_.Insert(proto, reinterpret_cast<ClockHandle**>(handle), priority,
                    capacity_.load(std::memory_order_relaxed),
                    strict_capacity_limit_.load(std::memory_order_relaxed));
Y
Yi Wu 已提交
1058 1059 1060
  return s;
}

1061 1062
ClockHandle* ClockCacheShard::Lookup(const Slice& key,
                                     const UniqueId64x2& hashed_key) {
1063 1064 1065
  if (UNLIKELY(key.size() != kCacheKeySize)) {
    return nullptr;
  }
1066
  return table_.Lookup(hashed_key);
Y
Yi Wu 已提交
1067 1068
}

1069
bool ClockCacheShard::Ref(ClockHandle* h) {
1070 1071 1072
  if (h == nullptr) {
    return false;
  }
1073
  table_.Ref(*h);
1074
  return true;
Y
Yi Wu 已提交
1075 1076
}

1077
bool ClockCacheShard::Release(ClockHandle* handle, bool useful,
1078
                              bool erase_if_last_ref) {
G
Guido Tagliavini Ponce 已提交
1079 1080 1081
  if (handle == nullptr) {
    return false;
  }
1082
  return table_.Release(handle, useful, erase_if_last_ref);
1083
}
1084

1085 1086
void ClockCacheShard::TEST_RefN(ClockHandle* h, size_t n) {
  table_.TEST_RefN(*h, n);
1087
}
1088

1089 1090
void ClockCacheShard::TEST_ReleaseN(ClockHandle* h, size_t n) {
  table_.TEST_ReleaseN(h, n);
1091
}
1092

1093
bool ClockCacheShard::Release(ClockHandle* handle, bool erase_if_last_ref) {
1094
  return Release(handle, /*useful=*/true, erase_if_last_ref);
1095 1096
}

1097
void ClockCacheShard::Erase(const Slice& key, const UniqueId64x2& hashed_key) {
1098 1099 1100
  if (UNLIKELY(key.size() != kCacheKeySize)) {
    return;
  }
1101
  table_.Erase(hashed_key);
G
Guido Tagliavini Ponce 已提交
1102
}
Y
Yi Wu 已提交
1103

1104
size_t ClockCacheShard::GetUsage() const { return table_.GetUsage(); }
Y
Yi Wu 已提交
1105

G
Guido Tagliavini Ponce 已提交
1106
size_t ClockCacheShard::GetPinnedUsage() const {
1107 1108
  // Computes the pinned usage by scanning the whole hash table. This
  // is slow, but avoids keeping an exact counter on the clock usage,
1109
  // i.e., the number of not externally referenced elements.
1110
  // Why avoid this counter? Because Lookup removes elements from the clock
1111 1112
  // list, so it would need to update the pinned usage every time,
  // which creates additional synchronization costs.
1113 1114 1115
  size_t table_pinned_usage = 0;
  const bool charge_metadata =
      metadata_charge_policy_ == kFullChargeCacheMetadata;
1116
  table_.ConstApplyToEntriesRange(
1117 1118
      [&table_pinned_usage, charge_metadata](const ClockHandle& h) {
        uint64_t meta = h.meta.load(std::memory_order_relaxed);
1119
        uint64_t refcount = GetRefcount(meta);
1120 1121 1122 1123 1124 1125 1126
        // Holding one ref for ConstApplyToEntriesRange
        assert(refcount > 0);
        if (refcount > 1) {
          table_pinned_usage += h.total_charge;
          if (charge_metadata) {
            table_pinned_usage += sizeof(ClockHandle);
          }
1127 1128 1129 1130
        }
      },
      0, table_.GetTableSize(), true);

1131 1132 1133 1134 1135 1136 1137 1138 1139
  return table_pinned_usage + table_.GetDetachedUsage();
}

size_t ClockCacheShard::GetOccupancyCount() const {
  return table_.GetOccupancy();
}

size_t ClockCacheShard::GetTableAddressCount() const {
  return table_.GetTableSize();
G
Guido Tagliavini Ponce 已提交
1140
}
Y
Yi Wu 已提交
1141

1142 1143 1144
HyperClockCache::HyperClockCache(
    size_t capacity, size_t estimated_value_size, int num_shard_bits,
    bool strict_capacity_limit,
1145 1146 1147 1148
    CacheMetadataChargePolicy metadata_charge_policy,
    std::shared_ptr<MemoryAllocator> memory_allocator)
    : ShardedCache(capacity, num_shard_bits, strict_capacity_limit,
                   std::move(memory_allocator)) {
1149 1150
  assert(estimated_value_size > 0 ||
         metadata_charge_policy != kDontChargeCacheMetadata);
1151 1152
  // TODO: should not need to go through two levels of pointer indirection to
  // get to table entries
1153 1154 1155 1156 1157
  size_t per_shard = GetPerShardCapacity();
  InitShards([=](ClockCacheShard* cs) {
    new (cs) ClockCacheShard(per_shard, estimated_value_size,
                             strict_capacity_limit, metadata_charge_policy);
  });
G
Guido Tagliavini Ponce 已提交
1158
}
Y
Yi Wu 已提交
1159

1160
void* HyperClockCache::Value(Handle* handle) {
G
Guido Tagliavini Ponce 已提交
1161 1162
  return reinterpret_cast<const ClockHandle*>(handle)->value;
}
1163

1164
size_t HyperClockCache::GetCharge(Handle* handle) const {
1165
  return reinterpret_cast<const ClockHandle*>(handle)->total_charge;
G
Guido Tagliavini Ponce 已提交
1166
}
Y
Yi Wu 已提交
1167

1168
Cache::DeleterFn HyperClockCache::GetDeleter(Handle* handle) const {
G
Guido Tagliavini Ponce 已提交
1169 1170 1171
  auto h = reinterpret_cast<const ClockHandle*>(handle);
  return h->deleter;
}
1172

1173
}  // namespace hyper_clock_cache
Y
Yi Wu 已提交
1174

1175
// DEPRECATED (see public API)
1176
std::shared_ptr<Cache> NewClockCache(
1177
    size_t capacity, int num_shard_bits, bool strict_capacity_limit,
1178
    CacheMetadataChargePolicy metadata_charge_policy) {
1179 1180 1181 1182
  return NewLRUCache(capacity, num_shard_bits, strict_capacity_limit,
                     /* high_pri_pool_ratio */ 0.5, nullptr,
                     kDefaultToAdaptiveMutex, metadata_charge_policy,
                     /* low_pri_pool_ratio */ 0.0);
1183 1184
}

1185 1186 1187
std::shared_ptr<Cache> HyperClockCacheOptions::MakeSharedCache() const {
  auto my_num_shard_bits = num_shard_bits;
  if (my_num_shard_bits >= 20) {
G
Guido Tagliavini Ponce 已提交
1188 1189
    return nullptr;  // The cache cannot be sharded into too many fine pieces.
  }
1190
  if (my_num_shard_bits < 0) {
1191 1192 1193
    // Use larger shard size to reduce risk of large entries clustering
    // or skewing individual shards.
    constexpr size_t min_shard_size = 32U * 1024U * 1024U;
1194
    my_num_shard_bits = GetDefaultCacheShardBits(capacity, min_shard_size);
1195
  }
1196 1197
  return std::make_shared<hyper_clock_cache::HyperClockCache>(
      capacity, estimated_entry_charge, my_num_shard_bits,
1198
      strict_capacity_limit, metadata_charge_policy, memory_allocator);
Y
Yi Wu 已提交
1199 1200
}

1201
}  // namespace ROCKSDB_NAMESPACE