clock_cache.cc 59.2 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

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

16
#include "cache/cache_key.h"
17
#include "cache/secondary_cache_adapter.h"
18
#include "logging/logging.h"
G
Guido Tagliavini Ponce 已提交
19
#include "monitoring/perf_context_imp.h"
20
#include "monitoring/statistics_impl.h"
G
Guido Tagliavini Ponce 已提交
21
#include "port/lang.h"
22
#include "rocksdb/env.h"
G
Guido Tagliavini Ponce 已提交
23 24 25
#include "util/hash.h"
#include "util/math.h"
#include "util/random.h"
Y
Yi Wu 已提交
26

G
Guido Tagliavini Ponce 已提交
27
namespace ROCKSDB_NAMESPACE {
Y
Yi Wu 已提交
28

29
namespace clock_cache {
Y
Yi Wu 已提交
30

31
namespace {
32 33 34 35 36 37
inline uint64_t GetRefcount(uint64_t meta) {
  return ((meta >> ClockHandle::kAcquireCounterShift) -
          (meta >> ClockHandle::kReleaseCounterShift)) &
         ClockHandle::kCounterMask;
}

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
inline uint64_t GetInitialCountdown(Cache::Priority priority) {
  // Set initial clock data from priority
  // TODO: configuration parameters for priority handling and clock cycle
  // count?
  switch (priority) {
    case Cache::Priority::HIGH:
      return ClockHandle::kHighCountdown;
    default:
      assert(false);
      FALLTHROUGH_INTENDED;
    case Cache::Priority::LOW:
      return ClockHandle::kLowCountdown;
    case Cache::Priority::BOTTOM:
      return ClockHandle::kBottomCountdown;
  }
}

55
inline void MarkEmpty(ClockHandle& h) {
56 57 58 59 60 61 62 63 64 65
#ifndef NDEBUG
  // Mark slot as empty, with assertion
  uint64_t 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
}

66 67 68 69 70 71 72 73 74 75
inline void FreeDataMarkEmpty(ClockHandle& h, MemoryAllocator* allocator) {
  // NOTE: in theory there's more room for parallelism if we copy the handle
  // data and delay actions like this until after marking the entry as empty,
  // but performance tests only show a regression by copying the few words
  // of data.
  h.FreeData(allocator);

  MarkEmpty(h);
}

76 77 78 79 80 81 82 83 84 85 86 87 88 89 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
inline bool ClockUpdate(ClockHandle& h) {
  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;
  // fprintf(stderr, "ClockUpdate @ %p: %lu %lu %u\n", &h, acquire_count,
  // release_count, (unsigned)(meta >> ClockHandle::kStateShift));
  if (acquire_count != release_count) {
    // Only clock update entries with no outstanding refs
    return false;
  }
  if (!((meta >> ClockHandle::kStateShift) & ClockHandle::kStateShareableBit)) {
    // Only clock update Shareable entries
    return false;
  }
  if ((meta >> ClockHandle::kStateShift == ClockHandle::kStateVisible) &&
      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);
    return false;
  }
  // Otherwise, remove entry (either unreferenced invisible or
  // unreferenced and expired visible).
  if (h.meta.compare_exchange_strong(
          meta,
          uint64_t{ClockHandle::kStateConstruction} << ClockHandle::kStateShift,
          std::memory_order_acquire)) {
    // Took ownership.
    return true;
  } else {
    // Compare-exchange failing probably
    // indicates the entry was used, so skip it in that case.
    return false;
  }
}

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 164 165 166 167 168 169 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
// 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);
  }
}

195 196 197 198 199 200 201 202 203 204 205 206 207 208 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 273 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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
inline bool BeginSlotInsert(const ClockHandleBasicData& proto, ClockHandle& h,
                            uint64_t initial_countdown, bool* already_matches) {
  assert(*already_matches == false);
  // 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.
    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
    if (h.hashed_key == proto.hashed_key) {
      // 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)
      *already_matches = true;
      return false;
    } 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/FIXME?: 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;
}

inline void FinishSlotInsert(const ClockHandleBasicData& proto, ClockHandle& h,
                             uint64_t initial_countdown, bool keep_ref) {
  // Save data fields
  ClockHandleBasicData* h_alias = &h;
  *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 - keep_ref)
              << ClockHandle::kReleaseCounterShift;

#ifndef NDEBUG
  // Save the state transition, with assertion
  uint64_t 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
}

bool TryInsert(const ClockHandleBasicData& proto, ClockHandle& h,
               uint64_t initial_countdown, bool keep_ref,
               bool* already_matches) {
  bool b = BeginSlotInsert(proto, h, initial_countdown, already_matches);
  if (b) {
    FinishSlotInsert(proto, h, initial_countdown, keep_ref);
  }
  return b;
}

}  // namespace

void ClockHandleBasicData::FreeData(MemoryAllocator* allocator) const {
  if (helper->del_cb) {
    helper->del_cb(value, allocator);
  }
}

template <class HandleImpl>
HandleImpl* BaseClockTable::StandaloneInsert(
    const ClockHandleBasicData& proto) {
  // Heap allocated separate from table
  HandleImpl* h = new HandleImpl();
  ClockHandleBasicData* h_alias = h;
  *h_alias = proto;
  h->SetStandalone();
  // Single reference (standalone 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 how much of usage is standalone
  standalone_usage_.fetch_add(proto.GetTotalCharge(),
                              std::memory_order_relaxed);
  return h;
}

template <class Table>
typename Table::HandleImpl* BaseClockTable::CreateStandalone(
    ClockHandleBasicData& proto, size_t capacity, bool strict_capacity_limit,
    bool allow_uncharged) {
  Table& derived = static_cast<Table&>(*this);
  typename Table::InsertState state;
  derived.StartInsert(state);

  const size_t total_charge = proto.GetTotalCharge();
  if (strict_capacity_limit) {
    Status s = ChargeUsageMaybeEvictStrict<Table>(
        total_charge, capacity,
        /*need_evict_for_occupancy=*/false, state);
    if (!s.ok()) {
      if (allow_uncharged) {
        proto.total_charge = 0;
      } else {
        return nullptr;
      }
    }
  } else {
    // Case strict_capacity_limit == false
    bool success = ChargeUsageMaybeEvictNonStrict<Table>(
        total_charge, capacity,
        /*need_evict_for_occupancy=*/false, state);
    if (!success) {
      // Force the issue
      usage_.fetch_add(total_charge, std::memory_order_relaxed);
    }
  }

  return StandaloneInsert<typename Table::HandleImpl>(proto);
}

template <class Table>
Status BaseClockTable::ChargeUsageMaybeEvictStrict(
    size_t total_charge, size_t capacity, bool need_evict_for_occupancy,
    typename Table::InsertState& state) {
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
  if (total_charge > capacity) {
    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;
    size_t evicted_count = 0;
384 385
    static_cast<Table*>(this)->Evict(request_evict_charge, &evicted_charge,
                                     &evicted_count, state);
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
    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);
      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);
  }
  return Status::OK();
}

414 415 416 417
template <class Table>
inline bool BaseClockTable::ChargeUsageMaybeEvictNonStrict(
    size_t total_charge, size_t capacity, bool need_evict_for_occupancy,
    typename Table::InsertState& state) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  // 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, such as the compare_exchange used with strict
      // capacity limit.
      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;
  size_t evicted_count = 0;
  if (need_evict_charge > 0) {
454 455
    static_cast<Table*>(this)->Evict(need_evict_charge, &evicted_charge,
                                     &evicted_count, state);
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    // Deal with potential occupancy deficit
    if (UNLIKELY(need_evict_for_occupancy) && evicted_count == 0) {
      assert(evicted_charge == 0);
      // Can't meet occupancy requirement
      return false;
    } 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);
  // Success
  return true;
}

474 475 476 477 478 479 480 481 482 483
template <class Table>
Status BaseClockTable::Insert(const ClockHandleBasicData& proto,
                              typename Table::HandleImpl** handle,
                              Cache::Priority priority, size_t capacity,
                              bool strict_capacity_limit) {
  using HandleImpl = typename Table::HandleImpl;
  Table& derived = static_cast<Table&>(*this);

  typename Table::InsertState state;
  derived.StartInsert(state);
484

485 486
  // Do we have the available occupancy? Optimistically assume we do
  // and deal with it if we don't.
487
  size_t old_occupancy = occupancy_.fetch_add(1, std::memory_order_acquire);
488
  // Whether we over-committed and need an eviction to make up for it
489 490
  bool need_evict_for_occupancy =
      !derived.GrowIfNeeded(old_occupancy + 1, state);
491 492 493

  // Usage/capacity handling is somewhat different depending on
  // strict_capacity_limit, but mostly pessimistic.
494
  bool use_standalone_insert = false;
495
  const size_t total_charge = proto.GetTotalCharge();
496
  if (strict_capacity_limit) {
497 498
    Status s = ChargeUsageMaybeEvictStrict<Table>(
        total_charge, capacity, need_evict_for_occupancy, state);
499
    if (!s.ok()) {
500 501
      // Revert occupancy
      occupancy_.fetch_sub(1, std::memory_order_relaxed);
502
      return s;
503 504 505
    }
  } else {
    // Case strict_capacity_limit == false
506 507
    bool success = ChargeUsageMaybeEvictNonStrict<Table>(
        total_charge, capacity, need_evict_for_occupancy, state);
508
    if (!success) {
509 510
      // Revert occupancy
      occupancy_.fetch_sub(1, std::memory_order_relaxed);
511 512 513
      if (handle == nullptr) {
        // Don't insert the entry but still return ok, as if the entry
        // inserted into cache and evicted immediately.
514
        proto.FreeData(allocator_);
515
        return Status::OK();
516
      } else {
517
        // Need to track usage of fallback standalone insert
518
        usage_.fetch_add(total_charge, std::memory_order_relaxed);
519
        use_standalone_insert = true;
520 521 522 523
      }
    }
  }

524
  if (!use_standalone_insert) {
525 526 527 528 529 530 531 532
    // 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.

533
    uint64_t initial_countdown = GetInitialCountdown(priority);
534 535
    assert(initial_countdown > 0);

536 537
    HandleImpl* e =
        derived.DoInsert(proto, initial_countdown, handle != nullptr, state);
538

539
    if (e) {
540 541 542 543 544 545
      // Successfully inserted
      if (handle) {
        *handle = e;
      }
      return Status::OK();
    }
546
    // Not inserted
547 548
    // Revert occupancy
    occupancy_.fetch_sub(1, std::memory_order_relaxed);
549
    // Maybe fall back on standalone insert
550
    if (handle == nullptr) {
551 552 553 554
      // Revert usage
      usage_.fetch_sub(total_charge, std::memory_order_relaxed);
      // No underflow
      assert(usage_.load(std::memory_order_relaxed) < SIZE_MAX / 2);
555
      // As if unrefed entry immdiately evicted
556
      proto.FreeData(allocator_);
557 558
      return Status::OK();
    }
559 560

    use_standalone_insert = true;
561 562
  }

563 564
  // Run standalone insert
  assert(use_standalone_insert);
565

566
  *handle = StandaloneInsert<HandleImpl>(proto);
567 568 569 570

  // 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
571 572
  // didn't go into the table (instead "standalone"), which could be redundant
  // Insert or some other reason (use_standalone_insert reasons above).
573 574 575
  return Status::OkOverwritten();
}

576 577 578 579 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 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
void BaseClockTable::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);
  // Must have already had a reference
  assert(GetRefcount(old_meta) > 0);
  (void)old_meta;
}

#ifndef NDEBUG
void BaseClockTable::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;
}

void BaseClockTable::TEST_ReleaseNMinus1(ClockHandle* h, size_t n) {
  assert(n > 0);

  // Like n-1 Releases, but assumes one more will happen in the caller to take
  // care of anything like erasing an unreferenced, invisible entry.
  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;
}
#endif

HyperClockTable::HyperClockTable(
    size_t capacity, bool /*strict_capacity_limit*/,
    CacheMetadataChargePolicy metadata_charge_policy,
    MemoryAllocator* allocator,
    const Cache::EvictionCallback* eviction_callback, const uint32_t* hash_seed,
    const Opts& opts)
    : BaseClockTable(metadata_charge_policy, allocator, eviction_callback,
                     hash_seed),
      length_bits_(CalcHashBits(capacity, opts.estimated_value_size,
                                metadata_charge_policy)),
      length_bits_mask_((size_t{1} << length_bits_) - 1),
      occupancy_limit_(static_cast<size_t>((uint64_t{1} << length_bits_) *
                                           kStrictLoadFactor)),
      array_(new HandleImpl[size_t{1} << length_bits_]) {
  if (metadata_charge_policy ==
      CacheMetadataChargePolicy::kFullChargeCacheMetadata) {
    usage_ += size_t{GetTableSize()} * sizeof(HandleImpl);
  }

  static_assert(sizeof(HandleImpl) == 64U,
                "Expecting size / alignment with common cache line size");
}

HyperClockTable::~HyperClockTable() {
  // Assumes there are no references or active operations on any slot/element
  // in the table.
  for (size_t i = 0; i < GetTableSize(); i++) {
    HandleImpl& h = array_[i];
    switch (h.meta >> ClockHandle::kStateShift) {
      case ClockHandle::kStateEmpty:
        // noop
        break;
      case ClockHandle::kStateInvisible:  // rare but possible
      case ClockHandle::kStateVisible:
        assert(GetRefcount(h.meta) == 0);
        h.FreeData(allocator_);
#ifndef NDEBUG
        Rollback(h.hashed_key, &h);
        ReclaimEntryUsage(h.GetTotalCharge());
#endif
        break;
      // otherwise
      default:
        assert(false);
        break;
657 658 659
    }
  }

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
#ifndef NDEBUG
  for (size_t i = 0; i < GetTableSize(); i++) {
    assert(array_[i].displacements.load() == 0);
  }
#endif

  assert(usage_.load() == 0 ||
         usage_.load() == size_t{GetTableSize()} * sizeof(HandleImpl));
  assert(occupancy_ == 0);
}

void HyperClockTable::StartInsert(InsertState&) {}

bool HyperClockTable::GrowIfNeeded(size_t new_occupancy, InsertState&) {
  return new_occupancy <= occupancy_limit_;
}

HyperClockTable::HandleImpl* HyperClockTable::DoInsert(
    const ClockHandleBasicData& proto, uint64_t initial_countdown,
    bool keep_ref, InsertState&) {
  bool already_matches = false;
  HandleImpl* e = FindSlot(
      proto.hashed_key,
      [&](HandleImpl* h) {
684 685
        return TryInsert(proto, *h, initial_countdown, keep_ref,
                         &already_matches);
686 687
      },
      [&](HandleImpl* h) {
688 689 690 691 692 693 694 695
        if (already_matches) {
          // Stop searching & roll back displacements
          Rollback(proto.hashed_key, h);
          return true;
        } else {
          // Keep going
          return false;
        }
696
      },
697 698 699 700 701 702 703 704 705 706 707
      [&](HandleImpl* h, bool is_last) {
        if (is_last) {
          // Search is ending. Roll back displacements
          Rollback(proto.hashed_key, h);
        } else {
          h->displacements.fetch_add(1, std::memory_order_relaxed);
        }
      });
  if (already_matches) {
    // Insertion skipped
    return nullptr;
708
  }
709
  if (e != nullptr) {
710 711 712
    // Successfully inserted
    return e;
  }
713 714 715 716 717 718 719 720
  // Else, no available slot found. Occupancy check 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);
721
  return nullptr;
722 723
}

724 725 726
HyperClockTable::HandleImpl* HyperClockTable::Lookup(
    const UniqueId64x2& hashed_key) {
  HandleImpl* e = FindSlot(
727
      hashed_key,
728
      [&](HandleImpl* h) {
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
        // 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
758
          if (h->hashed_key == hashed_key) {
759
            // Match
760
            return true;
761 762 763 764
          } else {
            // Mismatch. Pretend we never took the reference
            old_meta = h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                                         std::memory_order_release);
765
          }
766 767 768 769 770 771 772 773 774 775 776 777
        } 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.
778
        }
779
        (void)old_meta;
780 781
        return false;
      },
782
      [&](HandleImpl* h) {
783 784
        return h->displacements.load(std::memory_order_relaxed) == 0;
      },
785
      [&](HandleImpl* /*h*/, bool /*is_last*/) {});
786 787

  return e;
G
Guido Tagliavini Ponce 已提交
788
}
Y
Yi Wu 已提交
789

790 791
bool HyperClockTable::Release(HandleImpl* h, bool useful,
                              bool erase_if_last_ref) {
792 793 794 795
  // 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_.
796

797 798 799 800 801
  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);
802
  } else {
803 804 805
    // Decrement acquire counter to pretend it never happened
    old_meta = h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                                 std::memory_order_release);
806
  }
Y
Yi Wu 已提交
807

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  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 {
826
      if (GetRefcount(old_meta) != 0) {
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
        // 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
845
    size_t total_charge = h->GetTotalCharge();
846
    if (UNLIKELY(h->IsStandalone())) {
847
      h->FreeData(allocator_);
848
      // Delete standalone handle
849
      delete h;
850
      standalone_usage_.fetch_sub(total_charge, std::memory_order_relaxed);
851
      usage_.fetch_sub(total_charge, std::memory_order_relaxed);
852
    } else {
853
      Rollback(h->hashed_key, h);
854
      FreeDataMarkEmpty(*h, allocator_);
855
      ReclaimEntryUsage(total_charge);
856
    }
857 858 859 860 861
    return true;
  } else {
    // Correct for possible (but rare) overflow
    CorrectNearOverflow(old_meta, h->meta);
    return false;
862 863 864
  }
}

865
#ifndef NDEBUG
866
void HyperClockTable::TEST_ReleaseN(HandleImpl* h, size_t n) {
867
  if (n > 0) {
868 869
    // Do n-1 simple releases first
    TEST_ReleaseNMinus1(h, n);
870

871
    // Then the last release might be more involved
872 873
    Release(h, /*useful*/ true, /*erase_if_last_ref*/ false);
  }
874
}
875
#endif
876

877
void HyperClockTable::Erase(const UniqueId64x2& hashed_key) {
878
  (void)FindSlot(
879
      hashed_key,
880
      [&](HandleImpl* h) {
881 882 883 884 885 886 887 888
        // 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
889
          if (h->hashed_key == hashed_key) {
890 891 892 893 894 895 896 897 898
            // 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 (;;) {
899
              uint64_t refcount = GetRefcount(old_meta);
900 901 902 903 904 905 906 907
              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(
908 909 910 911
                             old_meta,
                             uint64_t{ClockHandle::kStateConstruction}
                                 << ClockHandle::kStateShift,
                             std::memory_order_acq_rel)) {
912
                // Took ownership
913
                assert(hashed_key == h->hashed_key);
914
                size_t total_charge = h->GetTotalCharge();
915
                FreeDataMarkEmpty(*h, allocator_);
916 917 918
                ReclaimEntryUsage(total_charge);
                // We already have a copy of hashed_key in this case, so OK to
                // delay Rollback until after releasing the entry
919
                Rollback(hashed_key, h);
920 921
                break;
              }
922
            }
923 924 925 926
          } else {
            // Mismatch. Pretend we never took the reference
            h->meta.fetch_sub(ClockHandle::kAcquireIncrement,
                              std::memory_order_release);
927
          }
928 929 930 931 932 933 934 935 936 937
        } 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.
938 939 940
        }
        return false;
      },
941
      [&](HandleImpl* h) {
942 943
        return h->displacements.load(std::memory_order_relaxed) == 0;
      },
944
      [&](HandleImpl* /*h*/, bool /*is_last*/) {});
G
Guido Tagliavini Ponce 已提交
945
}
Y
Yi Wu 已提交
946

947 948
void HyperClockTable::ConstApplyToEntriesRange(
    std::function<void(const HandleImpl&)> func, size_t index_begin,
949
    size_t index_end, bool apply_if_will_be_deleted) const {
950 951 952
  uint64_t check_state_mask = ClockHandle::kStateShareableBit;
  if (!apply_if_will_be_deleted) {
    check_state_mask |= ClockHandle::kStateVisibleBit;
953 954
  }

955
  for (size_t i = index_begin; i < index_end; i++) {
956
    HandleImpl& h = array_[i];
957

958
    // Note: to avoid using compare_exchange, we have to be extra careful.
959 960 961
    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) {
962 963 964
      // 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.)
965 966
      old_meta = h.meta.fetch_add(ClockHandle::kAcquireIncrement,
                                  std::memory_order_acquire);
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
      // 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.
983 984
      }
    }
985
  }
G
Guido Tagliavini Ponce 已提交
986
}
Y
Yi Wu 已提交
987

988
void HyperClockTable::EraseUnRefEntries() {
989
  for (size_t i = 0; i <= this->length_bits_mask_; i++) {
990
    HandleImpl& h = array_[i];
991 992 993 994

    uint64_t old_meta = h.meta.load(std::memory_order_relaxed);
    if (old_meta & (uint64_t{ClockHandle::kStateShareableBit}
                    << ClockHandle::kStateShift) &&
995
        GetRefcount(old_meta) == 0 &&
996 997 998 999 1000
        h.meta.compare_exchange_strong(old_meta,
                                       uint64_t{ClockHandle::kStateConstruction}
                                           << ClockHandle::kStateShift,
                                       std::memory_order_acquire)) {
      // Took ownership
1001 1002
      size_t total_charge = h.GetTotalCharge();
      Rollback(h.hashed_key, &h);
1003
      FreeDataMarkEmpty(h, allocator_);
1004
      ReclaimEntryUsage(total_charge);
1005
    }
1006
  }
G
Guido Tagliavini Ponce 已提交
1007 1008
}

1009
template <typename MatchFn, typename AbortFn, typename UpdateFn>
1010
inline HyperClockTable::HandleImpl* HyperClockTable::FindSlot(
1011 1012
    const UniqueId64x2& hashed_key, MatchFn match_fn, AbortFn abort_fn,
    UpdateFn update_fn) {
1013 1014
  // NOTE: upper 32 bits of hashed_key[0] is used for sharding
  //
1015 1016 1017 1018
  // 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.
1019
  size_t base = static_cast<size_t>(hashed_key[1]);
1020 1021 1022
  // 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.
1023 1024
  // TODO: we could also reconsider linear probing, though locality benefits
  // are limited because each slot is a full cache line
1025
  size_t increment = static_cast<size_t>(hashed_key[0]) | 1U;
1026 1027 1028 1029
  size_t first = ModTableSize(base);
  size_t current = first;
  bool is_last;
  do {
1030
    HandleImpl* h = &array_[current];
1031
    if (match_fn(h)) {
1032
      return h;
G
Guido Tagliavini Ponce 已提交
1033
    }
1034
    if (abort_fn(h)) {
1035
      return nullptr;
Y
Yi Wu 已提交
1036
    }
1037
    current = ModTableSize(current + increment);
1038 1039 1040
    is_last = current == first;
    update_fn(h, is_last);
  } while (!is_last);
1041 1042
  // We looped back.
  return nullptr;
1043 1044
}

1045 1046
inline void HyperClockTable::Rollback(const UniqueId64x2& hashed_key,
                                      const HandleImpl* h) {
1047 1048
  size_t current = ModTableSize(hashed_key[1]);
  size_t increment = static_cast<size_t>(hashed_key[0]) | 1U;
1049
  while (&array_[current] != h) {
1050
    array_[current].displacements.fetch_sub(1, std::memory_order_relaxed);
G
Guido Tagliavini Ponce 已提交
1051
    current = ModTableSize(current + increment);
Y
Yi Wu 已提交
1052 1053 1054
  }
}

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
inline void HyperClockTable::ReclaimEntryUsage(size_t total_charge) {
  auto old_occupancy = occupancy_.fetch_sub(1U, std::memory_order_release);
  (void)old_occupancy;
  // No underflow
  assert(old_occupancy > 0);
  auto old_usage = usage_.fetch_sub(total_charge, std::memory_order_relaxed);
  (void)old_usage;
  // No underflow
  assert(old_usage >= total_charge);
}

inline void HyperClockTable::Evict(size_t requested_charge,
1067 1068
                                   size_t* freed_charge, size_t* freed_count,
                                   InsertState&) {
1069 1070 1071 1072
  // precondition
  assert(requested_charge > 0);

  // TODO: make a tuning parameter?
1073
  constexpr size_t step_size = 4;
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086

  // 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_);

1087 1088 1089
  // For key reconstructed from hash
  UniqueId64x2 unhashed;

1090
  for (;;) {
1091
    for (size_t i = 0; i < step_size; i++) {
1092 1093 1094 1095 1096
      HandleImpl& h = array_[ModTableSize(Lower32of64(old_clock_pointer + i))];
      bool evicting = ClockUpdate(h);
      if (evicting) {
        Rollback(h.hashed_key, &h);
        *freed_charge += h.GetTotalCharge();
1097
        *freed_count += 1;
1098 1099 1100 1101
        bool took_ownership = false;
        if (eviction_callback_) {
          took_ownership =
              eviction_callback_(ClockCacheShard<HyperClockTable>::ReverseHash(
1102
                                     h.GetHash(), &unhashed, hash_seed_),
1103 1104 1105 1106 1107 1108
                                 reinterpret_cast<Cache::Handle*>(&h));
        }
        if (!took_ownership) {
          h.FreeData(allocator_);
        }
        MarkEmpty(h);
1109 1110 1111
      }
    }

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    // 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);
  }
1124 1125
}

1126 1127 1128 1129
template <class Table>
ClockCacheShard<Table>::ClockCacheShard(
    size_t capacity, bool strict_capacity_limit,
    CacheMetadataChargePolicy metadata_charge_policy,
1130
    MemoryAllocator* allocator,
1131
    const Cache::EvictionCallback* eviction_callback, const uint32_t* hash_seed,
1132
    const typename Table::Opts& opts)
1133
    : CacheShardBase(metadata_charge_policy),
1134
      table_(capacity, strict_capacity_limit, metadata_charge_policy, allocator,
1135
             eviction_callback, hash_seed, opts),
1136 1137 1138
      capacity_(capacity),
      strict_capacity_limit_(strict_capacity_limit) {
  // Initial charge metadata should not exceed capacity
1139
  assert(table_.GetUsage() <= capacity_ || capacity_ < sizeof(HandleImpl));
Y
Yi Wu 已提交
1140 1141
}

1142 1143 1144 1145
template <class Table>
void ClockCacheShard<Table>::EraseUnRefEntries() {
  table_.EraseUnRefEntries();
}
Y
Yi Wu 已提交
1146

1147 1148
template <class Table>
void ClockCacheShard<Table>::ApplyToSomeEntries(
1149 1150 1151
    const std::function<void(const Slice& key, Cache::ObjectPtr value,
                             size_t charge,
                             const Cache::CacheItemHelper* helper)>& callback,
1152
    size_t average_entries_per_lock, size_t* state) {
G
Guido Tagliavini Ponce 已提交
1153 1154 1155
  // 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.
1156 1157
  size_t length_bits = table_.GetLengthBits();
  size_t length = table_.GetTableSize();
1158

G
Guido Tagliavini Ponce 已提交
1159 1160 1161 1162 1163
  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);

1164 1165
  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 已提交
1166
  if (index_end >= length) {
1167
    // Going to end.
G
Guido Tagliavini Ponce 已提交
1168
    index_end = length;
1169
    *state = SIZE_MAX;
1170
  } else {
1171
    *state = index_end << (sizeof(size_t) * 8u - length_bits);
Y
Yi Wu 已提交
1172
  }
1173

1174
  auto hash_seed = table_.GetHashSeed();
1175
  table_.ConstApplyToEntriesRange(
1176
      [callback, hash_seed](const HandleImpl& h) {
1177
        UniqueId64x2 unhashed;
1178
        callback(ReverseHash(h.hashed_key, &unhashed, hash_seed), h.value,
1179
                 h.GetTotalCharge(), h.helper);
G
Guido Tagliavini Ponce 已提交
1180
      },
1181
      index_begin, index_end, false);
Y
Yi Wu 已提交
1182 1183
}

1184
int HyperClockTable::CalcHashBits(
G
Guido Tagliavini Ponce 已提交
1185 1186
    size_t capacity, size_t estimated_value_size,
    CacheMetadataChargePolicy metadata_charge_policy) {
1187 1188
  double average_slot_charge = estimated_value_size * kLoadFactor;
  if (metadata_charge_policy == kFullChargeCacheMetadata) {
1189
    average_slot_charge += sizeof(HandleImpl);
1190 1191 1192 1193 1194
  }
  assert(average_slot_charge > 0.0);
  uint64_t num_slots =
      static_cast<uint64_t>(capacity / average_slot_charge + 0.999999);

1195
  int hash_bits = FloorLog2((num_slots << 1) - 1);
1196 1197 1198
  if (metadata_charge_policy == kFullChargeCacheMetadata) {
    // For very small estimated value sizes, it's possible to overshoot
    while (hash_bits > 0 &&
1199
           uint64_t{sizeof(HandleImpl)} << hash_bits > capacity) {
1200 1201 1202 1203
      hash_bits--;
    }
  }
  return hash_bits;
Y
Yi Wu 已提交
1204 1205
}

1206 1207
template <class Table>
void ClockCacheShard<Table>::SetCapacity(size_t capacity) {
1208 1209
  capacity_.store(capacity, std::memory_order_relaxed);
  // next Insert will take care of any necessary evictions
Y
Yi Wu 已提交
1210 1211
}

1212 1213 1214
template <class Table>
void ClockCacheShard<Table>::SetStrictCapacityLimit(
    bool strict_capacity_limit) {
1215 1216 1217
  strict_capacity_limit_.store(strict_capacity_limit,
                               std::memory_order_relaxed);
  // next Insert will take care of any necessary evictions
Y
Yi Wu 已提交
1218 1219
}

1220 1221 1222
template <class Table>
Status ClockCacheShard<Table>::Insert(const Slice& key,
                                      const UniqueId64x2& hashed_key,
1223 1224 1225
                                      Cache::ObjectPtr value,
                                      const Cache::CacheItemHelper* helper,
                                      size_t charge, HandleImpl** handle,
1226
                                      Cache::Priority priority) {
1227
  if (UNLIKELY(key.size() != kCacheKeySize)) {
G
Guido Tagliavini Ponce 已提交
1228 1229 1230
    return Status::NotSupported("ClockCache only supports key size " +
                                std::to_string(kCacheKeySize) + "B");
  }
1231 1232
  ClockHandleBasicData proto;
  proto.hashed_key = hashed_key;
1233
  proto.value = value;
1234
  proto.helper = helper;
1235
  proto.total_charge = charge;
1236 1237 1238
  return table_.template Insert<Table>(
      proto, handle, priority, capacity_.load(std::memory_order_relaxed),
      strict_capacity_limit_.load(std::memory_order_relaxed));
1239 1240 1241
}

template <class Table>
1242 1243 1244
typename Table::HandleImpl* ClockCacheShard<Table>::CreateStandalone(
    const Slice& key, const UniqueId64x2& hashed_key, Cache::ObjectPtr obj,
    const Cache::CacheItemHelper* helper, size_t charge, bool allow_uncharged) {
1245 1246 1247 1248 1249 1250 1251 1252
  if (UNLIKELY(key.size() != kCacheKeySize)) {
    return nullptr;
  }
  ClockHandleBasicData proto;
  proto.hashed_key = hashed_key;
  proto.value = obj;
  proto.helper = helper;
  proto.total_charge = charge;
1253
  return table_.template CreateStandalone<Table>(
1254 1255
      proto, capacity_.load(std::memory_order_relaxed),
      strict_capacity_limit_.load(std::memory_order_relaxed), allow_uncharged);
Y
Yi Wu 已提交
1256 1257
}

1258 1259 1260
template <class Table>
typename ClockCacheShard<Table>::HandleImpl* ClockCacheShard<Table>::Lookup(
    const Slice& key, const UniqueId64x2& hashed_key) {
1261 1262 1263
  if (UNLIKELY(key.size() != kCacheKeySize)) {
    return nullptr;
  }
1264
  return table_.Lookup(hashed_key);
Y
Yi Wu 已提交
1265 1266
}

1267 1268
template <class Table>
bool ClockCacheShard<Table>::Ref(HandleImpl* h) {
1269 1270 1271
  if (h == nullptr) {
    return false;
  }
1272
  table_.Ref(*h);
1273
  return true;
Y
Yi Wu 已提交
1274 1275
}

1276 1277 1278
template <class Table>
bool ClockCacheShard<Table>::Release(HandleImpl* handle, bool useful,
                                     bool erase_if_last_ref) {
G
Guido Tagliavini Ponce 已提交
1279 1280 1281
  if (handle == nullptr) {
    return false;
  }
1282
  return table_.Release(handle, useful, erase_if_last_ref);
1283
}
1284

1285
#ifndef NDEBUG
1286 1287
template <class Table>
void ClockCacheShard<Table>::TEST_RefN(HandleImpl* h, size_t n) {
1288
  table_.TEST_RefN(*h, n);
1289
}
1290

1291 1292
template <class Table>
void ClockCacheShard<Table>::TEST_ReleaseN(HandleImpl* h, size_t n) {
1293
  table_.TEST_ReleaseN(h, n);
1294
}
1295
#endif
1296

1297 1298 1299
template <class Table>
bool ClockCacheShard<Table>::Release(HandleImpl* handle,
                                     bool erase_if_last_ref) {
1300
  return Release(handle, /*useful=*/true, erase_if_last_ref);
1301 1302
}

1303 1304 1305
template <class Table>
void ClockCacheShard<Table>::Erase(const Slice& key,
                                   const UniqueId64x2& hashed_key) {
1306 1307 1308
  if (UNLIKELY(key.size() != kCacheKeySize)) {
    return;
  }
1309
  table_.Erase(hashed_key);
G
Guido Tagliavini Ponce 已提交
1310
}
Y
Yi Wu 已提交
1311

1312 1313 1314 1315
template <class Table>
size_t ClockCacheShard<Table>::GetUsage() const {
  return table_.GetUsage();
}
Y
Yi Wu 已提交
1316

1317
template <class Table>
1318 1319
size_t ClockCacheShard<Table>::GetStandaloneUsage() const {
  return table_.GetStandaloneUsage();
1320 1321 1322 1323 1324 1325 1326
}

template <class Table>
size_t ClockCacheShard<Table>::GetCapacity() const {
  return capacity_;
}

1327 1328
template <class Table>
size_t ClockCacheShard<Table>::GetPinnedUsage() const {
1329 1330
  // Computes the pinned usage by scanning the whole hash table. This
  // is slow, but avoids keeping an exact counter on the clock usage,
1331
  // i.e., the number of not externally referenced elements.
1332
  // Why avoid this counter? Because Lookup removes elements from the clock
1333 1334
  // list, so it would need to update the pinned usage every time,
  // which creates additional synchronization costs.
1335 1336 1337
  size_t table_pinned_usage = 0;
  const bool charge_metadata =
      metadata_charge_policy_ == kFullChargeCacheMetadata;
1338
  table_.ConstApplyToEntriesRange(
1339
      [&table_pinned_usage, charge_metadata](const HandleImpl& h) {
1340
        uint64_t meta = h.meta.load(std::memory_order_relaxed);
1341
        uint64_t refcount = GetRefcount(meta);
1342 1343 1344
        // Holding one ref for ConstApplyToEntriesRange
        assert(refcount > 0);
        if (refcount > 1) {
1345
          table_pinned_usage += h.GetTotalCharge();
1346
          if (charge_metadata) {
1347
            table_pinned_usage += sizeof(HandleImpl);
1348
          }
1349 1350 1351 1352
        }
      },
      0, table_.GetTableSize(), true);

1353
  return table_pinned_usage + table_.GetStandaloneUsage();
1354 1355
}

1356 1357
template <class Table>
size_t ClockCacheShard<Table>::GetOccupancyCount() const {
1358 1359 1360
  return table_.GetOccupancy();
}

1361 1362 1363 1364 1365
template <class Table>
size_t ClockCacheShard<Table>::GetOccupancyLimit() const {
  return table_.GetOccupancyLimit();
}

1366 1367
template <class Table>
size_t ClockCacheShard<Table>::GetTableAddressCount() const {
1368
  return table_.GetTableSize();
G
Guido Tagliavini Ponce 已提交
1369
}
Y
Yi Wu 已提交
1370

1371 1372 1373
// Explicit instantiation
template class ClockCacheShard<HyperClockTable>;

1374 1375 1376 1377
HyperClockCache::HyperClockCache(const HyperClockCacheOptions& opts)
    : ShardedCache(opts) {
  assert(opts.estimated_entry_charge > 0 ||
         opts.metadata_charge_policy != kDontChargeCacheMetadata);
1378 1379
  // TODO: should not need to go through two levels of pointer indirection to
  // get to table entries
1380
  size_t per_shard = GetPerShardCapacity();
1381
  MemoryAllocator* alloc = this->memory_allocator();
1382 1383 1384 1385 1386
  InitShards([&](Shard* cs) {
    HyperClockTable::Opts table_opts;
    table_opts.estimated_value_size = opts.estimated_entry_charge;
    new (cs) Shard(per_shard, opts.strict_capacity_limit,
                   opts.metadata_charge_policy, alloc, &eviction_callback_,
1387
                   &hash_seed_, table_opts);
1388
  });
G
Guido Tagliavini Ponce 已提交
1389
}
Y
Yi Wu 已提交
1390

1391
Cache::ObjectPtr HyperClockCache::Value(Handle* handle) {
1392
  return reinterpret_cast<const HandleImpl*>(handle)->value;
G
Guido Tagliavini Ponce 已提交
1393
}
1394

1395
size_t HyperClockCache::GetCharge(Handle* handle) const {
1396
  return reinterpret_cast<const HandleImpl*>(handle)->GetTotalCharge();
G
Guido Tagliavini Ponce 已提交
1397
}
Y
Yi Wu 已提交
1398

1399 1400
const Cache::CacheItemHelper* HyperClockCache::GetCacheItemHelper(
    Handle* handle) const {
1401
  auto h = reinterpret_cast<const HandleImpl*>(handle);
1402
  return h->helper;
G
Guido Tagliavini Ponce 已提交
1403
}
1404

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
namespace {

// For each cache shard, estimate what the table load factor would be if
// cache filled to capacity with average entries. This is considered
// indicative of a potential problem if the shard is essentially operating
// "at limit", which we define as high actual usage (>80% of capacity)
// or actual occupancy very close to limit (>95% of limit).
// Also, for each shard compute the recommended estimated_entry_charge,
// and keep the minimum one for use as overall recommendation.
void AddShardEvaluation(const HyperClockCache::Shard& shard,
                        std::vector<double>& predicted_load_factors,
                        size_t& min_recommendation) {
1417
  size_t usage = shard.GetUsage() - shard.GetStandaloneUsage();
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
  size_t capacity = shard.GetCapacity();
  double usage_ratio = 1.0 * usage / capacity;

  size_t occupancy = shard.GetOccupancyCount();
  size_t occ_limit = shard.GetOccupancyLimit();
  double occ_ratio = 1.0 * occupancy / occ_limit;
  if (usage == 0 || occupancy == 0 || (usage_ratio < 0.8 && occ_ratio < 0.95)) {
    // Skip as described above
    return;
  }

  // If filled to capacity, what would the occupancy ratio be?
  double ratio = occ_ratio / usage_ratio;
  // Given max load factor, what that load factor be?
  double lf = ratio * kStrictLoadFactor;
  predicted_load_factors.push_back(lf);

  // Update min_recommendation also
  size_t recommendation = usage / occupancy;
  min_recommendation = std::min(min_recommendation, recommendation);
}

}  // namespace

void HyperClockCache::ReportProblems(
    const std::shared_ptr<Logger>& info_log) const {
  uint32_t shard_count = GetNumShards();
  std::vector<double> predicted_load_factors;
  size_t min_recommendation = SIZE_MAX;
  const_cast<HyperClockCache*>(this)->ForEachShard(
      [&](HyperClockCache::Shard* shard) {
        AddShardEvaluation(*shard, predicted_load_factors, min_recommendation);
      });

  if (predicted_load_factors.empty()) {
    // None operating "at limit" -> nothing to report
    return;
  }
  std::sort(predicted_load_factors.begin(), predicted_load_factors.end());

  // First, if the average load factor is within spec, we aren't going to
  // complain about a few shards being out of spec.
  // NOTE: this is only the average among cache shards operating "at limit,"
  // which should be representative of what we care about. It it normal, even
  // desirable, for a cache to operate "at limit" so this should not create
  // selection bias. See AddShardEvaluation().
  // TODO: Consider detecting cases where decreasing the number of shards
  // would be good, e.g. serious imbalance among shards.
  double average_load_factor =
      std::accumulate(predicted_load_factors.begin(),
                      predicted_load_factors.end(), 0.0) /
      shard_count;

  constexpr double kLowSpecLoadFactor = kLoadFactor / 2;
  constexpr double kMidSpecLoadFactor = kLoadFactor / 1.414;
  if (average_load_factor > kLoadFactor) {
    // Out of spec => Consider reporting load factor too high
    // Estimate effective overall capacity loss due to enforcing occupancy limit
    double lost_portion = 0.0;
    int over_count = 0;
    for (double lf : predicted_load_factors) {
      if (lf > kStrictLoadFactor) {
        ++over_count;
        lost_portion += (lf - kStrictLoadFactor) / lf / shard_count;
      }
    }
    // >= 20% loss -> error
    // >= 10% loss -> consistent warning
    // >= 1% loss -> intermittent warning
    InfoLogLevel level = InfoLogLevel::INFO_LEVEL;
    bool report = true;
    if (lost_portion > 0.2) {
      level = InfoLogLevel::ERROR_LEVEL;
    } else if (lost_portion > 0.1) {
      level = InfoLogLevel::WARN_LEVEL;
    } else if (lost_portion > 0.01) {
      int report_percent = static_cast<int>(lost_portion * 100.0);
      if (Random::GetTLSInstance()->PercentTrue(report_percent)) {
        level = InfoLogLevel::WARN_LEVEL;
      }
    } else {
      // don't report
      report = false;
    }
    if (report) {
      ROCKS_LOG_AT_LEVEL(
          info_log, level,
          "HyperClockCache@%p unable to use estimated %.1f%% capacity because "
          "of "
          "full occupancy in %d/%u cache shards (estimated_entry_charge too "
          "high). Recommend estimated_entry_charge=%zu",
          this, lost_portion * 100.0, over_count, (unsigned)shard_count,
          min_recommendation);
    }
  } else if (average_load_factor < kLowSpecLoadFactor) {
    // Out of spec => Consider reporting load factor too low
    // But cautiously because low is not as big of a problem.

    // Only report if highest occupancy shard is also below
    // spec and only if average is substantially out of spec
    if (predicted_load_factors.back() < kLowSpecLoadFactor &&
        average_load_factor < kLowSpecLoadFactor / 1.414) {
      InfoLogLevel level = InfoLogLevel::INFO_LEVEL;
      if (average_load_factor < kLowSpecLoadFactor / 2) {
        level = InfoLogLevel::WARN_LEVEL;
      }
      ROCKS_LOG_AT_LEVEL(
          info_log, level,
          "HyperClockCache@%p table has low occupancy at full capacity. Higher "
          "estimated_entry_charge (about %.1fx) would likely improve "
          "performance. Recommend estimated_entry_charge=%zu",
          this, kMidSpecLoadFactor / average_load_factor, min_recommendation);
    }
  }
}

1534
}  // namespace clock_cache
Y
Yi Wu 已提交
1535

1536
// DEPRECATED (see public API)
1537
std::shared_ptr<Cache> NewClockCache(
1538
    size_t capacity, int num_shard_bits, bool strict_capacity_limit,
1539
    CacheMetadataChargePolicy metadata_charge_policy) {
1540 1541 1542 1543
  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);
1544 1545
}

1546
std::shared_ptr<Cache> HyperClockCacheOptions::MakeSharedCache() const {
1547 1548 1549
  // For sanitized options
  HyperClockCacheOptions opts = *this;
  if (opts.num_shard_bits >= 20) {
G
Guido Tagliavini Ponce 已提交
1550 1551
    return nullptr;  // The cache cannot be sharded into too many fine pieces.
  }
1552
  if (opts.num_shard_bits < 0) {
1553 1554 1555
    // Use larger shard size to reduce risk of large entries clustering
    // or skewing individual shards.
    constexpr size_t min_shard_size = 32U * 1024U * 1024U;
1556 1557
    opts.num_shard_bits =
        GetDefaultCacheShardBits(opts.capacity, min_shard_size);
1558
  }
1559 1560 1561 1562 1563
  std::shared_ptr<Cache> cache =
      std::make_shared<clock_cache::HyperClockCache>(opts);
  if (opts.secondary_cache) {
    cache = std::make_shared<CacheWithSecondaryAdapter>(cache,
                                                        opts.secondary_cache);
1564 1565
  }
  return cache;
Y
Yi Wu 已提交
1566 1567
}

1568
}  // namespace ROCKSDB_NAMESPACE