clock_cache.cc 144 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  7. // Use of this source code is governed by a BSD-style license that can be
  8. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  9. #include "cache/clock_cache.h"
  10. #include <algorithm>
  11. #include <bitset>
  12. #include <cassert>
  13. #include <cinttypes>
  14. #include <cstddef>
  15. #include <cstdint>
  16. #include <cstdio>
  17. #include <exception>
  18. #include <functional>
  19. #include <numeric>
  20. #include <string>
  21. #include <thread>
  22. #include <type_traits>
  23. #include "cache/cache_key.h"
  24. #include "cache/secondary_cache_adapter.h"
  25. #include "logging/logging.h"
  26. #include "port/likely.h"
  27. #include "rocksdb/env.h"
  28. #include "util/autovector.h"
  29. #include "util/hash.h"
  30. #include "util/math.h"
  31. #include "util/random.h"
  32. namespace ROCKSDB_NAMESPACE {
  33. namespace clock_cache {
  34. namespace {
  35. inline uint64_t GetRefcount(uint64_t meta) {
  36. return ((meta >> ClockHandle::kAcquireCounterShift) -
  37. (meta >> ClockHandle::kReleaseCounterShift)) &
  38. ClockHandle::kCounterMask;
  39. }
  40. inline uint64_t GetInitialCountdown(Cache::Priority priority) {
  41. // Set initial clock data from priority
  42. // TODO: configuration parameters for priority handling and clock cycle
  43. // count?
  44. switch (priority) {
  45. case Cache::Priority::HIGH:
  46. return ClockHandle::kHighCountdown;
  47. case Cache::Priority::LOW:
  48. return ClockHandle::kLowCountdown;
  49. case Cache::Priority::BOTTOM:
  50. return ClockHandle::kBottomCountdown;
  51. }
  52. // Switch should have been exhaustive.
  53. assert(false);
  54. // For release build, fall back on something reasonable.
  55. return ClockHandle::kLowCountdown;
  56. }
  57. inline void MarkEmpty(ClockHandle& h) {
  58. #ifndef NDEBUG
  59. // Mark slot as empty, with assertion
  60. uint64_t meta = h.meta.Exchange(0);
  61. assert(meta >> ClockHandle::kStateShift == ClockHandle::kStateConstruction);
  62. #else
  63. // Mark slot as empty
  64. h.meta.Store(0);
  65. #endif
  66. }
  67. inline void FreeDataMarkEmpty(ClockHandle& h, MemoryAllocator* allocator) {
  68. // NOTE: in theory there's more room for parallelism if we copy the handle
  69. // data and delay actions like this until after marking the entry as empty,
  70. // but performance tests only show a regression by copying the few words
  71. // of data.
  72. h.FreeData(allocator);
  73. MarkEmpty(h);
  74. }
  75. // Called to undo the effect of referencing an entry for internal purposes,
  76. // so it should not be marked as having been used.
  77. inline void Unref(const ClockHandle& h, uint64_t count = 1) {
  78. // Pretend we never took the reference
  79. // WART: there's a tiny chance we release last ref to invisible
  80. // entry here. If that happens, we let eviction take care of it.
  81. uint64_t old_meta = h.meta.FetchSub(ClockHandle::kAcquireIncrement * count);
  82. assert(GetRefcount(old_meta) != 0);
  83. (void)old_meta;
  84. }
  85. inline bool ClockUpdate(ClockHandle& h, BaseClockTable::EvictionData* data,
  86. bool* purgeable = nullptr) {
  87. uint64_t meta;
  88. if (purgeable) {
  89. assert(*purgeable == false);
  90. // In AutoHCC, our eviction process follows the chain structure, so we
  91. // should ensure that we see the latest state of each entry, at least for
  92. // assertion checking.
  93. meta = h.meta.Load();
  94. } else {
  95. // In FixedHCC, our eviction process is a simple iteration without regard
  96. // to probing order, displacements, etc., so it doesn't matter if we see
  97. // somewhat stale data.
  98. meta = h.meta.LoadRelaxed();
  99. }
  100. if (((meta >> ClockHandle::kStateShift) & ClockHandle::kStateShareableBit) ==
  101. 0) {
  102. // Only clock update Shareable entries
  103. if (purgeable) {
  104. *purgeable = true;
  105. // AutoHCC only: make sure we only attempt to update non-empty slots
  106. assert((meta >> ClockHandle::kStateShift) &
  107. ClockHandle::kStateOccupiedBit);
  108. }
  109. return false;
  110. }
  111. uint64_t acquire_count =
  112. (meta >> ClockHandle::kAcquireCounterShift) & ClockHandle::kCounterMask;
  113. uint64_t release_count =
  114. (meta >> ClockHandle::kReleaseCounterShift) & ClockHandle::kCounterMask;
  115. if (acquire_count != release_count) {
  116. // Only clock update entries with no outstanding refs
  117. data->seen_pinned_count++;
  118. return false;
  119. }
  120. if ((meta >> ClockHandle::kStateShift == ClockHandle::kStateVisible) &&
  121. acquire_count > 0) {
  122. // Decrement clock
  123. uint64_t new_count =
  124. std::min(acquire_count - 1, uint64_t{ClockHandle::kMaxCountdown} - 1);
  125. // Compare-exchange in the decremented clock info, but
  126. // not aggressively
  127. uint64_t new_meta =
  128. (uint64_t{ClockHandle::kStateVisible} << ClockHandle::kStateShift) |
  129. (meta & ClockHandle::kHitBitMask) |
  130. (new_count << ClockHandle::kReleaseCounterShift) |
  131. (new_count << ClockHandle::kAcquireCounterShift);
  132. h.meta.CasStrongRelaxed(meta, new_meta);
  133. return false;
  134. }
  135. // Otherwise, remove entry (either unreferenced invisible or
  136. // unreferenced and expired visible).
  137. if (h.meta.CasStrong(meta, (uint64_t{ClockHandle::kStateConstruction}
  138. << ClockHandle::kStateShift) |
  139. (meta & ClockHandle::kHitBitMask))) {
  140. // Took ownership.
  141. data->freed_charge += h.GetTotalCharge();
  142. data->freed_count += 1;
  143. return true;
  144. } else {
  145. // Compare-exchange failing probably
  146. // indicates the entry was used, so skip it in that case.
  147. return false;
  148. }
  149. }
  150. // If an entry doesn't receive clock updates but is repeatedly referenced &
  151. // released, the acquire and release counters could overflow without some
  152. // intervention. This is that intervention, which should be inexpensive
  153. // because it only incurs a simple, very predictable check. (Applying a bit
  154. // mask in addition to an increment to every Release likely would be
  155. // relatively expensive, because it's an extra atomic update.)
  156. //
  157. // We do have to assume that we never have many millions of simultaneous
  158. // references to a cache handle, because we cannot represent so many
  159. // references with the difference in counters, masked to the number of
  160. // counter bits. Similarly, we assume there aren't millions of threads
  161. // holding transient references (which might be "undone" rather than
  162. // released by the way).
  163. //
  164. // Consider these possible states for each counter:
  165. // low: less than kMaxCountdown
  166. // medium: kMaxCountdown to half way to overflow + kMaxCountdown
  167. // high: half way to overflow + kMaxCountdown, or greater
  168. //
  169. // And these possible states for the combination of counters:
  170. // acquire / release
  171. // ------- -------
  172. // low low - Normal / common, with caveats (see below)
  173. // medium low - Can happen while holding some refs
  174. // high low - Violates assumptions (too many refs)
  175. // low medium - Violates assumptions (refs underflow, etc.)
  176. // medium medium - Normal (very read heavy cache)
  177. // high medium - Can happen while holding some refs
  178. // low high - This function is supposed to prevent
  179. // medium high - Violates assumptions (refs underflow, etc.)
  180. // high high - Needs CorrectNearOverflow
  181. //
  182. // Basically, this function detects (high, high) state (inferred from
  183. // release alone being high) and bumps it back down to (medium, medium)
  184. // state with the same refcount and the same logical countdown counter
  185. // (everything > kMaxCountdown is logically the same). Note that bumping
  186. // down to (low, low) would modify the countdown counter, so is "reserved"
  187. // in a sense.
  188. //
  189. // If near-overflow correction is triggered here, there's no guarantee
  190. // that another thread hasn't freed the entry and replaced it with another.
  191. // Therefore, it must be the case that the correction does not affect
  192. // entries unless they are very old (many millions of acquire-release cycles).
  193. // (Our bit manipulation is indeed idempotent and only affects entries in
  194. // exceptional cases.) We assume a pre-empted thread will not stall that long.
  195. // If it did, the state could be corrupted in the (unlikely) case that the top
  196. // bit of the acquire counter is set but not the release counter, and thus
  197. // we only clear the top bit of the acquire counter on resumption. It would
  198. // then appear that there are too many refs and the entry would be permanently
  199. // pinned (which is not terrible for an exceptionally rare occurrence), unless
  200. // it is referenced enough (at least kMaxCountdown more times) for the release
  201. // counter to reach "high" state again and bumped back to "medium." (This
  202. // motivates only checking for release counter in high state, not both in high
  203. // state.)
  204. inline void CorrectNearOverflow(uint64_t old_meta,
  205. AcqRelAtomic<uint64_t>& meta) {
  206. // We clear both top-most counter bits at the same time.
  207. constexpr uint64_t kCounterTopBit = uint64_t{1}
  208. << (ClockHandle::kCounterNumBits - 1);
  209. constexpr uint64_t kClearBits =
  210. (kCounterTopBit << ClockHandle::kAcquireCounterShift) |
  211. (kCounterTopBit << ClockHandle::kReleaseCounterShift);
  212. // A simple check that allows us to initiate clearing the top bits for
  213. // a large portion of the "high" state space on release counter.
  214. constexpr uint64_t kCheckBits =
  215. (kCounterTopBit | (ClockHandle::kMaxCountdown + 1))
  216. << ClockHandle::kReleaseCounterShift;
  217. if (UNLIKELY(old_meta & kCheckBits)) {
  218. meta.FetchAndRelaxed(~kClearBits);
  219. }
  220. }
  221. inline bool BeginSlotInsert(const ClockHandleBasicData& proto, ClockHandle& h,
  222. uint64_t initial_countdown, bool* already_matches) {
  223. assert(*already_matches == false);
  224. // Optimistically transition the slot from "empty" to
  225. // "under construction" (no effect on other states)
  226. uint64_t old_meta = h.meta.FetchOr(uint64_t{ClockHandle::kStateOccupiedBit}
  227. << ClockHandle::kStateShift);
  228. uint64_t old_state = old_meta >> ClockHandle::kStateShift;
  229. if (old_state == ClockHandle::kStateEmpty) {
  230. // We've started inserting into an available slot, and taken
  231. // ownership.
  232. return true;
  233. } else if (old_state != ClockHandle::kStateVisible) {
  234. // Slot not usable / touchable now
  235. return false;
  236. }
  237. // Existing, visible entry, which might be a match.
  238. // But first, we need to acquire a ref to read it. In fact, number of
  239. // refs for initial countdown, so that we boost the clock state if
  240. // this is a match.
  241. old_meta =
  242. h.meta.FetchAdd(ClockHandle::kAcquireIncrement * initial_countdown);
  243. // Like Lookup
  244. if ((old_meta >> ClockHandle::kStateShift) == ClockHandle::kStateVisible) {
  245. // Acquired a read reference
  246. if (h.hashed_key == proto.hashed_key) {
  247. // Match. Release in a way that boosts the clock state
  248. old_meta =
  249. h.meta.FetchAdd(ClockHandle::kReleaseIncrement * initial_countdown);
  250. // Correct for possible (but rare) overflow
  251. CorrectNearOverflow(old_meta, h.meta);
  252. // Insert detached instead (only if return handle needed)
  253. *already_matches = true;
  254. return false;
  255. } else {
  256. // Mismatch.
  257. Unref(h, initial_countdown);
  258. }
  259. } else if (UNLIKELY((old_meta >> ClockHandle::kStateShift) ==
  260. ClockHandle::kStateInvisible)) {
  261. // Pretend we never took the reference
  262. Unref(h, initial_countdown);
  263. } else {
  264. // For other states, incrementing the acquire counter has no effect
  265. // so we don't need to undo it.
  266. // Slot not usable / touchable now.
  267. }
  268. return false;
  269. }
  270. inline void FinishSlotInsert(const ClockHandleBasicData& proto, ClockHandle& h,
  271. uint64_t initial_countdown, bool keep_ref) {
  272. // Save data fields
  273. ClockHandleBasicData* h_alias = &h;
  274. *h_alias = proto;
  275. // Transition from "under construction" state to "visible" state
  276. uint64_t new_meta = uint64_t{ClockHandle::kStateVisible}
  277. << ClockHandle::kStateShift;
  278. // Maybe with an outstanding reference
  279. new_meta |= initial_countdown << ClockHandle::kAcquireCounterShift;
  280. new_meta |= (initial_countdown - keep_ref)
  281. << ClockHandle::kReleaseCounterShift;
  282. #ifndef NDEBUG
  283. // Save the state transition, with assertion
  284. uint64_t old_meta = h.meta.Exchange(new_meta);
  285. assert(old_meta >> ClockHandle::kStateShift ==
  286. ClockHandle::kStateConstruction);
  287. #else
  288. // Save the state transition
  289. h.meta.Store(new_meta);
  290. #endif
  291. }
  292. bool TryInsert(const ClockHandleBasicData& proto, ClockHandle& h,
  293. uint64_t initial_countdown, bool keep_ref,
  294. bool* already_matches) {
  295. bool b = BeginSlotInsert(proto, h, initial_countdown, already_matches);
  296. if (b) {
  297. FinishSlotInsert(proto, h, initial_countdown, keep_ref);
  298. }
  299. return b;
  300. }
  301. // Func must be const HandleImpl& -> void callable
  302. template <class HandleImpl, class Func>
  303. void ConstApplyToEntriesRange(const Func& func, const HandleImpl* begin,
  304. const HandleImpl* end,
  305. bool apply_if_will_be_deleted) {
  306. uint64_t check_state_mask = ClockHandle::kStateShareableBit;
  307. if (!apply_if_will_be_deleted) {
  308. check_state_mask |= ClockHandle::kStateVisibleBit;
  309. }
  310. for (const HandleImpl* h = begin; h < end; ++h) {
  311. // Note: to avoid using compare_exchange, we have to be extra careful.
  312. uint64_t old_meta = h->meta.LoadRelaxed();
  313. // Check if it's an entry visible to lookups
  314. if ((old_meta >> ClockHandle::kStateShift) & check_state_mask) {
  315. // Increment acquire counter. Note: it's possible that the entry has
  316. // completely changed since we loaded old_meta, but incrementing acquire
  317. // count is always safe. (Similar to optimistic Lookup here.)
  318. old_meta = h->meta.FetchAdd(ClockHandle::kAcquireIncrement);
  319. // Check whether we actually acquired a reference.
  320. if ((old_meta >> ClockHandle::kStateShift) &
  321. ClockHandle::kStateShareableBit) {
  322. // Apply func if appropriate
  323. if ((old_meta >> ClockHandle::kStateShift) & check_state_mask) {
  324. func(*h);
  325. }
  326. // Pretend we never took the reference
  327. Unref(*h);
  328. // No net change, so don't need to check for overflow
  329. } else {
  330. // For other states, incrementing the acquire counter has no effect
  331. // so we don't need to undo it. Furthermore, we cannot safely undo
  332. // it because we did not acquire a read reference to lock the
  333. // entry in a Shareable state.
  334. }
  335. }
  336. }
  337. }
  338. uint32_t SanitizeEvictionEffortCap(int eviction_effort_cap) {
  339. eviction_effort_cap = std::max(int{1}, eviction_effort_cap);
  340. return static_cast<uint32_t>(eviction_effort_cap);
  341. }
  342. } // namespace
  343. void ClockHandleBasicData::FreeData(MemoryAllocator* allocator) const {
  344. if (helper->del_cb) {
  345. helper->del_cb(value, allocator);
  346. }
  347. }
  348. BaseClockTable::BaseClockTable(size_t capacity, bool strict_capacity_limit,
  349. int eviction_effort_cap,
  350. CacheMetadataChargePolicy metadata_charge_policy,
  351. MemoryAllocator* allocator,
  352. const Cache::EvictionCallback* eviction_callback,
  353. const uint32_t* hash_seed)
  354. : capacity_(capacity),
  355. eec_and_scl_(EecAndScl{}
  356. .With<EvictionEffortCap>(
  357. SanitizeEvictionEffortCap(eviction_effort_cap))
  358. .With<StrictCapacityLimit>(strict_capacity_limit)),
  359. metadata_charge_policy_(metadata_charge_policy),
  360. allocator_(allocator),
  361. eviction_callback_(*eviction_callback),
  362. hash_seed_(*hash_seed) {}
  363. template <class HandleImpl>
  364. HandleImpl* BaseClockTable::StandaloneInsert(
  365. const ClockHandleBasicData& proto) {
  366. // Heap allocated separate from table
  367. HandleImpl* h = new HandleImpl();
  368. ClockHandleBasicData* h_alias = h;
  369. *h_alias = proto;
  370. h->SetStandalone();
  371. // Single reference (standalone entries only created if returning a refed
  372. // Handle back to user)
  373. uint64_t meta = uint64_t{ClockHandle::kStateInvisible}
  374. << ClockHandle::kStateShift;
  375. meta |= uint64_t{1} << ClockHandle::kAcquireCounterShift;
  376. h->meta.Store(meta);
  377. // Keep track of how much of usage is standalone
  378. standalone_usage_.FetchAddRelaxed(proto.GetTotalCharge());
  379. return h;
  380. }
  381. template <class Table>
  382. typename Table::HandleImpl* BaseClockTable::CreateStandalone(
  383. ClockHandleBasicData& proto, bool allow_uncharged) {
  384. Table& derived = static_cast<Table&>(*this);
  385. typename Table::InsertState state;
  386. derived.StartInsert(state);
  387. const size_t total_charge = proto.GetTotalCharge();
  388. // NOTE: we can use eec_and_scl as eviction_effort_cap below because
  389. // strict_capacity_limit=true is supposed to disable the limit on eviction
  390. // effort, and a large value effectively does that.
  391. if (eec_and_scl_.LoadRelaxed().Get<StrictCapacityLimit>()) {
  392. Status s = ChargeUsageMaybeEvictStrict<Table>(
  393. total_charge,
  394. /*need_evict_for_occupancy=*/false, state);
  395. if (!s.ok()) {
  396. if (allow_uncharged) {
  397. proto.total_charge = 0;
  398. } else {
  399. return nullptr;
  400. }
  401. }
  402. } else {
  403. // Case strict_capacity_limit == false
  404. bool success = ChargeUsageMaybeEvictNonStrict<Table>(
  405. total_charge,
  406. /*need_evict_for_occupancy=*/false, state);
  407. if (!success) {
  408. // Force the issue
  409. usage_.FetchAddRelaxed(total_charge);
  410. }
  411. }
  412. return StandaloneInsert<typename Table::HandleImpl>(proto);
  413. }
  414. template <class Table>
  415. Status BaseClockTable::ChargeUsageMaybeEvictStrict(
  416. size_t total_charge, bool need_evict_for_occupancy,
  417. typename Table::InsertState& state) {
  418. const size_t capacity = capacity_.LoadRelaxed();
  419. if (total_charge > capacity) {
  420. return Status::MemoryLimit(
  421. "Cache entry too large for a single cache shard: " +
  422. std::to_string(total_charge) + " > " + std::to_string(capacity));
  423. }
  424. // Grab any available capacity, and free up any more required.
  425. size_t old_usage = usage_.LoadRelaxed();
  426. size_t new_usage;
  427. do {
  428. new_usage = std::min(capacity, old_usage + total_charge);
  429. if (new_usage == old_usage) {
  430. // No change needed
  431. break;
  432. }
  433. } while (!usage_.CasWeakRelaxed(old_usage, new_usage));
  434. // How much do we need to evict then?
  435. size_t need_evict_charge = old_usage + total_charge - new_usage;
  436. size_t request_evict_charge = need_evict_charge;
  437. if (UNLIKELY(need_evict_for_occupancy) && request_evict_charge == 0) {
  438. // Require at least 1 eviction.
  439. request_evict_charge = 1;
  440. }
  441. if (request_evict_charge > 0) {
  442. EvictionData data;
  443. static_cast<Table*>(this)->Evict(request_evict_charge, state, &data);
  444. occupancy_.FetchSub(data.freed_count);
  445. if (LIKELY(data.freed_charge > need_evict_charge)) {
  446. assert(data.freed_count > 0);
  447. // Evicted more than enough
  448. usage_.FetchSubRelaxed(data.freed_charge - need_evict_charge);
  449. } else if (data.freed_charge < need_evict_charge ||
  450. (UNLIKELY(need_evict_for_occupancy) && data.freed_count == 0)) {
  451. // Roll back to old usage minus evicted
  452. usage_.FetchSubRelaxed(data.freed_charge + (new_usage - old_usage));
  453. if (data.freed_charge < need_evict_charge) {
  454. return Status::MemoryLimit(
  455. "Insert failed because unable to evict entries to stay within "
  456. "capacity limit.");
  457. } else {
  458. return Status::MemoryLimit(
  459. "Insert failed because unable to evict entries to stay within "
  460. "table occupancy limit.");
  461. }
  462. }
  463. // If we needed to evict something and we are proceeding, we must have
  464. // evicted something.
  465. assert(data.freed_count > 0);
  466. }
  467. return Status::OK();
  468. }
  469. template <class Table>
  470. inline bool BaseClockTable::ChargeUsageMaybeEvictNonStrict(
  471. size_t total_charge, bool need_evict_for_occupancy,
  472. typename Table::InsertState& state) {
  473. // For simplicity, we consider that either the cache can accept the insert
  474. // with no evictions, or we must evict enough to make (at least) enough
  475. // space. It could lead to unnecessary failures or excessive evictions in
  476. // some extreme cases, but allows a fast, simple protocol. If we allow a
  477. // race to get us over capacity, then we might never get back to capacity
  478. // limit if the sizes of entries allow each insertion to evict the minimum
  479. // charge. Thus, we should evict some extra if it's not a signifcant
  480. // portion of the shard capacity. This can have the side benefit of
  481. // involving fewer threads in eviction.
  482. const size_t old_usage = usage_.LoadRelaxed();
  483. const size_t capacity = capacity_.LoadRelaxed();
  484. size_t need_evict_charge;
  485. // NOTE: if total_charge > old_usage, there isn't yet enough to evict
  486. // `total_charge` amount. Even if we only try to evict `old_usage` amount,
  487. // there's likely something referenced and we would eat CPU looking for
  488. // enough to evict.
  489. if (old_usage + total_charge <= capacity || total_charge > old_usage) {
  490. // Good enough for me (might run over with a race)
  491. need_evict_charge = 0;
  492. } else {
  493. // Try to evict enough space, and maybe some extra
  494. need_evict_charge = total_charge;
  495. if (old_usage > capacity) {
  496. // Not too much to avoid thundering herd while avoiding strict
  497. // synchronization, such as the compare_exchange used with strict
  498. // capacity limit.
  499. need_evict_charge += std::min(capacity / 1024, total_charge) + 1;
  500. }
  501. }
  502. if (UNLIKELY(need_evict_for_occupancy) && need_evict_charge == 0) {
  503. // Special case: require at least 1 eviction if we only have to
  504. // deal with occupancy
  505. need_evict_charge = 1;
  506. }
  507. EvictionData data;
  508. if (need_evict_charge > 0) {
  509. static_cast<Table*>(this)->Evict(need_evict_charge, state, &data);
  510. // Deal with potential occupancy deficit
  511. if (UNLIKELY(need_evict_for_occupancy) && data.freed_count == 0) {
  512. assert(data.freed_charge == 0);
  513. // Can't meet occupancy requirement
  514. return false;
  515. } else {
  516. // Update occupancy for evictions
  517. occupancy_.FetchSub(data.freed_count);
  518. }
  519. }
  520. // Track new usage even if we weren't able to evict enough
  521. usage_.FetchAddRelaxed(total_charge - data.freed_charge);
  522. // No underflow
  523. assert(usage_.LoadRelaxed() < SIZE_MAX / 2);
  524. // Success
  525. return true;
  526. }
  527. void BaseClockTable::TrackAndReleaseEvictedEntry(ClockHandle* h) {
  528. bool took_value_ownership = false;
  529. if (eviction_callback_) {
  530. // For key reconstructed from hash
  531. UniqueId64x2 unhashed;
  532. took_value_ownership =
  533. eviction_callback_(ClockCacheShard<FixedHyperClockTable>::ReverseHash(
  534. h->GetHash(), &unhashed, hash_seed_),
  535. static_cast<Cache::Handle*>(h),
  536. h->meta.LoadRelaxed() & ClockHandle::kHitBitMask);
  537. }
  538. if (!took_value_ownership) {
  539. h->FreeData(allocator_);
  540. }
  541. MarkEmpty(*h);
  542. }
  543. bool BaseClockTable::IsEvictionEffortExceeded(
  544. const BaseClockTable::EvictionData& data) const {
  545. auto eviction_effort_cap =
  546. eec_and_scl_.LoadRelaxed().GetEffectiveEvictionEffortCap();
  547. // Basically checks whether the ratio of useful effort to wasted effort is
  548. // too low, with a start-up allowance for wasted effort before any useful
  549. // effort.
  550. return (data.freed_count + 1U) * uint64_t{eviction_effort_cap} <=
  551. data.seen_pinned_count;
  552. }
  553. template <class Table>
  554. Status BaseClockTable::Insert(const ClockHandleBasicData& proto,
  555. typename Table::HandleImpl** handle,
  556. Cache::Priority priority) {
  557. using HandleImpl = typename Table::HandleImpl;
  558. Table& derived = static_cast<Table&>(*this);
  559. typename Table::InsertState state;
  560. derived.StartInsert(state);
  561. // Do we have the available occupancy? Optimistically assume we do
  562. // and deal with it if we don't.
  563. size_t old_occupancy = occupancy_.FetchAdd(1);
  564. // Whether we over-committed and need an eviction to make up for it
  565. bool need_evict_for_occupancy =
  566. !derived.GrowIfNeeded(old_occupancy + 1, state);
  567. // Usage/capacity handling is somewhat different depending on
  568. // strict_capacity_limit, but mostly pessimistic.
  569. bool use_standalone_insert = false;
  570. const size_t total_charge = proto.GetTotalCharge();
  571. // NOTE: we can use eec_and_scl as eviction_effort_cap below because
  572. // strict_capacity_limit=true is supposed to disable the limit on eviction
  573. // effort, and a large value effectively does that.
  574. if (eec_and_scl_.LoadRelaxed().Get<StrictCapacityLimit>()) {
  575. Status s = ChargeUsageMaybeEvictStrict<Table>(
  576. total_charge, need_evict_for_occupancy, state);
  577. if (!s.ok()) {
  578. // Revert occupancy
  579. occupancy_.FetchSubRelaxed(1);
  580. return s;
  581. }
  582. } else {
  583. // Case strict_capacity_limit == false
  584. bool success = ChargeUsageMaybeEvictNonStrict<Table>(
  585. total_charge, need_evict_for_occupancy, state);
  586. if (!success) {
  587. // Revert occupancy
  588. occupancy_.FetchSubRelaxed(1);
  589. if (handle == nullptr) {
  590. // Don't insert the entry but still return ok, as if the entry
  591. // inserted into cache and evicted immediately.
  592. proto.FreeData(allocator_);
  593. return Status::OK();
  594. } else {
  595. // Need to track usage of fallback standalone insert
  596. usage_.FetchAddRelaxed(total_charge);
  597. use_standalone_insert = true;
  598. }
  599. }
  600. }
  601. if (!use_standalone_insert) {
  602. // Attempt a table insert, but abort if we find an existing entry for the
  603. // key. If we were to overwrite old entries, we would either
  604. // * Have to gain ownership over an existing entry to overwrite it, which
  605. // would only work if there are no outstanding (read) references and would
  606. // create a small gap in availability of the entry (old or new) to lookups.
  607. // * Have to insert into a suboptimal location (more probes) so that the
  608. // old entry can be kept around as well.
  609. uint64_t initial_countdown = GetInitialCountdown(priority);
  610. assert(initial_countdown > 0);
  611. HandleImpl* e =
  612. derived.DoInsert(proto, initial_countdown, handle != nullptr, state);
  613. if (e) {
  614. // Successfully inserted
  615. if (handle) {
  616. *handle = e;
  617. }
  618. return Status::OK();
  619. }
  620. // Not inserted
  621. // Revert occupancy
  622. occupancy_.FetchSubRelaxed(1);
  623. // Maybe fall back on standalone insert
  624. if (handle == nullptr) {
  625. // Revert usage
  626. usage_.FetchSubRelaxed(total_charge);
  627. // No underflow
  628. assert(usage_.LoadRelaxed() < SIZE_MAX / 2);
  629. // As if unrefed entry immdiately evicted
  630. proto.FreeData(allocator_);
  631. return Status::OK();
  632. }
  633. use_standalone_insert = true;
  634. }
  635. // Run standalone insert
  636. assert(use_standalone_insert);
  637. *handle = StandaloneInsert<HandleImpl>(proto);
  638. // The OkOverwritten status is used to count "redundant" insertions into
  639. // block cache. This implementation doesn't strictly check for redundant
  640. // insertions, but we instead are probably interested in how many insertions
  641. // didn't go into the table (instead "standalone"), which could be redundant
  642. // Insert or some other reason (use_standalone_insert reasons above).
  643. return Status::OkOverwritten();
  644. }
  645. void BaseClockTable::Ref(ClockHandle& h) {
  646. // Increment acquire counter
  647. uint64_t old_meta = h.meta.FetchAdd(ClockHandle::kAcquireIncrement);
  648. assert((old_meta >> ClockHandle::kStateShift) &
  649. ClockHandle::kStateShareableBit);
  650. // Must have already had a reference
  651. assert(GetRefcount(old_meta) > 0);
  652. (void)old_meta;
  653. }
  654. #ifndef NDEBUG
  655. void BaseClockTable::TEST_RefN(ClockHandle& h, size_t n) {
  656. // Increment acquire counter
  657. uint64_t old_meta = h.meta.FetchAdd(n * ClockHandle::kAcquireIncrement);
  658. assert((old_meta >> ClockHandle::kStateShift) &
  659. ClockHandle::kStateShareableBit);
  660. (void)old_meta;
  661. }
  662. void BaseClockTable::TEST_ReleaseNMinus1(ClockHandle* h, size_t n) {
  663. assert(n > 0);
  664. // Like n-1 Releases, but assumes one more will happen in the caller to take
  665. // care of anything like erasing an unreferenced, invisible entry.
  666. uint64_t old_meta =
  667. h->meta.FetchAdd((n - 1) * ClockHandle::kReleaseIncrement);
  668. assert((old_meta >> ClockHandle::kStateShift) &
  669. ClockHandle::kStateShareableBit);
  670. (void)old_meta;
  671. }
  672. #endif
  673. FixedHyperClockTable::FixedHyperClockTable(
  674. size_t capacity, bool strict_capacity_limit,
  675. CacheMetadataChargePolicy metadata_charge_policy,
  676. MemoryAllocator* allocator,
  677. const Cache::EvictionCallback* eviction_callback, const uint32_t* hash_seed,
  678. const Opts& opts)
  679. : BaseClockTable(capacity, strict_capacity_limit, opts.eviction_effort_cap,
  680. metadata_charge_policy, allocator, eviction_callback,
  681. hash_seed),
  682. length_bits_(CalcHashBits(capacity, opts.estimated_value_size,
  683. metadata_charge_policy)),
  684. length_bits_mask_((size_t{1} << length_bits_) - 1),
  685. occupancy_limit_(static_cast<size_t>((uint64_t{1} << length_bits_) *
  686. kStrictLoadFactor)),
  687. array_(new HandleImpl[size_t{1} << length_bits_]) {
  688. if (metadata_charge_policy ==
  689. CacheMetadataChargePolicy::kFullChargeCacheMetadata) {
  690. usage_.FetchAddRelaxed(size_t{GetTableSize()} * sizeof(HandleImpl));
  691. }
  692. static_assert(sizeof(HandleImpl) == 64U,
  693. "Expecting size / alignment with common cache line size");
  694. }
  695. FixedHyperClockTable::~FixedHyperClockTable() {
  696. // Assumes there are no references or active operations on any slot/element
  697. // in the table.
  698. for (size_t i = 0; i < GetTableSize(); i++) {
  699. HandleImpl& h = array_[i];
  700. switch (h.meta.LoadRelaxed() >> ClockHandle::kStateShift) {
  701. case ClockHandle::kStateEmpty:
  702. // noop
  703. break;
  704. case ClockHandle::kStateInvisible: // rare but possible
  705. case ClockHandle::kStateVisible:
  706. assert(GetRefcount(h.meta.LoadRelaxed()) == 0);
  707. h.FreeData(allocator_);
  708. #ifndef NDEBUG
  709. Rollback(h.hashed_key, &h);
  710. ReclaimEntryUsage(h.GetTotalCharge());
  711. #endif
  712. break;
  713. // otherwise
  714. default:
  715. assert(false);
  716. break;
  717. }
  718. }
  719. #ifndef NDEBUG
  720. for (size_t i = 0; i < GetTableSize(); i++) {
  721. assert(array_[i].displacements.LoadRelaxed() == 0);
  722. }
  723. #endif
  724. assert(usage_.LoadRelaxed() == 0 ||
  725. usage_.LoadRelaxed() == size_t{GetTableSize()} * sizeof(HandleImpl));
  726. assert(occupancy_.LoadRelaxed() == 0);
  727. }
  728. void FixedHyperClockTable::StartInsert(InsertState&) {}
  729. bool FixedHyperClockTable::GrowIfNeeded(size_t new_occupancy, InsertState&) {
  730. return new_occupancy <= occupancy_limit_;
  731. }
  732. FixedHyperClockTable::HandleImpl* FixedHyperClockTable::DoInsert(
  733. const ClockHandleBasicData& proto, uint64_t initial_countdown,
  734. bool keep_ref, InsertState&) {
  735. bool already_matches = false;
  736. HandleImpl* e = FindSlot(
  737. proto.hashed_key,
  738. [&](HandleImpl* h) {
  739. return TryInsert(proto, *h, initial_countdown, keep_ref,
  740. &already_matches);
  741. },
  742. [&](HandleImpl* h) {
  743. if (already_matches) {
  744. // Stop searching & roll back displacements
  745. Rollback(proto.hashed_key, h);
  746. return true;
  747. } else {
  748. // Keep going
  749. return false;
  750. }
  751. },
  752. [&](HandleImpl* h, bool is_last) {
  753. if (is_last) {
  754. // Search is ending. Roll back displacements
  755. Rollback(proto.hashed_key, h);
  756. } else {
  757. h->displacements.FetchAddRelaxed(1);
  758. }
  759. });
  760. if (already_matches) {
  761. // Insertion skipped
  762. return nullptr;
  763. }
  764. if (e != nullptr) {
  765. // Successfully inserted
  766. return e;
  767. }
  768. // Else, no available slot found. Occupancy check should generally prevent
  769. // this, except it's theoretically possible for other threads to evict and
  770. // replace entries in the right order to hit every slot when it is populated.
  771. // Assuming random hashing, the chance of that should be no higher than
  772. // pow(kStrictLoadFactor, n) for n slots. That should be infeasible for
  773. // roughly n >= 256, so if this assertion fails, that suggests something is
  774. // going wrong.
  775. assert(GetTableSize() < 256);
  776. return nullptr;
  777. }
  778. FixedHyperClockTable::HandleImpl* FixedHyperClockTable::Lookup(
  779. const UniqueId64x2& hashed_key) {
  780. HandleImpl* e = FindSlot(
  781. hashed_key,
  782. [&](HandleImpl* h) {
  783. // Mostly branch-free version (similar performance)
  784. /*
  785. uint64_t old_meta = h->meta.FetchAdd(ClockHandle::kAcquireIncrement,
  786. std::memory_order_acquire);
  787. bool Shareable = (old_meta >> (ClockHandle::kStateShift + 1)) & 1U;
  788. bool visible = (old_meta >> ClockHandle::kStateShift) & 1U;
  789. bool match = (h->key == key) & visible;
  790. h->meta.FetchSub(static_cast<uint64_t>(Shareable & !match) <<
  791. ClockHandle::kAcquireCounterShift); return
  792. match;
  793. */
  794. // Optimistic lookup should pay off when the table is relatively
  795. // sparse.
  796. constexpr bool kOptimisticLookup = true;
  797. uint64_t old_meta;
  798. if (!kOptimisticLookup) {
  799. old_meta = h->meta.Load();
  800. if ((old_meta >> ClockHandle::kStateShift) !=
  801. ClockHandle::kStateVisible) {
  802. return false;
  803. }
  804. }
  805. // (Optimistically) increment acquire counter
  806. old_meta = h->meta.FetchAdd(ClockHandle::kAcquireIncrement);
  807. // Check if it's an entry visible to lookups
  808. if ((old_meta >> ClockHandle::kStateShift) ==
  809. ClockHandle::kStateVisible) {
  810. // Acquired a read reference
  811. if (h->hashed_key == hashed_key) {
  812. // Match
  813. // Update the hit bit
  814. if (eviction_callback_) {
  815. h->meta.FetchOrRelaxed(uint64_t{1} << ClockHandle::kHitBitShift);
  816. }
  817. return true;
  818. } else {
  819. // Mismatch. Pretend we never took the reference
  820. Unref(*h);
  821. }
  822. } else if (UNLIKELY((old_meta >> ClockHandle::kStateShift) ==
  823. ClockHandle::kStateInvisible)) {
  824. // Pretend we never took the reference
  825. Unref(*h);
  826. } else {
  827. // For other states, incrementing the acquire counter has no effect
  828. // so we don't need to undo it. Furthermore, we cannot safely undo
  829. // it because we did not acquire a read reference to lock the
  830. // entry in a Shareable state.
  831. }
  832. return false;
  833. },
  834. [&](HandleImpl* h) { return h->displacements.LoadRelaxed() == 0; },
  835. [&](HandleImpl* /*h*/, bool /*is_last*/) {});
  836. return e;
  837. }
  838. bool FixedHyperClockTable::Release(HandleImpl* h, bool useful,
  839. bool erase_if_last_ref) {
  840. // In contrast with LRUCache's Release, this function won't delete the handle
  841. // when the cache is above capacity and the reference is the last one. Space
  842. // is only freed up by EvictFromClock (called by Insert when space is needed)
  843. // and Erase. We do this to avoid an extra atomic read of the variable usage_.
  844. uint64_t old_meta;
  845. if (useful) {
  846. // Increment release counter to indicate was used
  847. old_meta = h->meta.FetchAdd(ClockHandle::kReleaseIncrement);
  848. } else {
  849. // Decrement acquire counter to pretend it never happened
  850. old_meta = h->meta.FetchSub(ClockHandle::kAcquireIncrement);
  851. }
  852. assert((old_meta >> ClockHandle::kStateShift) &
  853. ClockHandle::kStateShareableBit);
  854. // No underflow
  855. assert(((old_meta >> ClockHandle::kAcquireCounterShift) &
  856. ClockHandle::kCounterMask) !=
  857. ((old_meta >> ClockHandle::kReleaseCounterShift) &
  858. ClockHandle::kCounterMask));
  859. if (erase_if_last_ref || UNLIKELY(old_meta >> ClockHandle::kStateShift ==
  860. ClockHandle::kStateInvisible)) {
  861. // FIXME: There's a chance here that another thread could replace this
  862. // entry and we end up erasing the wrong one.
  863. // Update for last FetchAdd op
  864. if (useful) {
  865. old_meta += ClockHandle::kReleaseIncrement;
  866. } else {
  867. old_meta -= ClockHandle::kAcquireIncrement;
  868. }
  869. // Take ownership if no refs
  870. do {
  871. if (GetRefcount(old_meta) != 0) {
  872. // Not last ref at some point in time during this Release call
  873. // Correct for possible (but rare) overflow
  874. CorrectNearOverflow(old_meta, h->meta);
  875. return false;
  876. }
  877. if ((old_meta & (uint64_t{ClockHandle::kStateShareableBit}
  878. << ClockHandle::kStateShift)) == 0) {
  879. // Someone else took ownership
  880. return false;
  881. }
  882. // Note that there's a small chance that we release, another thread
  883. // replaces this entry with another, reaches zero refs, and then we end
  884. // up erasing that other entry. That's an acceptable risk / imprecision.
  885. } while (
  886. !h->meta.CasWeak(old_meta, uint64_t{ClockHandle::kStateConstruction}
  887. << ClockHandle::kStateShift));
  888. // Took ownership
  889. size_t total_charge = h->GetTotalCharge();
  890. if (UNLIKELY(h->IsStandalone())) {
  891. h->FreeData(allocator_);
  892. // Delete standalone handle
  893. delete h;
  894. standalone_usage_.FetchSubRelaxed(total_charge);
  895. usage_.FetchSubRelaxed(total_charge);
  896. } else {
  897. Rollback(h->hashed_key, h);
  898. FreeDataMarkEmpty(*h, allocator_);
  899. ReclaimEntryUsage(total_charge);
  900. }
  901. return true;
  902. } else {
  903. // Correct for possible (but rare) overflow
  904. CorrectNearOverflow(old_meta, h->meta);
  905. return false;
  906. }
  907. }
  908. #ifndef NDEBUG
  909. void FixedHyperClockTable::TEST_ReleaseN(HandleImpl* h, size_t n) {
  910. if (n > 0) {
  911. // Do n-1 simple releases first
  912. TEST_ReleaseNMinus1(h, n);
  913. // Then the last release might be more involved
  914. Release(h, /*useful*/ true, /*erase_if_last_ref*/ false);
  915. }
  916. }
  917. #endif
  918. void FixedHyperClockTable::Erase(const UniqueId64x2& hashed_key) {
  919. (void)FindSlot(
  920. hashed_key,
  921. [&](HandleImpl* h) {
  922. // Could be multiple entries in rare cases. Erase them all.
  923. // Optimistically increment acquire counter
  924. uint64_t old_meta = h->meta.FetchAdd(ClockHandle::kAcquireIncrement);
  925. // Check if it's an entry visible to lookups
  926. if ((old_meta >> ClockHandle::kStateShift) ==
  927. ClockHandle::kStateVisible) {
  928. // Acquired a read reference
  929. if (h->hashed_key == hashed_key) {
  930. // Match. Set invisible.
  931. old_meta =
  932. h->meta.FetchAnd(~(uint64_t{ClockHandle::kStateVisibleBit}
  933. << ClockHandle::kStateShift));
  934. // Apply update to local copy
  935. old_meta &= ~(uint64_t{ClockHandle::kStateVisibleBit}
  936. << ClockHandle::kStateShift);
  937. for (;;) {
  938. uint64_t refcount = GetRefcount(old_meta);
  939. assert(refcount > 0);
  940. if (refcount > 1) {
  941. // Not last ref at some point in time during this Erase call
  942. // Pretend we never took the reference
  943. Unref(*h);
  944. break;
  945. } else if (h->meta.CasWeak(
  946. old_meta, uint64_t{ClockHandle::kStateConstruction}
  947. << ClockHandle::kStateShift)) {
  948. // Took ownership
  949. assert(hashed_key == h->hashed_key);
  950. size_t total_charge = h->GetTotalCharge();
  951. FreeDataMarkEmpty(*h, allocator_);
  952. ReclaimEntryUsage(total_charge);
  953. // We already have a copy of hashed_key in this case, so OK to
  954. // delay Rollback until after releasing the entry
  955. Rollback(hashed_key, h);
  956. break;
  957. }
  958. }
  959. } else {
  960. // Mismatch. Pretend we never took the reference
  961. Unref(*h);
  962. }
  963. } else if (UNLIKELY((old_meta >> ClockHandle::kStateShift) ==
  964. ClockHandle::kStateInvisible)) {
  965. // Pretend we never took the reference
  966. Unref(*h);
  967. } else {
  968. // For other states, incrementing the acquire counter has no effect
  969. // so we don't need to undo it.
  970. }
  971. return false;
  972. },
  973. [&](HandleImpl* h) { return h->displacements.LoadRelaxed() == 0; },
  974. [&](HandleImpl* /*h*/, bool /*is_last*/) {});
  975. }
  976. void FixedHyperClockTable::EraseUnRefEntries() {
  977. for (size_t i = 0; i <= this->length_bits_mask_; i++) {
  978. HandleImpl& h = array_[i];
  979. uint64_t old_meta = h.meta.LoadRelaxed();
  980. if (old_meta & (uint64_t{ClockHandle::kStateShareableBit}
  981. << ClockHandle::kStateShift) &&
  982. GetRefcount(old_meta) == 0 &&
  983. h.meta.CasStrong(old_meta, uint64_t{ClockHandle::kStateConstruction}
  984. << ClockHandle::kStateShift)) {
  985. // Took ownership
  986. size_t total_charge = h.GetTotalCharge();
  987. Rollback(h.hashed_key, &h);
  988. FreeDataMarkEmpty(h, allocator_);
  989. ReclaimEntryUsage(total_charge);
  990. }
  991. }
  992. }
  993. template <typename MatchFn, typename AbortFn, typename UpdateFn>
  994. inline FixedHyperClockTable::HandleImpl* FixedHyperClockTable::FindSlot(
  995. const UniqueId64x2& hashed_key, const MatchFn& match_fn,
  996. const AbortFn& abort_fn, const UpdateFn& update_fn) {
  997. // NOTE: upper 32 bits of hashed_key[0] is used for sharding
  998. //
  999. // We use double-hashing probing. Every probe in the sequence is a
  1000. // pseudorandom integer, computed as a linear function of two random hashes,
  1001. // which we call base and increment. Specifically, the i-th probe is base + i
  1002. // * increment modulo the table size.
  1003. size_t base = static_cast<size_t>(hashed_key[1]);
  1004. // We use an odd increment, which is relatively prime with the power-of-two
  1005. // table size. This implies that we cycle back to the first probe only
  1006. // after probing every slot exactly once.
  1007. // TODO: we could also reconsider linear probing, though locality benefits
  1008. // are limited because each slot is a full cache line
  1009. size_t increment = static_cast<size_t>(hashed_key[0]) | 1U;
  1010. size_t first = ModTableSize(base);
  1011. size_t current = first;
  1012. bool is_last;
  1013. do {
  1014. HandleImpl* h = &array_[current];
  1015. if (match_fn(h)) {
  1016. return h;
  1017. }
  1018. if (abort_fn(h)) {
  1019. return nullptr;
  1020. }
  1021. current = ModTableSize(current + increment);
  1022. is_last = current == first;
  1023. update_fn(h, is_last);
  1024. } while (!is_last);
  1025. // We looped back.
  1026. return nullptr;
  1027. }
  1028. inline void FixedHyperClockTable::Rollback(const UniqueId64x2& hashed_key,
  1029. const HandleImpl* h) {
  1030. size_t current = ModTableSize(hashed_key[1]);
  1031. size_t increment = static_cast<size_t>(hashed_key[0]) | 1U;
  1032. while (&array_[current] != h) {
  1033. array_[current].displacements.FetchSubRelaxed(1);
  1034. current = ModTableSize(current + increment);
  1035. }
  1036. }
  1037. inline void FixedHyperClockTable::ReclaimEntryUsage(size_t total_charge) {
  1038. auto old_occupancy = occupancy_.FetchSub(1U);
  1039. (void)old_occupancy;
  1040. // No underflow
  1041. assert(old_occupancy > 0);
  1042. auto old_usage = usage_.FetchSubRelaxed(total_charge);
  1043. (void)old_usage;
  1044. // No underflow
  1045. assert(old_usage >= total_charge);
  1046. }
  1047. inline void FixedHyperClockTable::Evict(size_t requested_charge, InsertState&,
  1048. EvictionData* data) {
  1049. // precondition
  1050. assert(requested_charge > 0);
  1051. // TODO: make a tuning parameter?
  1052. constexpr size_t step_size = 4;
  1053. // First (concurrent) increment clock pointer
  1054. uint64_t old_clock_pointer = clock_pointer_.FetchAddRelaxed(step_size);
  1055. // Cap the eviction effort at this thread (along with those operating in
  1056. // parallel) circling through the whole structure kMaxCountdown times.
  1057. // In other words, this eviction run must find something/anything that is
  1058. // unreferenced at start of and during the eviction run that isn't reclaimed
  1059. // by a concurrent eviction run.
  1060. uint64_t max_clock_pointer =
  1061. old_clock_pointer + (ClockHandle::kMaxCountdown << length_bits_);
  1062. for (;;) {
  1063. for (size_t i = 0; i < step_size; i++) {
  1064. HandleImpl& h = array_[ModTableSize(Lower32of64(old_clock_pointer + i))];
  1065. bool evicting = ClockUpdate(h, data);
  1066. if (evicting) {
  1067. Rollback(h.hashed_key, &h);
  1068. TrackAndReleaseEvictedEntry(&h);
  1069. }
  1070. }
  1071. // Loop exit condition
  1072. if (data->freed_charge >= requested_charge) {
  1073. return;
  1074. }
  1075. if (old_clock_pointer >= max_clock_pointer) {
  1076. return;
  1077. }
  1078. if (IsEvictionEffortExceeded(*data)) {
  1079. eviction_effort_exceeded_count_.FetchAddRelaxed(1);
  1080. return;
  1081. }
  1082. // Advance clock pointer (concurrently)
  1083. old_clock_pointer = clock_pointer_.FetchAddRelaxed(step_size);
  1084. }
  1085. }
  1086. template <class Table>
  1087. ClockCacheShard<Table>::ClockCacheShard(
  1088. size_t capacity, bool strict_capacity_limit,
  1089. CacheMetadataChargePolicy metadata_charge_policy,
  1090. MemoryAllocator* allocator,
  1091. const Cache::EvictionCallback* eviction_callback, const uint32_t* hash_seed,
  1092. const typename Table::Opts& opts)
  1093. : CacheShardBase(metadata_charge_policy),
  1094. table_(capacity, strict_capacity_limit, metadata_charge_policy, allocator,
  1095. eviction_callback, hash_seed, opts) {
  1096. // Initial charge metadata should not exceed capacity
  1097. assert(table_.GetUsage() <= table_.GetCapacity() ||
  1098. table_.GetCapacity() < sizeof(HandleImpl));
  1099. }
  1100. template <class Table>
  1101. void ClockCacheShard<Table>::EraseUnRefEntries() {
  1102. table_.EraseUnRefEntries();
  1103. }
  1104. template <class Table>
  1105. void ClockCacheShard<Table>::ApplyToSomeEntries(
  1106. const std::function<void(const Slice& key, Cache::ObjectPtr value,
  1107. size_t charge,
  1108. const Cache::CacheItemHelper* helper)>& callback,
  1109. size_t average_entries_per_lock, size_t* state) {
  1110. // The state will be a simple index into the table. Even with a dynamic
  1111. // hyper clock cache, entries will generally stay in their existing
  1112. // slots, so we don't need to be aware of the high-level organization
  1113. // that makes lookup efficient.
  1114. size_t length = table_.GetTableSize();
  1115. assert(average_entries_per_lock > 0);
  1116. size_t index_begin = *state;
  1117. size_t index_end = index_begin + average_entries_per_lock;
  1118. if (index_end >= length) {
  1119. // Going to end.
  1120. index_end = length;
  1121. *state = SIZE_MAX;
  1122. } else {
  1123. *state = index_end;
  1124. }
  1125. auto hash_seed = table_.GetHashSeed();
  1126. ConstApplyToEntriesRange(
  1127. [callback, hash_seed](const HandleImpl& h) {
  1128. UniqueId64x2 unhashed;
  1129. callback(ReverseHash(h.hashed_key, &unhashed, hash_seed), h.value,
  1130. h.GetTotalCharge(), h.helper);
  1131. },
  1132. table_.HandlePtr(index_begin), table_.HandlePtr(index_end), false);
  1133. }
  1134. int FixedHyperClockTable::CalcHashBits(
  1135. size_t capacity, size_t estimated_value_size,
  1136. CacheMetadataChargePolicy metadata_charge_policy) {
  1137. double average_slot_charge = estimated_value_size * kLoadFactor;
  1138. if (metadata_charge_policy == kFullChargeCacheMetadata) {
  1139. average_slot_charge += sizeof(HandleImpl);
  1140. }
  1141. assert(average_slot_charge > 0.0);
  1142. uint64_t num_slots =
  1143. static_cast<uint64_t>(capacity / average_slot_charge + 0.999999);
  1144. int hash_bits = FloorLog2((num_slots << 1) - 1);
  1145. if (metadata_charge_policy == kFullChargeCacheMetadata) {
  1146. // For very small estimated value sizes, it's possible to overshoot
  1147. while (hash_bits > 0 &&
  1148. uint64_t{sizeof(HandleImpl)} << hash_bits > capacity) {
  1149. hash_bits--;
  1150. }
  1151. }
  1152. return hash_bits;
  1153. }
  1154. template <class Table>
  1155. void ClockCacheShard<Table>::SetCapacity(size_t capacity) {
  1156. table_.SetCapacity(capacity);
  1157. // next Insert will take care of any necessary evictions
  1158. }
  1159. template <class Table>
  1160. void ClockCacheShard<Table>::SetStrictCapacityLimit(
  1161. bool strict_capacity_limit) {
  1162. table_.SetStrictCapacityLimit(strict_capacity_limit);
  1163. // next Insert will take care of any necessary evictions
  1164. }
  1165. template <class Table>
  1166. Status ClockCacheShard<Table>::Insert(const Slice& key,
  1167. const UniqueId64x2& hashed_key,
  1168. Cache::ObjectPtr value,
  1169. const Cache::CacheItemHelper* helper,
  1170. size_t charge, HandleImpl** handle,
  1171. Cache::Priority priority) {
  1172. if (UNLIKELY(key.size() != kCacheKeySize)) {
  1173. return Status::NotSupported("ClockCache only supports key size " +
  1174. std::to_string(kCacheKeySize) + "B");
  1175. }
  1176. ClockHandleBasicData proto;
  1177. proto.hashed_key = hashed_key;
  1178. proto.value = value;
  1179. proto.helper = helper;
  1180. proto.total_charge = charge;
  1181. return table_.template Insert<Table>(proto, handle, priority);
  1182. }
  1183. template <class Table>
  1184. typename Table::HandleImpl* ClockCacheShard<Table>::CreateStandalone(
  1185. const Slice& key, const UniqueId64x2& hashed_key, Cache::ObjectPtr obj,
  1186. const Cache::CacheItemHelper* helper, size_t charge, bool allow_uncharged) {
  1187. if (UNLIKELY(key.size() != kCacheKeySize)) {
  1188. return nullptr;
  1189. }
  1190. ClockHandleBasicData proto;
  1191. proto.hashed_key = hashed_key;
  1192. proto.value = obj;
  1193. proto.helper = helper;
  1194. proto.total_charge = charge;
  1195. return table_.template CreateStandalone<Table>(proto, allow_uncharged);
  1196. }
  1197. template <class Table>
  1198. typename ClockCacheShard<Table>::HandleImpl* ClockCacheShard<Table>::Lookup(
  1199. const Slice& key, const UniqueId64x2& hashed_key) {
  1200. if (UNLIKELY(key.size() != kCacheKeySize)) {
  1201. return nullptr;
  1202. }
  1203. return table_.Lookup(hashed_key);
  1204. }
  1205. template <class Table>
  1206. bool ClockCacheShard<Table>::Ref(HandleImpl* h) {
  1207. if (h == nullptr) {
  1208. return false;
  1209. }
  1210. table_.Ref(*h);
  1211. return true;
  1212. }
  1213. template <class Table>
  1214. bool ClockCacheShard<Table>::Release(HandleImpl* handle, bool useful,
  1215. bool erase_if_last_ref) {
  1216. if (handle == nullptr) {
  1217. return false;
  1218. }
  1219. return table_.Release(handle, useful, erase_if_last_ref);
  1220. }
  1221. #ifndef NDEBUG
  1222. template <class Table>
  1223. void ClockCacheShard<Table>::TEST_RefN(HandleImpl* h, size_t n) {
  1224. table_.TEST_RefN(*h, n);
  1225. }
  1226. template <class Table>
  1227. void ClockCacheShard<Table>::TEST_ReleaseN(HandleImpl* h, size_t n) {
  1228. table_.TEST_ReleaseN(h, n);
  1229. }
  1230. #endif
  1231. template <class Table>
  1232. bool ClockCacheShard<Table>::Release(HandleImpl* handle,
  1233. bool erase_if_last_ref) {
  1234. return Release(handle, /*useful=*/true, erase_if_last_ref);
  1235. }
  1236. template <class Table>
  1237. void ClockCacheShard<Table>::Erase(const Slice& key,
  1238. const UniqueId64x2& hashed_key) {
  1239. if (UNLIKELY(key.size() != kCacheKeySize)) {
  1240. return;
  1241. }
  1242. table_.Erase(hashed_key);
  1243. }
  1244. template <class Table>
  1245. size_t ClockCacheShard<Table>::GetUsage() const {
  1246. return table_.GetUsage();
  1247. }
  1248. template <class Table>
  1249. size_t ClockCacheShard<Table>::GetStandaloneUsage() const {
  1250. return table_.GetStandaloneUsage();
  1251. }
  1252. template <class Table>
  1253. size_t ClockCacheShard<Table>::GetCapacity() const {
  1254. return table_.GetCapacity();
  1255. }
  1256. template <class Table>
  1257. size_t ClockCacheShard<Table>::GetPinnedUsage() const {
  1258. // Computes the pinned usage by scanning the whole hash table. This
  1259. // is slow, but avoids keeping an exact counter on the clock usage,
  1260. // i.e., the number of not externally referenced elements.
  1261. // Why avoid this counter? Because Lookup removes elements from the clock
  1262. // list, so it would need to update the pinned usage every time,
  1263. // which creates additional synchronization costs.
  1264. size_t table_pinned_usage = 0;
  1265. const bool charge_metadata =
  1266. metadata_charge_policy_ == kFullChargeCacheMetadata;
  1267. ConstApplyToEntriesRange(
  1268. [&table_pinned_usage, charge_metadata](const HandleImpl& h) {
  1269. uint64_t meta = h.meta.LoadRelaxed();
  1270. uint64_t refcount = GetRefcount(meta);
  1271. // Holding one ref for ConstApplyToEntriesRange
  1272. assert(refcount > 0);
  1273. if (refcount > 1) {
  1274. table_pinned_usage += h.GetTotalCharge();
  1275. if (charge_metadata) {
  1276. table_pinned_usage += sizeof(HandleImpl);
  1277. }
  1278. }
  1279. },
  1280. table_.HandlePtr(0), table_.HandlePtr(table_.GetTableSize()), true);
  1281. return table_pinned_usage + table_.GetStandaloneUsage();
  1282. }
  1283. template <class Table>
  1284. size_t ClockCacheShard<Table>::GetOccupancyCount() const {
  1285. return table_.GetOccupancy();
  1286. }
  1287. template <class Table>
  1288. size_t ClockCacheShard<Table>::GetOccupancyLimit() const {
  1289. return table_.GetOccupancyLimit();
  1290. }
  1291. template <class Table>
  1292. size_t ClockCacheShard<Table>::GetTableAddressCount() const {
  1293. return table_.GetTableSize();
  1294. }
  1295. // Explicit instantiation
  1296. template class ClockCacheShard<FixedHyperClockTable>;
  1297. template class ClockCacheShard<AutoHyperClockTable>;
  1298. template <class Table>
  1299. BaseHyperClockCache<Table>::BaseHyperClockCache(
  1300. const HyperClockCacheOptions& opts)
  1301. : ShardedCache<ClockCacheShard<Table>>(opts) {
  1302. // TODO: should not need to go through two levels of pointer indirection to
  1303. // get to table entries
  1304. size_t per_shard = this->GetPerShardCapacity();
  1305. MemoryAllocator* alloc = this->memory_allocator();
  1306. this->InitShards([&](Shard* cs) {
  1307. typename Table::Opts table_opts{opts};
  1308. new (cs) Shard(per_shard, opts.strict_capacity_limit,
  1309. opts.metadata_charge_policy, alloc,
  1310. &this->eviction_callback_, &this->hash_seed_, table_opts);
  1311. });
  1312. }
  1313. template <class Table>
  1314. Cache::ObjectPtr BaseHyperClockCache<Table>::Value(Handle* handle) {
  1315. return static_cast<const typename Table::HandleImpl*>(handle)->value;
  1316. }
  1317. template <class Table>
  1318. size_t BaseHyperClockCache<Table>::GetCharge(Handle* handle) const {
  1319. return static_cast<const typename Table::HandleImpl*>(handle)
  1320. ->GetTotalCharge();
  1321. }
  1322. template <class Table>
  1323. const Cache::CacheItemHelper* BaseHyperClockCache<Table>::GetCacheItemHelper(
  1324. Handle* handle) const {
  1325. auto h = static_cast<const typename Table::HandleImpl*>(handle);
  1326. return h->helper;
  1327. }
  1328. template <class Table>
  1329. void BaseHyperClockCache<Table>::ApplyToHandle(
  1330. Cache* cache, Handle* handle,
  1331. const std::function<void(const Slice& key, Cache::ObjectPtr value,
  1332. size_t charge, const CacheItemHelper* helper)>&
  1333. callback) {
  1334. BaseHyperClockCache<Table>* cache_ptr =
  1335. static_cast<BaseHyperClockCache<Table>*>(cache);
  1336. auto h = static_cast<const typename Table::HandleImpl*>(handle);
  1337. UniqueId64x2 unhashed;
  1338. auto hash_seed = cache_ptr->GetShard(h->GetHash()).GetTable().GetHashSeed();
  1339. callback(
  1340. ClockCacheShard<Table>::ReverseHash(h->hashed_key, &unhashed, hash_seed),
  1341. h->value, h->GetTotalCharge(), h->helper);
  1342. }
  1343. namespace {
  1344. // For each cache shard, estimate what the table load factor would be if
  1345. // cache filled to capacity with average entries. This is considered
  1346. // indicative of a potential problem if the shard is essentially operating
  1347. // "at limit", which we define as high actual usage (>80% of capacity)
  1348. // or actual occupancy very close to limit (>95% of limit).
  1349. // Also, for each shard compute the recommended estimated_entry_charge,
  1350. // and keep the minimum one for use as overall recommendation.
  1351. void AddShardEvaluation(const FixedHyperClockCache::Shard& shard,
  1352. std::vector<double>& predicted_load_factors,
  1353. size_t& min_recommendation) {
  1354. size_t usage = shard.GetUsage() - shard.GetStandaloneUsage();
  1355. size_t capacity = shard.GetCapacity();
  1356. double usage_ratio = 1.0 * usage / capacity;
  1357. size_t occupancy = shard.GetOccupancyCount();
  1358. size_t occ_limit = shard.GetOccupancyLimit();
  1359. double occ_ratio = 1.0 * occupancy / occ_limit;
  1360. if (usage == 0 || occupancy == 0 || (usage_ratio < 0.8 && occ_ratio < 0.95)) {
  1361. // Skip as described above
  1362. return;
  1363. }
  1364. // If filled to capacity, what would the occupancy ratio be?
  1365. double ratio = occ_ratio / usage_ratio;
  1366. // Given max load factor, what that load factor be?
  1367. double lf = ratio * FixedHyperClockTable::kStrictLoadFactor;
  1368. predicted_load_factors.push_back(lf);
  1369. // Update min_recommendation also
  1370. size_t recommendation = usage / occupancy;
  1371. min_recommendation = std::min(min_recommendation, recommendation);
  1372. }
  1373. bool IsSlotOccupied(const ClockHandle& h) {
  1374. return (h.meta.LoadRelaxed() >> ClockHandle::kStateShift) != 0;
  1375. }
  1376. } // namespace
  1377. // NOTE: GCC might warn about subobject linkage if this is in anon namespace
  1378. template <size_t N = 500>
  1379. class LoadVarianceStats {
  1380. public:
  1381. std::string Report() const {
  1382. return "Overall " + PercentStr(positive_count_, samples_) + " (" +
  1383. std::to_string(positive_count_) + "/" + std::to_string(samples_) +
  1384. "), Min/Max/Window = " + PercentStr(min_, N) + "/" +
  1385. PercentStr(max_, N) + "/" + std::to_string(N) +
  1386. ", MaxRun{Pos/Neg} = " + std::to_string(max_pos_run_) + "/" +
  1387. std::to_string(max_neg_run_);
  1388. }
  1389. void Add(bool positive) {
  1390. recent_[samples_ % N] = positive;
  1391. if (positive) {
  1392. ++positive_count_;
  1393. ++cur_pos_run_;
  1394. max_pos_run_ = std::max(max_pos_run_, cur_pos_run_);
  1395. cur_neg_run_ = 0;
  1396. } else {
  1397. ++cur_neg_run_;
  1398. max_neg_run_ = std::max(max_neg_run_, cur_neg_run_);
  1399. cur_pos_run_ = 0;
  1400. }
  1401. ++samples_;
  1402. if (samples_ >= N) {
  1403. size_t count_set = recent_.count();
  1404. max_ = std::max(max_, count_set);
  1405. min_ = std::min(min_, count_set);
  1406. }
  1407. }
  1408. private:
  1409. size_t max_ = 0;
  1410. size_t min_ = N;
  1411. size_t positive_count_ = 0;
  1412. size_t samples_ = 0;
  1413. size_t max_pos_run_ = 0;
  1414. size_t cur_pos_run_ = 0;
  1415. size_t max_neg_run_ = 0;
  1416. size_t cur_neg_run_ = 0;
  1417. std::bitset<N> recent_;
  1418. static std::string PercentStr(size_t a, size_t b) {
  1419. if (b == 0) {
  1420. return "??%";
  1421. } else {
  1422. return std::to_string(uint64_t{100} * a / b) + "%";
  1423. }
  1424. }
  1425. };
  1426. template <class Table>
  1427. void BaseHyperClockCache<Table>::ReportProblems(
  1428. const std::shared_ptr<Logger>& info_log) const {
  1429. if (info_log->GetInfoLogLevel() <= InfoLogLevel::DEBUG_LEVEL) {
  1430. LoadVarianceStats slot_stats;
  1431. uint64_t eviction_effort_exceeded_count = 0;
  1432. this->ForEachShard([&](const BaseHyperClockCache<Table>::Shard* shard) {
  1433. size_t count = shard->GetTableAddressCount();
  1434. for (size_t i = 0; i < count; ++i) {
  1435. slot_stats.Add(IsSlotOccupied(*shard->GetTable().HandlePtr(i)));
  1436. }
  1437. eviction_effort_exceeded_count +=
  1438. shard->GetTable().GetEvictionEffortExceededCount();
  1439. });
  1440. ROCKS_LOG_AT_LEVEL(info_log, InfoLogLevel::DEBUG_LEVEL,
  1441. "Slot occupancy stats: %s", slot_stats.Report().c_str());
  1442. ROCKS_LOG_AT_LEVEL(info_log, InfoLogLevel::DEBUG_LEVEL,
  1443. "Eviction effort exceeded: %" PRIu64,
  1444. eviction_effort_exceeded_count);
  1445. }
  1446. }
  1447. void FixedHyperClockCache::ReportProblems(
  1448. const std::shared_ptr<Logger>& info_log) const {
  1449. BaseHyperClockCache::ReportProblems(info_log);
  1450. uint32_t shard_count = GetNumShards();
  1451. std::vector<double> predicted_load_factors;
  1452. size_t min_recommendation = SIZE_MAX;
  1453. ForEachShard([&](const FixedHyperClockCache::Shard* shard) {
  1454. AddShardEvaluation(*shard, predicted_load_factors, min_recommendation);
  1455. });
  1456. if (predicted_load_factors.empty()) {
  1457. // None operating "at limit" -> nothing to report
  1458. return;
  1459. }
  1460. std::sort(predicted_load_factors.begin(), predicted_load_factors.end());
  1461. // First, if the average load factor is within spec, we aren't going to
  1462. // complain about a few shards being out of spec.
  1463. // NOTE: this is only the average among cache shards operating "at limit,"
  1464. // which should be representative of what we care about. It it normal, even
  1465. // desirable, for a cache to operate "at limit" so this should not create
  1466. // selection bias. See AddShardEvaluation().
  1467. // TODO: Consider detecting cases where decreasing the number of shards
  1468. // would be good, e.g. serious imbalance among shards.
  1469. double average_load_factor =
  1470. std::accumulate(predicted_load_factors.begin(),
  1471. predicted_load_factors.end(), 0.0) /
  1472. shard_count;
  1473. constexpr double kLowSpecLoadFactor = FixedHyperClockTable::kLoadFactor / 2;
  1474. constexpr double kMidSpecLoadFactor =
  1475. FixedHyperClockTable::kLoadFactor / 1.414;
  1476. if (average_load_factor > FixedHyperClockTable::kLoadFactor) {
  1477. // Out of spec => Consider reporting load factor too high
  1478. // Estimate effective overall capacity loss due to enforcing occupancy limit
  1479. double lost_portion = 0.0;
  1480. int over_count = 0;
  1481. for (double lf : predicted_load_factors) {
  1482. if (lf > FixedHyperClockTable::kStrictLoadFactor) {
  1483. ++over_count;
  1484. lost_portion +=
  1485. (lf - FixedHyperClockTable::kStrictLoadFactor) / lf / shard_count;
  1486. }
  1487. }
  1488. // >= 20% loss -> error
  1489. // >= 10% loss -> consistent warning
  1490. // >= 1% loss -> intermittent warning
  1491. InfoLogLevel level = InfoLogLevel::INFO_LEVEL;
  1492. bool report = true;
  1493. if (lost_portion > 0.2) {
  1494. level = InfoLogLevel::ERROR_LEVEL;
  1495. } else if (lost_portion > 0.1) {
  1496. level = InfoLogLevel::WARN_LEVEL;
  1497. } else if (lost_portion > 0.01) {
  1498. int report_percent = static_cast<int>(lost_portion * 100.0);
  1499. if (Random::GetTLSInstance()->PercentTrue(report_percent)) {
  1500. level = InfoLogLevel::WARN_LEVEL;
  1501. }
  1502. } else {
  1503. // don't report
  1504. report = false;
  1505. }
  1506. if (report) {
  1507. ROCKS_LOG_AT_LEVEL(
  1508. info_log, level,
  1509. "FixedHyperClockCache@%p unable to use estimated %.1f%% capacity "
  1510. "because of full occupancy in %d/%u cache shards "
  1511. "(estimated_entry_charge too high). "
  1512. "Recommend estimated_entry_charge=%zu",
  1513. this, lost_portion * 100.0, over_count, (unsigned)shard_count,
  1514. min_recommendation);
  1515. }
  1516. } else if (average_load_factor < kLowSpecLoadFactor) {
  1517. // Out of spec => Consider reporting load factor too low
  1518. // But cautiously because low is not as big of a problem.
  1519. // Only report if highest occupancy shard is also below
  1520. // spec and only if average is substantially out of spec
  1521. if (predicted_load_factors.back() < kLowSpecLoadFactor &&
  1522. average_load_factor < kLowSpecLoadFactor / 1.414) {
  1523. InfoLogLevel level = InfoLogLevel::INFO_LEVEL;
  1524. if (average_load_factor < kLowSpecLoadFactor / 2) {
  1525. level = InfoLogLevel::WARN_LEVEL;
  1526. }
  1527. ROCKS_LOG_AT_LEVEL(
  1528. info_log, level,
  1529. "FixedHyperClockCache@%p table has low occupancy at full capacity. "
  1530. "Higher estimated_entry_charge (about %.1fx) would likely improve "
  1531. "performance. Recommend estimated_entry_charge=%zu",
  1532. this, kMidSpecLoadFactor / average_load_factor, min_recommendation);
  1533. }
  1534. }
  1535. }
  1536. // =======================================================================
  1537. // AutoHyperClockCache
  1538. // =======================================================================
  1539. // See AutoHyperClockTable::length_info_ etc. for how the linear hashing
  1540. // metadata is encoded. Here are some example values:
  1541. //
  1542. // Used length | min shift | threshold | max shift
  1543. // 2 | 1 | 0 | 1
  1544. // 3 | 1 | 1 | 2
  1545. // 4 | 2 | 0 | 2
  1546. // 5 | 2 | 1 | 3
  1547. // 6 | 2 | 2 | 3
  1548. // 7 | 2 | 3 | 3
  1549. // 8 | 3 | 0 | 3
  1550. // 9 | 3 | 1 | 4
  1551. // ...
  1552. // Note:
  1553. // * min shift = floor(log2(used length))
  1554. // * max shift = ceil(log2(used length))
  1555. // * used length == (1 << shift) + threshold
  1556. // Also, shift=0 is never used in practice, so is reserved for "unset"
  1557. namespace {
  1558. inline int LengthInfoToMinShift(uint64_t length_info) {
  1559. int mask_shift = BitwiseAnd(length_info, int{255});
  1560. assert(mask_shift <= 63);
  1561. assert(mask_shift > 0);
  1562. return mask_shift;
  1563. }
  1564. inline size_t LengthInfoToThreshold(uint64_t length_info) {
  1565. return static_cast<size_t>(length_info >> 8);
  1566. }
  1567. inline size_t LengthInfoToUsedLength(uint64_t length_info) {
  1568. size_t threshold = LengthInfoToThreshold(length_info);
  1569. int shift = LengthInfoToMinShift(length_info);
  1570. assert(threshold < (size_t{1} << shift));
  1571. size_t used_length = (size_t{1} << shift) + threshold;
  1572. assert(used_length >= 2);
  1573. return used_length;
  1574. }
  1575. inline uint64_t UsedLengthToLengthInfo(size_t used_length) {
  1576. assert(used_length >= 2);
  1577. int shift = FloorLog2(used_length);
  1578. uint64_t threshold = BottomNBits(used_length, shift);
  1579. uint64_t length_info =
  1580. (uint64_t{threshold} << 8) + static_cast<uint64_t>(shift);
  1581. assert(LengthInfoToUsedLength(length_info) == used_length);
  1582. assert(LengthInfoToMinShift(length_info) == shift);
  1583. assert(LengthInfoToThreshold(length_info) == threshold);
  1584. return length_info;
  1585. }
  1586. // Avoid potential initialization order race with port::kPageSize
  1587. constexpr size_t kPresumedPageSize = 4096;
  1588. inline size_t GetStartingLength(size_t capacity) {
  1589. if (capacity > kPresumedPageSize) {
  1590. // Start with one memory page
  1591. return kPresumedPageSize / sizeof(AutoHyperClockTable::HandleImpl);
  1592. } else {
  1593. // Mostly to make unit tests happy
  1594. return 4;
  1595. }
  1596. }
  1597. inline size_t GetHomeIndex(uint64_t hash, int shift) {
  1598. return static_cast<size_t>(BottomNBits(hash, shift));
  1599. }
  1600. inline void GetHomeIndexAndShift(uint64_t length_info, uint64_t hash,
  1601. size_t* home, int* shift) {
  1602. int min_shift = LengthInfoToMinShift(length_info);
  1603. size_t threshold = LengthInfoToThreshold(length_info);
  1604. bool extra_shift = GetHomeIndex(hash, min_shift) < threshold;
  1605. *home = GetHomeIndex(hash, min_shift + extra_shift);
  1606. *shift = min_shift + extra_shift;
  1607. assert(*home < LengthInfoToUsedLength(length_info));
  1608. }
  1609. inline int GetShiftFromNextWithShift(uint64_t next_with_shift) {
  1610. return BitwiseAnd(next_with_shift,
  1611. AutoHyperClockTable::HandleImpl::kShiftMask);
  1612. }
  1613. inline size_t GetNextFromNextWithShift(uint64_t next_with_shift) {
  1614. return static_cast<size_t>(next_with_shift >>
  1615. AutoHyperClockTable::HandleImpl::kNextShift);
  1616. }
  1617. inline uint64_t MakeNextWithShift(size_t next, int shift) {
  1618. return (uint64_t{next} << AutoHyperClockTable::HandleImpl::kNextShift) |
  1619. static_cast<uint64_t>(shift);
  1620. }
  1621. inline uint64_t MakeNextWithShiftEnd(size_t head, int shift) {
  1622. return AutoHyperClockTable::HandleImpl::kNextEndFlags |
  1623. MakeNextWithShift(head, shift);
  1624. }
  1625. // Helper function for Lookup
  1626. inline bool MatchAndRef(const UniqueId64x2* hashed_key, const ClockHandle& h,
  1627. int shift = 0, size_t home = 0,
  1628. bool* full_match_or_unknown = nullptr) {
  1629. // Must be at least something to match
  1630. assert(hashed_key || shift > 0);
  1631. uint64_t old_meta;
  1632. // (Optimistically) increment acquire counter.
  1633. old_meta = h.meta.FetchAdd(ClockHandle::kAcquireIncrement);
  1634. // Check if it's a referencable (sharable) entry
  1635. if ((old_meta & (uint64_t{ClockHandle::kStateShareableBit}
  1636. << ClockHandle::kStateShift)) == 0) {
  1637. // For non-sharable states, incrementing the acquire counter has no effect
  1638. // so we don't need to undo it. Furthermore, we cannot safely undo
  1639. // it because we did not acquire a read reference to lock the
  1640. // entry in a Shareable state.
  1641. if (full_match_or_unknown) {
  1642. *full_match_or_unknown = true;
  1643. }
  1644. return false;
  1645. }
  1646. // Else acquired a read reference
  1647. assert(GetRefcount(old_meta + ClockHandle::kAcquireIncrement) > 0);
  1648. if (hashed_key && h.hashed_key == *hashed_key &&
  1649. LIKELY(old_meta & (uint64_t{ClockHandle::kStateVisibleBit}
  1650. << ClockHandle::kStateShift))) {
  1651. // Match on full key, visible
  1652. if (full_match_or_unknown) {
  1653. *full_match_or_unknown = true;
  1654. }
  1655. return true;
  1656. } else if (shift > 0 && home == BottomNBits(h.hashed_key[1], shift)) {
  1657. // NOTE: upper 32 bits of hashed_key[0] is used for sharding
  1658. // Match on home address, possibly invisible
  1659. if (full_match_or_unknown) {
  1660. *full_match_or_unknown = false;
  1661. }
  1662. return true;
  1663. } else {
  1664. // Mismatch. Pretend we never took the reference
  1665. Unref(h);
  1666. if (full_match_or_unknown) {
  1667. *full_match_or_unknown = false;
  1668. }
  1669. return false;
  1670. }
  1671. }
  1672. // Assumes a chain rewrite lock prevents concurrent modification of
  1673. // these chain pointers
  1674. void UpgradeShiftsOnRange(AutoHyperClockTable::HandleImpl* arr,
  1675. size_t& frontier, uint64_t stop_before_or_new_tail,
  1676. int old_shift, int new_shift) {
  1677. assert(frontier != SIZE_MAX);
  1678. assert(new_shift == old_shift + 1);
  1679. (void)old_shift;
  1680. (void)new_shift;
  1681. using HandleImpl = AutoHyperClockTable::HandleImpl;
  1682. for (;;) {
  1683. uint64_t next_with_shift = arr[frontier].chain_next_with_shift.Load();
  1684. assert(GetShiftFromNextWithShift(next_with_shift) == old_shift);
  1685. if (next_with_shift == stop_before_or_new_tail) {
  1686. // Stopping at entry with pointer matching "stop before"
  1687. assert(!HandleImpl::IsEnd(next_with_shift));
  1688. return;
  1689. }
  1690. if (HandleImpl::IsEnd(next_with_shift)) {
  1691. // Also update tail to new tail
  1692. assert(HandleImpl::IsEnd(stop_before_or_new_tail));
  1693. arr[frontier].chain_next_with_shift.Store(stop_before_or_new_tail);
  1694. // Mark nothing left to upgrade
  1695. frontier = SIZE_MAX;
  1696. return;
  1697. }
  1698. // Next is another entry to process, so upgrade and advance frontier
  1699. arr[frontier].chain_next_with_shift.FetchAdd(1U);
  1700. assert(GetShiftFromNextWithShift(next_with_shift + 1) == new_shift);
  1701. frontier = GetNextFromNextWithShift(next_with_shift);
  1702. }
  1703. }
  1704. size_t CalcOccupancyLimit(size_t used_length) {
  1705. return static_cast<size_t>(used_length * AutoHyperClockTable::kMaxLoadFactor +
  1706. 0.999);
  1707. }
  1708. } // namespace
  1709. // An RAII wrapper for locking a chain of entries (flag bit on the head)
  1710. // so that there is only one thread allowed to remove entries from the
  1711. // chain, or to rewrite it by splitting for Grow. Without the lock,
  1712. // all lookups and insertions at the head can proceed wait-free.
  1713. // The class also provides functions for safely manipulating the head pointer
  1714. // while holding the lock--or wanting to should it become non-empty.
  1715. //
  1716. // The flag bits on the head are such that the head cannot be locked if it
  1717. // is an empty chain, so that a "blind" FetchOr will try to lock a non-empty
  1718. // chain but have no effect on an empty chain. When a potential rewrite
  1719. // operation see an empty head pointer, there is no need to lock as the
  1720. // operation is a no-op. However, there are some cases such as CAS-update
  1721. // where locking might be required after initially not being needed, if the
  1722. // operation is forced to revisit the head pointer.
  1723. class AutoHyperClockTable::ChainRewriteLock {
  1724. public:
  1725. using HandleImpl = AutoHyperClockTable::HandleImpl;
  1726. // Acquire lock if head of h is not an end
  1727. explicit ChainRewriteLock(HandleImpl* h, RelaxedAtomic<uint64_t>& yield_count)
  1728. : head_ptr_(&h->head_next_with_shift) {
  1729. Acquire(yield_count);
  1730. }
  1731. // RAII wrap existing lock held (or end)
  1732. explicit ChainRewriteLock(HandleImpl* h,
  1733. RelaxedAtomic<uint64_t>& /*yield_count*/,
  1734. uint64_t already_locked_or_end)
  1735. : head_ptr_(&h->head_next_with_shift) {
  1736. saved_head_ = already_locked_or_end;
  1737. // already locked or end
  1738. assert(saved_head_ & HandleImpl::kHeadLocked);
  1739. }
  1740. ~ChainRewriteLock() {
  1741. if (!IsEnd()) {
  1742. // Release lock
  1743. uint64_t old = head_ptr_->FetchAnd(~HandleImpl::kHeadLocked);
  1744. (void)old;
  1745. assert((old & HandleImpl::kNextEndFlags) == HandleImpl::kHeadLocked);
  1746. }
  1747. }
  1748. void Reset(HandleImpl* h, RelaxedAtomic<uint64_t>& yield_count) {
  1749. this->~ChainRewriteLock();
  1750. new (this) ChainRewriteLock(h, yield_count);
  1751. }
  1752. // Expected current state, assuming no parallel updates.
  1753. uint64_t GetSavedHead() const { return saved_head_; }
  1754. bool CasUpdate(uint64_t next_with_shift,
  1755. RelaxedAtomic<uint64_t>& yield_count) {
  1756. uint64_t new_head = next_with_shift | HandleImpl::kHeadLocked;
  1757. uint64_t expected = GetSavedHead();
  1758. bool success = head_ptr_->CasStrong(expected, new_head);
  1759. if (success) {
  1760. // Ensure IsEnd() is kept up-to-date, including for dtor
  1761. saved_head_ = new_head;
  1762. } else {
  1763. // Parallel update to head, such as Insert()
  1764. if (IsEnd()) {
  1765. // Didn't previously hold a lock
  1766. if (HandleImpl::IsEnd(expected)) {
  1767. // Still don't need to
  1768. saved_head_ = expected;
  1769. } else {
  1770. // Need to acquire lock before proceeding
  1771. Acquire(yield_count);
  1772. }
  1773. } else {
  1774. // Parallel update must preserve our lock
  1775. assert((expected & HandleImpl::kNextEndFlags) ==
  1776. HandleImpl::kHeadLocked);
  1777. saved_head_ = expected;
  1778. }
  1779. }
  1780. return success;
  1781. }
  1782. bool IsEnd() const { return HandleImpl::IsEnd(saved_head_); }
  1783. private:
  1784. void Acquire(RelaxedAtomic<uint64_t>& yield_count) {
  1785. for (;;) {
  1786. // Acquire removal lock on the chain
  1787. uint64_t old_head = head_ptr_->FetchOr(HandleImpl::kHeadLocked);
  1788. if ((old_head & HandleImpl::kNextEndFlags) != HandleImpl::kHeadLocked) {
  1789. // Either acquired the lock or lock not needed (end)
  1790. assert((old_head & HandleImpl::kNextEndFlags) == 0 ||
  1791. (old_head & HandleImpl::kNextEndFlags) ==
  1792. HandleImpl::kNextEndFlags);
  1793. saved_head_ = old_head | HandleImpl::kHeadLocked;
  1794. break;
  1795. }
  1796. // NOTE: one of the few yield-wait loops, which is rare enough in practice
  1797. // for its performance to be insignificant. (E.g. using C++20 atomic
  1798. // wait/notify would likely be worse because of wasted notify costs.)
  1799. yield_count.FetchAddRelaxed(1);
  1800. std::this_thread::yield();
  1801. }
  1802. }
  1803. AcqRelAtomic<uint64_t>* head_ptr_;
  1804. uint64_t saved_head_;
  1805. };
  1806. AutoHyperClockTable::AutoHyperClockTable(
  1807. size_t capacity, bool strict_capacity_limit,
  1808. CacheMetadataChargePolicy metadata_charge_policy,
  1809. MemoryAllocator* allocator,
  1810. const Cache::EvictionCallback* eviction_callback, const uint32_t* hash_seed,
  1811. const Opts& opts)
  1812. : BaseClockTable(capacity, strict_capacity_limit, opts.eviction_effort_cap,
  1813. metadata_charge_policy, allocator, eviction_callback,
  1814. hash_seed),
  1815. array_(MemMapping::AllocateLazyZeroed(
  1816. sizeof(HandleImpl) * CalcMaxUsableLength(capacity,
  1817. opts.min_avg_value_size,
  1818. metadata_charge_policy))),
  1819. length_info_(UsedLengthToLengthInfo(GetStartingLength(capacity))),
  1820. occupancy_limit_(
  1821. CalcOccupancyLimit(LengthInfoToUsedLength(length_info_.Load()))),
  1822. grow_frontier_(GetTableSize()),
  1823. clock_pointer_mask_(
  1824. BottomNBits(UINT64_MAX, LengthInfoToMinShift(length_info_.Load()))) {
  1825. if (array_.Get() == nullptr) {
  1826. fprintf(stderr,
  1827. "Anonymous mmap for RocksDB HyperClockCache failed. Aborting.\n");
  1828. std::terminate();
  1829. }
  1830. if (metadata_charge_policy ==
  1831. CacheMetadataChargePolicy::kFullChargeCacheMetadata) {
  1832. // NOTE: ignoring page boundaries for simplicity
  1833. usage_.FetchAddRelaxed(size_t{GetTableSize()} * sizeof(HandleImpl));
  1834. }
  1835. static_assert(sizeof(HandleImpl) == 64U,
  1836. "Expecting size / alignment with common cache line size");
  1837. // Populate head pointers
  1838. uint64_t length_info = length_info_.Load();
  1839. int min_shift = LengthInfoToMinShift(length_info);
  1840. int max_shift = min_shift + 1;
  1841. size_t major = uint64_t{1} << min_shift;
  1842. size_t used_length = GetTableSize();
  1843. assert(major <= used_length);
  1844. assert(used_length <= major * 2);
  1845. // Initialize the initial usable set of slots. This slightly odd iteration
  1846. // order makes it easier to get the correct shift amount on each head.
  1847. for (size_t i = 0; i < major; ++i) {
  1848. #ifndef NDEBUG
  1849. int shift;
  1850. size_t home;
  1851. #endif
  1852. if (major + i < used_length) {
  1853. array_[i].head_next_with_shift.StoreRelaxed(
  1854. MakeNextWithShiftEnd(i, max_shift));
  1855. array_[major + i].head_next_with_shift.StoreRelaxed(
  1856. MakeNextWithShiftEnd(major + i, max_shift));
  1857. #ifndef NDEBUG // Extra invariant checking
  1858. GetHomeIndexAndShift(length_info, i, &home, &shift);
  1859. assert(home == i);
  1860. assert(shift == max_shift);
  1861. GetHomeIndexAndShift(length_info, major + i, &home, &shift);
  1862. assert(home == major + i);
  1863. assert(shift == max_shift);
  1864. #endif
  1865. } else {
  1866. array_[i].head_next_with_shift.StoreRelaxed(
  1867. MakeNextWithShiftEnd(i, min_shift));
  1868. #ifndef NDEBUG // Extra invariant checking
  1869. GetHomeIndexAndShift(length_info, i, &home, &shift);
  1870. assert(home == i);
  1871. assert(shift == min_shift);
  1872. GetHomeIndexAndShift(length_info, major + i, &home, &shift);
  1873. assert(home == i);
  1874. assert(shift == min_shift);
  1875. #endif
  1876. }
  1877. }
  1878. }
  1879. AutoHyperClockTable::~AutoHyperClockTable() {
  1880. // As usual, destructor assumes there are no references or active operations
  1881. // on any slot/element in the table.
  1882. // It's possible that there were not enough Insert() after final concurrent
  1883. // Grow to ensure length_info_ (published GetTableSize()) is fully up to
  1884. // date. Probe for first unused slot to ensure we see the whole structure.
  1885. size_t used_end = GetTableSize();
  1886. while (used_end < array_.Count() &&
  1887. array_[used_end].head_next_with_shift.LoadRelaxed() !=
  1888. HandleImpl::kUnusedMarker) {
  1889. used_end++;
  1890. }
  1891. // This check can be extra expensive for a cache that is just created,
  1892. // maybe used for a small number of entries, as in a unit test, and then
  1893. // destroyed. Only do this in rare modes. REVISED: Don't scan the whole mmap,
  1894. // just a reasonable frontier past what we expect to have written.
  1895. #ifdef MUST_FREE_HEAP_ALLOCATIONS
  1896. for (size_t i = used_end; i < array_.Count() && i < used_end + 64U; i++) {
  1897. assert(array_[i].head_next_with_shift.LoadRelaxed() == 0);
  1898. assert(array_[i].chain_next_with_shift.LoadRelaxed() == 0);
  1899. assert(array_[i].meta.LoadRelaxed() == 0);
  1900. }
  1901. #endif // MUST_FREE_HEAP_ALLOCATIONS
  1902. #ifndef NDEBUG // Extra invariant checking
  1903. std::vector<bool> was_populated(used_end);
  1904. std::vector<bool> was_pointed_to(used_end);
  1905. #endif // !NDEBUG
  1906. for (size_t i = 0; i < used_end; i++) {
  1907. HandleImpl& h = array_[i];
  1908. switch (h.meta.LoadRelaxed() >> ClockHandle::kStateShift) {
  1909. case ClockHandle::kStateEmpty:
  1910. // noop
  1911. break;
  1912. case ClockHandle::kStateInvisible: // rare but possible
  1913. case ClockHandle::kStateVisible:
  1914. assert(GetRefcount(h.meta.LoadRelaxed()) == 0);
  1915. h.FreeData(allocator_);
  1916. #ifndef NDEBUG // Extra invariant checking
  1917. usage_.FetchSubRelaxed(h.total_charge);
  1918. occupancy_.FetchSubRelaxed(1U);
  1919. was_populated[i] = true;
  1920. if (!HandleImpl::IsEnd(h.chain_next_with_shift.LoadRelaxed())) {
  1921. assert((h.chain_next_with_shift.LoadRelaxed() &
  1922. HandleImpl::kHeadLocked) == 0);
  1923. size_t next =
  1924. GetNextFromNextWithShift(h.chain_next_with_shift.LoadRelaxed());
  1925. assert(!was_pointed_to[next]);
  1926. was_pointed_to[next] = true;
  1927. }
  1928. #endif // !NDEBUG
  1929. break;
  1930. // otherwise
  1931. default:
  1932. assert(false);
  1933. break;
  1934. }
  1935. #ifndef NDEBUG // Extra invariant checking
  1936. if (!HandleImpl::IsEnd(h.head_next_with_shift.LoadRelaxed())) {
  1937. size_t next =
  1938. GetNextFromNextWithShift(h.head_next_with_shift.LoadRelaxed());
  1939. assert(!was_pointed_to[next]);
  1940. was_pointed_to[next] = true;
  1941. }
  1942. #endif // !NDEBUG
  1943. }
  1944. #ifndef NDEBUG // Extra invariant checking
  1945. // This check is not perfect, but should detect most reasonable cases
  1946. // of abandonned or floating entries, etc. (A floating cycle would not
  1947. // be reported as bad.)
  1948. for (size_t i = 0; i < used_end; i++) {
  1949. if (was_populated[i]) {
  1950. assert(was_pointed_to[i]);
  1951. } else {
  1952. assert(!was_pointed_to[i]);
  1953. }
  1954. }
  1955. #endif // !NDEBUG
  1956. // Metadata charging only follows the published table size
  1957. assert(usage_.LoadRelaxed() == 0 ||
  1958. usage_.LoadRelaxed() == GetTableSize() * sizeof(HandleImpl));
  1959. assert(occupancy_.LoadRelaxed() == 0);
  1960. }
  1961. size_t AutoHyperClockTable::GetTableSize() const {
  1962. return LengthInfoToUsedLength(length_info_.Load());
  1963. }
  1964. size_t AutoHyperClockTable::GetOccupancyLimit() const {
  1965. return occupancy_limit_.LoadRelaxed();
  1966. }
  1967. void AutoHyperClockTable::StartInsert(InsertState& state) {
  1968. state.saved_length_info = length_info_.Load();
  1969. }
  1970. // Because we have linked lists, bugs or even hardware errors can make it
  1971. // possible to create a cycle, which would lead to infinite loop.
  1972. // Furthermore, when we have retry cases in the code, we want to be sure
  1973. // these are not (and do not become) spin-wait loops. Given the assumption
  1974. // of quality hashing and the infeasibility of consistently recurring
  1975. // concurrent modifications to an entry or chain, we can safely bound the
  1976. // number of loop iterations in feasible operation, whether following chain
  1977. // pointers or retrying with some backtracking. A smaller limit is used for
  1978. // stress testing, to detect potential issues such as cycles or spin-waits,
  1979. // and a larger limit is used to break cycles should they occur in production.
  1980. #define CHECK_TOO_MANY_ITERATIONS(i) \
  1981. { \
  1982. assert(i < 768); \
  1983. if (UNLIKELY(i >= 4096)) { \
  1984. std::terminate(); \
  1985. } \
  1986. }
  1987. bool AutoHyperClockTable::GrowIfNeeded(size_t new_occupancy,
  1988. InsertState& state) {
  1989. // new_occupancy has taken into account other threads that are also trying
  1990. // to insert, so as soon as we see sufficient *published* usable size, we
  1991. // can declare success even if we aren't the one that grows the table.
  1992. // However, there's an awkward state where other threads own growing the
  1993. // table to sufficient usable size, but the udpated size is not yet
  1994. // published. If we wait, then that likely slows the ramp-up cache
  1995. // performance. If we unblock ourselves by ensuring we grow by at least one
  1996. // slot, we could technically overshoot required size by number of parallel
  1997. // threads accessing block cache. On balance considering typical cases and
  1998. // the modest consequences of table being slightly too large, the latter
  1999. // seems preferable.
  2000. //
  2001. // So if the published occupancy limit is too small, we unblock ourselves
  2002. // by committing to growing the table by at least one slot. Also note that
  2003. // we might need to grow more than once to actually increase the occupancy
  2004. // limit (due to max load factor < 1.0)
  2005. while (UNLIKELY(new_occupancy > occupancy_limit_.LoadRelaxed())) {
  2006. // At this point we commit the thread to growing unless we've reached the
  2007. // limit (returns false).
  2008. if (!Grow(state)) {
  2009. return false;
  2010. }
  2011. }
  2012. // Success (didn't need to grow, or did successfully)
  2013. return true;
  2014. }
  2015. bool AutoHyperClockTable::Grow(InsertState& state) {
  2016. // Allocate the next grow slot
  2017. size_t grow_home = grow_frontier_.FetchAddRelaxed(1);
  2018. if (grow_home >= array_.Count()) {
  2019. // Can't grow any more.
  2020. // (Tested by unit test ClockCacheTest/Limits)
  2021. // Make sure we don't overflow grow_frontier_ by reaching here repeatedly
  2022. grow_frontier_.StoreRelaxed(array_.Count());
  2023. return false;
  2024. }
  2025. #ifdef COERCE_CONTEXT_SWITCH
  2026. // This is useful in reproducing concurrency issues in Grow()
  2027. while (Random::GetTLSInstance()->OneIn(2)) {
  2028. std::this_thread::yield();
  2029. }
  2030. #endif
  2031. // Basically, to implement https://en.wikipedia.org/wiki/Linear_hashing
  2032. // entries that belong in a new chain starting at grow_home will be
  2033. // split off from the chain starting at old_home, which is computed here.
  2034. int old_shift = FloorLog2(grow_home);
  2035. size_t old_home = BottomNBits(grow_home, old_shift);
  2036. assert(old_home + (size_t{1} << old_shift) == grow_home);
  2037. // Wait here to ensure any Grow operations that would directly feed into
  2038. // this one are finished, though the full waiting actually completes in
  2039. // acquiring the rewrite lock for old_home in SplitForGrow. Here we ensure
  2040. // the expected shift amount has been reached, and there we ensure the
  2041. // chain rewrite lock has been released.
  2042. size_t old_old_home = BottomNBits(grow_home, old_shift - 1);
  2043. for (;;) {
  2044. uint64_t old_old_head = array_[old_old_home].head_next_with_shift.Load();
  2045. if (GetShiftFromNextWithShift(old_old_head) >= old_shift) {
  2046. if ((old_old_head & HandleImpl::kNextEndFlags) !=
  2047. HandleImpl::kHeadLocked) {
  2048. break;
  2049. }
  2050. }
  2051. // NOTE: one of the few yield-wait loops, which is rare enough in practice
  2052. // for its performance to be insignificant.
  2053. yield_count_.FetchAddRelaxed(1);
  2054. std::this_thread::yield();
  2055. }
  2056. // Do the dirty work of splitting the chain, including updating heads and
  2057. // chain nexts for new shift amounts.
  2058. SplitForGrow(grow_home, old_home, old_shift);
  2059. // length_info_ can be updated any time after the new shift amount is
  2060. // published to both heads, potentially before the end of SplitForGrow.
  2061. // But we also can't update length_info_ until the previous Grow operation
  2062. // (with grow_home := this grow_home - 1) has published the new shift amount
  2063. // to both of its heads. However, we don't want to artificially wait here
  2064. // on that Grow that is otherwise irrelevant.
  2065. //
  2066. // We could have each Grow operation advance length_info_ here as far as it
  2067. // can without waiting, by checking for updated shift on the corresponding
  2068. // old home and also stopping at an empty head value for possible grow_home.
  2069. // However, this could increase CPU cache line sharing and in 1/64 cases
  2070. // bring in an extra page from our mmap.
  2071. //
  2072. // Instead, part of the strategy is delegated to DoInsert():
  2073. // * Here we try to bring length_info_ up to date with this grow_home as
  2074. // much as we can without waiting. It will fall short if a previous Grow
  2075. // is still between reserving the grow slot and making the first big step
  2076. // to publish the new shift amount.
  2077. // * To avoid length_info_ being perpetually out-of-date (for a small number
  2078. // of heads) after our last Grow, we do the same when Insert has to "fall
  2079. // forward" due to length_info_ being out-of-date.
  2080. CatchUpLengthInfoNoWait(grow_home);
  2081. // See usage in DoInsert()
  2082. state.likely_empty_slot = grow_home;
  2083. // Success
  2084. return true;
  2085. }
  2086. // See call in Grow()
  2087. void AutoHyperClockTable::CatchUpLengthInfoNoWait(
  2088. size_t known_usable_grow_home) {
  2089. uint64_t current_length_info = length_info_.Load();
  2090. size_t published_usable_size = LengthInfoToUsedLength(current_length_info);
  2091. while (published_usable_size <= known_usable_grow_home) {
  2092. // For when published_usable_size was grow_home
  2093. size_t next_usable_size = published_usable_size + 1;
  2094. uint64_t next_length_info = UsedLengthToLengthInfo(next_usable_size);
  2095. // known_usable_grow_home is known to be ready for Lookup/Insert with
  2096. // the new shift amount, but between that and published usable size, we
  2097. // need to check.
  2098. if (published_usable_size < known_usable_grow_home) {
  2099. int old_shift = FloorLog2(next_usable_size - 1);
  2100. size_t old_home = BottomNBits(published_usable_size, old_shift);
  2101. int shift = GetShiftFromNextWithShift(
  2102. array_[old_home].head_next_with_shift.Load());
  2103. if (shift <= old_shift) {
  2104. // Not ready
  2105. break;
  2106. }
  2107. }
  2108. // CAS update length_info_. This only moves in one direction, so if CAS
  2109. // fails, someone else made progress like we are trying, and we can just
  2110. // pick up the new value and keep going as appropriate.
  2111. if (length_info_.CasStrong(current_length_info, next_length_info)) {
  2112. current_length_info = next_length_info;
  2113. // Update usage_ if metadata charge policy calls for it
  2114. if (metadata_charge_policy_ ==
  2115. CacheMetadataChargePolicy::kFullChargeCacheMetadata) {
  2116. // NOTE: ignoring page boundaries for simplicity
  2117. usage_.FetchAddRelaxed(sizeof(HandleImpl));
  2118. }
  2119. }
  2120. published_usable_size = LengthInfoToUsedLength(current_length_info);
  2121. }
  2122. // After updating lengh_info_ we can update occupancy_limit_,
  2123. // allowing for later operations to update it before us.
  2124. // Note: there is no AcqRelAtomic max operation, so we have to use a CAS loop
  2125. size_t old_occupancy_limit = occupancy_limit_.LoadRelaxed();
  2126. size_t new_occupancy_limit = CalcOccupancyLimit(published_usable_size);
  2127. while (old_occupancy_limit < new_occupancy_limit) {
  2128. if (occupancy_limit_.CasWeakRelaxed(old_occupancy_limit,
  2129. new_occupancy_limit)) {
  2130. break;
  2131. }
  2132. }
  2133. }
  2134. void AutoHyperClockTable::SplitForGrow(size_t grow_home, size_t old_home,
  2135. int old_shift) {
  2136. int new_shift = old_shift + 1;
  2137. HandleImpl* const arr = array_.Get();
  2138. // We implement a somewhat complicated splitting algorithm to ensure that
  2139. // entries are always wait-free visible to Lookup, without Lookup needing
  2140. // to double-check length_info_ to ensure every potentially relevant
  2141. // existing entry is seen. This works step-by-step, carefully sharing
  2142. // unmigrated parts of the chain between the source chain and the new
  2143. // destination chain. This means that Lookup might see a partially migrated
  2144. // chain so has to take that into consideration when checking that it hasn't
  2145. // "jumped off" its intended chain (due to a parallel modification to an
  2146. // "under (de)construction" entry that was found on the chain but has
  2147. // been reassigned).
  2148. //
  2149. // We use a "rewrite lock" on the source and desination chains to exclude
  2150. // removals from those, and we have a prior waiting step that ensures any Grow
  2151. // operations feeding into this one have completed. But this process does have
  2152. // to gracefully handle concurrent insertions to the head of the source chain,
  2153. // and once marked ready, the destination chain.
  2154. //
  2155. // With those considerations, the migration starts with one "big step,"
  2156. // potentially with retries to deal with insertions in parallel. Part of the
  2157. // big step is to mark the two chain heads as updated with the new shift
  2158. // amount, which redirects Lookups to the appropriate new chain.
  2159. //
  2160. // After that big step that updates the heads, the rewrite lock makes it
  2161. // relatively easy to deal with the rest of the migration. Big
  2162. // simplifications come from being able to read the hashed_key of each
  2163. // entry on the chain without needing to hold a read reference, and
  2164. // from never "jumping our to another chain." Concurrent insertions only
  2165. // happen at the chain head, which is outside of what is left to migrate.
  2166. //
  2167. // A series of smaller steps finishes splitting apart the existing chain into
  2168. // two distinct chains, followed by some steps to fully commit the result.
  2169. //
  2170. // Except for trivial cases in which all entries (or remaining entries)
  2171. // on the input chain go to one output chain, there is an important invariant
  2172. // after each step of migration, including after the initial "big step":
  2173. // For each output chain, the "zero chain" (new hash bit is zero) and the
  2174. // "one chain" (new hash bit is one) we have a "frontier" entry marking the
  2175. // boundary between what has been migrated and what has not. One of the
  2176. // frontiers is along the old chain after the other, and all entries between
  2177. // them are for the same target chain as the earlier frontier. Thus, the
  2178. // chains share linked list tails starting at the latter frontier. All
  2179. // pointers from the new head locations to the frontier entries are marked
  2180. // with the new shift amount, while all pointers after the frontiers use the
  2181. // old shift amount.
  2182. //
  2183. // And after each step there is a strengthening step to reach a stronger
  2184. // invariant: the frontier earlier in the original chain is advanced to be
  2185. // immediately before the other frontier.
  2186. //
  2187. // Consider this original input chain,
  2188. //
  2189. // OldHome -Old-> A0 -Old-> B0 -Old-> A1 -Old-> C0 -Old-> OldHome(End)
  2190. // GrowHome (empty)
  2191. //
  2192. // == BIG STEP ==
  2193. // The initial big step finds the first entry that will be on the each
  2194. // output chain (in this case A0 and A1). We use brackets ([]) to mark them
  2195. // as our prospective frontiers.
  2196. //
  2197. // OldHome -Old-> [A0] -Old-> B0 -Old-> [A1] -Old-> C0 -Old-> OldHome(End)
  2198. // GrowHome (empty)
  2199. //
  2200. // Next we speculatively update grow_home head to point to the first entry for
  2201. // the one chain. This will not be used by Lookup until the head at old_home
  2202. // uses the new shift amount.
  2203. //
  2204. // OldHome -Old-> [A0] -Old-> B0 -Old-> [A1] -Old-> C0 -Old-> OldHome(End)
  2205. // GrowHome --------------New------------/
  2206. //
  2207. // Observe that if Lookup were to use the new head at GrowHome, it would be
  2208. // able to find all relevant entries. Finishing the initial big step
  2209. // requires a CAS (compare_exchange) of the OldHome head because there
  2210. // might have been parallel insertions there, in which case we roll back
  2211. // and try again. (We might need to point GrowHome head differently.)
  2212. //
  2213. // OldHome -New-> [A0] -Old-> B0 -Old-> [A1] -Old-> C0 -Old-> OldHome(End)
  2214. // GrowHome --------------New------------/
  2215. //
  2216. // Upgrading the OldHome head pointer with the new shift amount, with a
  2217. // compare_exchange, completes the initial big step, with [A0] as zero
  2218. // chain frontier and [A1] as one chain frontier. Links before the frontiers
  2219. // use the new shift amount and links after use the old shift amount.
  2220. // == END BIG STEP==
  2221. // == STRENGTHENING ==
  2222. // Zero chain frontier is advanced to [B0] (immediately before other
  2223. // frontier) by updating pointers with new shift amounts.
  2224. //
  2225. // OldHome -New-> A0 -New-> [B0] -Old-> [A1] -Old-> C0 -Old-> OldHome(End)
  2226. // GrowHome -------------New-----------/
  2227. //
  2228. // == END STRENGTHENING ==
  2229. // == SMALL STEP #1 ==
  2230. // From the strong invariant state, we need to find the next entry for
  2231. // the new chain with the earlier frontier. In this case, we need to find
  2232. // the next entry for the zero chain that comes after [B0], which in this
  2233. // case is C0. This will be our next zero chain frontier, at least under
  2234. // the weak invariant. To get there, we simply update the link between
  2235. // the current two frontiers to skip over the entries irreleveant to the
  2236. // ealier frontier chain. In this case, the zero chain skips over A1. As a
  2237. // result, he other chain is now the "earlier."
  2238. //
  2239. // OldHome -New-> A0 -New-> B0 -New-> [C0] -Old-> OldHome(End)
  2240. // GrowHome -New-> [A1] ------Old-----/
  2241. //
  2242. // == END SMALL STEP #1 ==
  2243. //
  2244. // Repeating the cycle and end handling is not as interesting.
  2245. // Acquire rewrite lock on zero chain (if it's non-empty)
  2246. ChainRewriteLock zero_head_lock(&arr[old_home], yield_count_);
  2247. // Used for locking the one chain below
  2248. uint64_t saved_one_head;
  2249. // One head has not been written to
  2250. assert(arr[grow_home].head_next_with_shift.Load() == 0);
  2251. // old_home will also the head of the new "zero chain" -- all entries in the
  2252. // "from" chain whose next hash bit is 0. grow_home will be head of the new
  2253. // "one chain".
  2254. // For these, SIZE_MAX is like nullptr (unknown)
  2255. size_t zero_chain_frontier = SIZE_MAX;
  2256. size_t one_chain_frontier = SIZE_MAX;
  2257. size_t cur = SIZE_MAX;
  2258. // Set to 0 (zero chain frontier earlier), 1 (one chain), or -1 (unknown)
  2259. int chain_frontier_first = -1;
  2260. // Might need to retry initial update of heads
  2261. for (int i = 0;; ++i) {
  2262. CHECK_TOO_MANY_ITERATIONS(i);
  2263. assert(zero_chain_frontier == SIZE_MAX);
  2264. assert(one_chain_frontier == SIZE_MAX);
  2265. assert(cur == SIZE_MAX);
  2266. assert(chain_frontier_first == -1);
  2267. uint64_t next_with_shift = zero_head_lock.GetSavedHead();
  2268. // Find a single representative for each target chain, or scan the whole
  2269. // chain if some target chain has no representative.
  2270. for (;; ++i) {
  2271. CHECK_TOO_MANY_ITERATIONS(i);
  2272. // Loop invariants
  2273. assert((chain_frontier_first < 0) == (zero_chain_frontier == SIZE_MAX &&
  2274. one_chain_frontier == SIZE_MAX));
  2275. assert((cur == SIZE_MAX) == (zero_chain_frontier == SIZE_MAX &&
  2276. one_chain_frontier == SIZE_MAX));
  2277. assert(GetShiftFromNextWithShift(next_with_shift) == old_shift);
  2278. // Check for end of original chain
  2279. if (HandleImpl::IsEnd(next_with_shift)) {
  2280. cur = SIZE_MAX;
  2281. break;
  2282. }
  2283. // next_with_shift is not End
  2284. cur = GetNextFromNextWithShift(next_with_shift);
  2285. if (BottomNBits(arr[cur].hashed_key[1], new_shift) == old_home) {
  2286. // Entry for zero chain
  2287. if (zero_chain_frontier == SIZE_MAX) {
  2288. zero_chain_frontier = cur;
  2289. if (one_chain_frontier != SIZE_MAX) {
  2290. // Ready to update heads
  2291. break;
  2292. }
  2293. // Nothing yet for one chain
  2294. chain_frontier_first = 0;
  2295. }
  2296. } else {
  2297. assert(BottomNBits(arr[cur].hashed_key[1], new_shift) == grow_home);
  2298. // Entry for one chain
  2299. if (one_chain_frontier == SIZE_MAX) {
  2300. one_chain_frontier = cur;
  2301. if (zero_chain_frontier != SIZE_MAX) {
  2302. // Ready to update heads
  2303. break;
  2304. }
  2305. // Nothing yet for zero chain
  2306. chain_frontier_first = 1;
  2307. }
  2308. }
  2309. next_with_shift = arr[cur].chain_next_with_shift.Load();
  2310. }
  2311. // Try to update heads for initial migration info
  2312. // We only reached the end of the migrate-from chain already if one of the
  2313. // target chains will be empty.
  2314. assert((cur == SIZE_MAX) ==
  2315. (zero_chain_frontier == SIZE_MAX || one_chain_frontier == SIZE_MAX));
  2316. assert((chain_frontier_first < 0) ==
  2317. (zero_chain_frontier == SIZE_MAX && one_chain_frontier == SIZE_MAX));
  2318. // Always update one chain's head first (safe), and mark it as locked
  2319. saved_one_head = HandleImpl::kHeadLocked |
  2320. (one_chain_frontier != SIZE_MAX
  2321. ? MakeNextWithShift(one_chain_frontier, new_shift)
  2322. : MakeNextWithShiftEnd(grow_home, new_shift));
  2323. arr[grow_home].head_next_with_shift.Store(saved_one_head);
  2324. // Make sure length_info_ hasn't been updated too early, as we're about
  2325. // to make the change that makes it safe to update (e.g. in DoInsert())
  2326. assert(LengthInfoToUsedLength(length_info_.Load()) <= grow_home);
  2327. // Try to set zero's head.
  2328. if (zero_head_lock.CasUpdate(
  2329. zero_chain_frontier != SIZE_MAX
  2330. ? MakeNextWithShift(zero_chain_frontier, new_shift)
  2331. : MakeNextWithShiftEnd(old_home, new_shift),
  2332. yield_count_)) {
  2333. // Both heads successfully updated to new shift
  2334. break;
  2335. } else {
  2336. // Concurrent insertion. This should not happen too many times.
  2337. CHECK_TOO_MANY_ITERATIONS(i);
  2338. // The easiest solution is to restart.
  2339. zero_chain_frontier = SIZE_MAX;
  2340. one_chain_frontier = SIZE_MAX;
  2341. cur = SIZE_MAX;
  2342. chain_frontier_first = -1;
  2343. continue;
  2344. }
  2345. }
  2346. // Create an RAII wrapper for the one chain rewrite lock we are already
  2347. // holding (if was not end) and is now "published" after successful CAS on
  2348. // zero chain head.
  2349. ChainRewriteLock one_head_lock(&arr[grow_home], yield_count_, saved_one_head);
  2350. // Except for trivial cases, we have something like
  2351. // AHome -New-> [A0] -Old-> [B0] -Old-> [C0] \ |
  2352. // BHome --------------------New------------> [A1] -Old-> ...
  2353. // And we need to upgrade as much as we can on the "first" chain
  2354. // (the one eventually pointing to the other's frontier). This will
  2355. // also finish off any case in which one of the target chains will be empty.
  2356. if (chain_frontier_first >= 0) {
  2357. size_t& first_frontier = chain_frontier_first == 0
  2358. ? /*&*/ zero_chain_frontier
  2359. : /*&*/ one_chain_frontier;
  2360. size_t& other_frontier = chain_frontier_first != 0
  2361. ? /*&*/ zero_chain_frontier
  2362. : /*&*/ one_chain_frontier;
  2363. uint64_t stop_before_or_new_tail =
  2364. other_frontier != SIZE_MAX
  2365. ? /*stop before*/ MakeNextWithShift(other_frontier, old_shift)
  2366. : /*new tail*/ MakeNextWithShiftEnd(
  2367. chain_frontier_first == 0 ? old_home : grow_home, new_shift);
  2368. UpgradeShiftsOnRange(arr, first_frontier, stop_before_or_new_tail,
  2369. old_shift, new_shift);
  2370. }
  2371. if (zero_chain_frontier == SIZE_MAX) {
  2372. // Already finished migrating
  2373. assert(one_chain_frontier == SIZE_MAX);
  2374. assert(cur == SIZE_MAX);
  2375. } else {
  2376. // Still need to migrate between two target chains
  2377. for (int i = 0;; ++i) {
  2378. CHECK_TOO_MANY_ITERATIONS(i);
  2379. // Overall loop invariants
  2380. assert(zero_chain_frontier != SIZE_MAX);
  2381. assert(one_chain_frontier != SIZE_MAX);
  2382. assert(cur != SIZE_MAX);
  2383. assert(chain_frontier_first >= 0);
  2384. size_t& first_frontier = chain_frontier_first == 0
  2385. ? /*&*/ zero_chain_frontier
  2386. : /*&*/ one_chain_frontier;
  2387. size_t& other_frontier = chain_frontier_first != 0
  2388. ? /*&*/ zero_chain_frontier
  2389. : /*&*/ one_chain_frontier;
  2390. assert(cur != first_frontier);
  2391. assert(GetNextFromNextWithShift(
  2392. arr[first_frontier].chain_next_with_shift.Load()) ==
  2393. other_frontier);
  2394. uint64_t next_with_shift = arr[cur].chain_next_with_shift.Load();
  2395. // Check for end of original chain
  2396. if (HandleImpl::IsEnd(next_with_shift)) {
  2397. // Can set upgraded tail on first chain
  2398. uint64_t first_new_tail = MakeNextWithShiftEnd(
  2399. chain_frontier_first == 0 ? old_home : grow_home, new_shift);
  2400. arr[first_frontier].chain_next_with_shift.Store(first_new_tail);
  2401. // And upgrade remainder of other chain
  2402. uint64_t other_new_tail = MakeNextWithShiftEnd(
  2403. chain_frontier_first != 0 ? old_home : grow_home, new_shift);
  2404. UpgradeShiftsOnRange(arr, other_frontier, other_new_tail, old_shift,
  2405. new_shift);
  2406. assert(other_frontier == SIZE_MAX); // Finished
  2407. break;
  2408. }
  2409. // next_with_shift is not End
  2410. cur = GetNextFromNextWithShift(next_with_shift);
  2411. int target_chain;
  2412. if (BottomNBits(arr[cur].hashed_key[1], new_shift) == old_home) {
  2413. // Entry for zero chain
  2414. target_chain = 0;
  2415. } else {
  2416. assert(BottomNBits(arr[cur].hashed_key[1], new_shift) == grow_home);
  2417. // Entry for one chain
  2418. target_chain = 1;
  2419. }
  2420. if (target_chain == chain_frontier_first) {
  2421. // Found next entry to skip to on the first chain
  2422. uint64_t skip_to = MakeNextWithShift(cur, new_shift);
  2423. arr[first_frontier].chain_next_with_shift.Store(skip_to);
  2424. first_frontier = cur;
  2425. // Upgrade other chain up to entry before that one
  2426. UpgradeShiftsOnRange(arr, other_frontier, next_with_shift, old_shift,
  2427. new_shift);
  2428. // Swap which is marked as first
  2429. chain_frontier_first = 1 - chain_frontier_first;
  2430. } else {
  2431. // Nothing to do yet, as we need to keep old generation pointers in
  2432. // place for lookups
  2433. }
  2434. }
  2435. }
  2436. }
  2437. // Variant of PurgeImplLocked: Removes all "under (de) construction" entries
  2438. // from a chain where already holding a rewrite lock
  2439. using PurgeLockedOpData = void;
  2440. // Variant of PurgeImplLocked: Clock-updates all entries in a chain, in
  2441. // addition to functionality of PurgeLocked, where already holding a rewrite
  2442. // lock. (Caller finalizes eviction on entries added to the autovector, in part
  2443. // so that we don't hold the rewrite lock while doing potentially expensive
  2444. // callback and allocator free.)
  2445. using ClockUpdateChainLockedOpData =
  2446. autovector<AutoHyperClockTable::HandleImpl*>;
  2447. template <class OpData>
  2448. void AutoHyperClockTable::PurgeImplLocked(OpData* op_data,
  2449. ChainRewriteLock& rewrite_lock,
  2450. size_t home,
  2451. BaseClockTable::EvictionData* data) {
  2452. constexpr bool kIsPurge = std::is_same_v<OpData, PurgeLockedOpData>;
  2453. constexpr bool kIsClockUpdateChain =
  2454. std::is_same_v<OpData, ClockUpdateChainLockedOpData>;
  2455. // Exactly one op specified
  2456. static_assert(kIsPurge + kIsClockUpdateChain == 1);
  2457. HandleImpl* const arr = array_.Get();
  2458. uint64_t next_with_shift = rewrite_lock.GetSavedHead();
  2459. assert(!HandleImpl::IsEnd(next_with_shift));
  2460. int home_shift = GetShiftFromNextWithShift(next_with_shift);
  2461. (void)home;
  2462. (void)home_shift;
  2463. size_t next = GetNextFromNextWithShift(next_with_shift);
  2464. assert(next < array_.Count());
  2465. HandleImpl* h = &arr[next];
  2466. HandleImpl* prev_to_keep = nullptr;
  2467. #ifndef NDEBUG
  2468. uint64_t prev_to_keep_next_with_shift = 0;
  2469. #endif
  2470. // Whether there are entries between h and prev_to_keep that should be
  2471. // purged from the chain.
  2472. bool pending_purge = false;
  2473. // Walk the chain, and stitch together any entries that are still
  2474. // "shareable," possibly after clock update. prev_to_keep tells us where
  2475. // the last "stitch back to" location is (nullptr => head).
  2476. for (size_t i = 0;; ++i) {
  2477. CHECK_TOO_MANY_ITERATIONS(i);
  2478. bool purgeable = false;
  2479. // In last iteration, h will be nullptr, to stitch together the tail of
  2480. // the chain.
  2481. if (h) {
  2482. // NOTE: holding a rewrite lock on the chain prevents any "under
  2483. // (de)construction" entries in the chain from being marked empty, which
  2484. // allows us to access the hashed_keys without holding a read ref.
  2485. assert(home == BottomNBits(h->hashed_key[1], home_shift));
  2486. if constexpr (kIsClockUpdateChain) {
  2487. // Clock update and/or check for purgeable (under (de)construction)
  2488. if (ClockUpdate(*h, data, &purgeable)) {
  2489. // Remember for finishing eviction
  2490. op_data->push_back(h);
  2491. // Entries for eviction become purgeable
  2492. purgeable = true;
  2493. assert((h->meta.Load() >> ClockHandle::kStateShift) ==
  2494. ClockHandle::kStateConstruction);
  2495. }
  2496. } else {
  2497. (void)op_data;
  2498. (void)data;
  2499. purgeable = ((h->meta.Load() >> ClockHandle::kStateShift) &
  2500. ClockHandle::kStateShareableBit) == 0;
  2501. }
  2502. }
  2503. if (purgeable) {
  2504. assert((h->meta.Load() >> ClockHandle::kStateShift) ==
  2505. ClockHandle::kStateConstruction);
  2506. pending_purge = true;
  2507. } else if (pending_purge) {
  2508. if (prev_to_keep) {
  2509. // Update chain next to skip purgeable entries
  2510. assert(prev_to_keep->chain_next_with_shift.Load() ==
  2511. prev_to_keep_next_with_shift);
  2512. prev_to_keep->chain_next_with_shift.Store(next_with_shift);
  2513. } else if (rewrite_lock.CasUpdate(next_with_shift, yield_count_)) {
  2514. // Managed to update head without any parallel insertions
  2515. } else {
  2516. // Parallel insertion must have interfered. Need to do a purge
  2517. // from updated head to here. Since we have no prev_to_keep, there's
  2518. // no risk of duplicate clock updates to entries. Any entries already
  2519. // updated must have been evicted (purgeable) and it's OK to clock
  2520. // update any new entries just inserted in parallel.
  2521. // Can simply restart (GetSavedHead() already updated from CAS failure).
  2522. next_with_shift = rewrite_lock.GetSavedHead();
  2523. assert(!HandleImpl::IsEnd(next_with_shift));
  2524. next = GetNextFromNextWithShift(next_with_shift);
  2525. assert(next < array_.Count());
  2526. h = &arr[next];
  2527. pending_purge = false;
  2528. assert(prev_to_keep == nullptr);
  2529. assert(GetShiftFromNextWithShift(next_with_shift) == home_shift);
  2530. continue;
  2531. }
  2532. pending_purge = false;
  2533. prev_to_keep = h;
  2534. } else {
  2535. prev_to_keep = h;
  2536. }
  2537. if (h == nullptr) {
  2538. // Reached end of the chain
  2539. return;
  2540. }
  2541. // Read chain pointer
  2542. next_with_shift = h->chain_next_with_shift.Load();
  2543. #ifndef NDEBUG
  2544. if (prev_to_keep == h) {
  2545. prev_to_keep_next_with_shift = next_with_shift;
  2546. }
  2547. #endif
  2548. assert(GetShiftFromNextWithShift(next_with_shift) == home_shift);
  2549. // Check for end marker
  2550. if (HandleImpl::IsEnd(next_with_shift)) {
  2551. h = nullptr;
  2552. } else {
  2553. next = GetNextFromNextWithShift(next_with_shift);
  2554. assert(next < array_.Count());
  2555. h = &arr[next];
  2556. assert(h != prev_to_keep);
  2557. }
  2558. }
  2559. }
  2560. // Variant of PurgeImpl: Removes all "under (de) construction" entries in a
  2561. // chain, such that any entry with the given key must have been purged.
  2562. using PurgeOpData = const UniqueId64x2;
  2563. // Variant of PurgeImpl: Clock-updates all entries in a chain, in addition to
  2564. // purging as appropriate. (Caller finalizes eviction on entries added to the
  2565. // autovector, in part so that we don't hold the rewrite lock while doing
  2566. // potentially expensive callback and allocator free.)
  2567. using ClockUpdateChainOpData = ClockUpdateChainLockedOpData;
  2568. template <class OpData>
  2569. void AutoHyperClockTable::PurgeImpl(OpData* op_data, size_t home,
  2570. BaseClockTable::EvictionData* data) {
  2571. // Early efforts to make AutoHCC fully wait-free ran into too many problems
  2572. // that needed obscure and potentially inefficient work-arounds to have a
  2573. // chance at working.
  2574. //
  2575. // The implementation settled on "essentially wait-free" which can be
  2576. // achieved by locking at the level of each probing chain and only for
  2577. // operations that might remove entries from the chain. Because parallel
  2578. // clock updates and Grow operations are ordered, contention is very rare.
  2579. // However, parallel insertions at any chain head have to be accommodated
  2580. // to keep them wait-free.
  2581. //
  2582. // This function implements Purge and ClockUpdateChain functions (see above
  2583. // OpData type definitions) as part of higher-level operations. This function
  2584. // ensures the correct chain is (eventually) covered and handles rewrite
  2585. // locking the chain. PurgeImplLocked has lower level details.
  2586. //
  2587. // In general, these operations and Grow are kept simpler by allowing eager
  2588. // purging of under (de-)construction entries. For example, an Erase
  2589. // operation might find that another thread has purged the entry from the
  2590. // chain by the time its own purge operation acquires the rewrite lock and
  2591. // proceeds. This is OK, and potentially reduces the number of lock/unlock
  2592. // cycles because empty chains are not rewrite-lockable.
  2593. constexpr bool kIsPurge = std::is_same_v<OpData, PurgeOpData>;
  2594. constexpr bool kIsClockUpdateChain =
  2595. std::is_same_v<OpData, ClockUpdateChainOpData>;
  2596. // Exactly one op specified
  2597. static_assert(kIsPurge + kIsClockUpdateChain == 1);
  2598. int home_shift = 0;
  2599. if constexpr (kIsPurge) {
  2600. // Purge callers leave home unspecified, to be determined from key
  2601. assert(home == SIZE_MAX);
  2602. GetHomeIndexAndShift(length_info_.Load(), (*op_data)[1], &home,
  2603. &home_shift);
  2604. assert(home_shift > 0);
  2605. } else {
  2606. assert(kIsClockUpdateChain);
  2607. // Evict callers must specify home
  2608. assert(home < SIZE_MAX);
  2609. }
  2610. HandleImpl* const arr = array_.Get();
  2611. // Acquire the RAII rewrite lock (if not an empty chain)
  2612. ChainRewriteLock rewrite_lock(&arr[home], yield_count_);
  2613. if constexpr (kIsPurge) {
  2614. // Ensure we are at the correct home for the shift in effect for the
  2615. // chain head.
  2616. for (;;) {
  2617. int shift = GetShiftFromNextWithShift(rewrite_lock.GetSavedHead());
  2618. if (shift > home_shift) {
  2619. // Found a newer shift at candidate head, which must apply to us.
  2620. // Newer shift might not yet be reflected in length_info_ (an atomicity
  2621. // gap in Grow), so operate as if it is. Note that other insertions
  2622. // could happen using this shift before length_info_ is updated, and
  2623. // it's possible (though unlikely) that multiple generations of Grow
  2624. // have occurred. If shift is more than one generation ahead of
  2625. // home_shift, it's possible that not all descendent homes have
  2626. // reached the `shift` generation. Thus, we need to advance only one
  2627. // shift at a time looking for a home+head with a matching shift
  2628. // amount.
  2629. home_shift++;
  2630. home = GetHomeIndex((*op_data)[1], home_shift);
  2631. rewrite_lock.Reset(&arr[home], yield_count_);
  2632. continue;
  2633. } else {
  2634. assert(shift == home_shift);
  2635. }
  2636. break;
  2637. }
  2638. }
  2639. // If the chain is empty, nothing to do
  2640. if (!rewrite_lock.IsEnd()) {
  2641. if constexpr (kIsPurge) {
  2642. PurgeLockedOpData* locked_op_data{};
  2643. PurgeImplLocked(locked_op_data, rewrite_lock, home, data);
  2644. } else {
  2645. PurgeImplLocked(op_data, rewrite_lock, home, data);
  2646. }
  2647. }
  2648. }
  2649. AutoHyperClockTable::HandleImpl* AutoHyperClockTable::DoInsert(
  2650. const ClockHandleBasicData& proto, uint64_t initial_countdown,
  2651. bool take_ref, InsertState& state) {
  2652. size_t home;
  2653. int orig_home_shift;
  2654. GetHomeIndexAndShift(state.saved_length_info, proto.hashed_key[1], &home,
  2655. &orig_home_shift);
  2656. HandleImpl* const arr = array_.Get();
  2657. // We could go searching through the chain for any duplicate, but that's
  2658. // not typically helpful, except for the REDUNDANT block cache stats.
  2659. // (Inferior duplicates will age out with eviction.) However, we do skip
  2660. // insertion if the home slot (or some other we happen to probe) already
  2661. // has a match (already_matches below). This helps to keep better locality
  2662. // when we can.
  2663. //
  2664. // And we can do that as part of searching for an available slot to
  2665. // insert the new entry, because our preferred location and first slot
  2666. // checked will be the home slot.
  2667. //
  2668. // As the table initially grows to size, few entries will be in the same
  2669. // cache line as the chain head. However, churn in the cache relatively
  2670. // quickly improves the proportion of entries sharing that cache line with
  2671. // the chain head. Data:
  2672. //
  2673. // Initial population only: (cache_bench with -ops_per_thread=1)
  2674. // Entries at home count: 29,202 (out of 129,170 entries in 94,411 chains)
  2675. // Approximate average cache lines read to find an existing entry:
  2676. // 129.2 / 94.4 [without the heads]
  2677. // + (94.4 - 29.2) / 94.4 [the heads not included with entries]
  2678. // = 2.06 cache lines
  2679. //
  2680. // After 10 million ops: (-threads=10 -ops_per_thread=100000)
  2681. // Entries at home count: 67,556 (out of 129,359 entries in 94,756 chains)
  2682. // That's a majority of entries and more than 2/3rds of chains.
  2683. // Approximate average cache lines read to find an existing entry:
  2684. // = 1.65 cache lines
  2685. // Even if we aren't saving a ref to this entry (take_ref == false), we need
  2686. // to keep a reference while we are inserting the entry into a chain, so that
  2687. // it is not erased by another thread while trying to insert it on the chain.
  2688. constexpr bool initial_take_ref = true;
  2689. size_t used_length = LengthInfoToUsedLength(state.saved_length_info);
  2690. assert(home < used_length);
  2691. size_t idx = home;
  2692. bool already_matches = false;
  2693. bool already_matches_ignore = false;
  2694. if (TryInsert(proto, arr[idx], initial_countdown, initial_take_ref,
  2695. &already_matches)) {
  2696. assert(idx == home);
  2697. } else if (already_matches) {
  2698. return nullptr;
  2699. // Here we try to populate newly-opened slots in the table, but not
  2700. // when we can add something to its home slot. This makes the structure
  2701. // more performant more quickly on (initial) growth. We ignore "already
  2702. // matches" in this case because it is unlikely and difficult to
  2703. // incorporate logic for here cleanly and efficiently.
  2704. } else if (UNLIKELY(state.likely_empty_slot > 0) &&
  2705. TryInsert(proto, arr[state.likely_empty_slot], initial_countdown,
  2706. initial_take_ref, &already_matches_ignore)) {
  2707. idx = state.likely_empty_slot;
  2708. } else {
  2709. // We need to search for an available slot outside of the home.
  2710. // Linear hashing provides nice resizing but does typically mean
  2711. // that some heads (home locations) have (in expectation) twice as
  2712. // many entries mapped to them as other heads. For example if the
  2713. // usable length is 80, then heads 16-63 are (in expectation) twice
  2714. // as loaded as heads 0-15 and 64-79, which are using another hash bit.
  2715. //
  2716. // This means that if we just use linear probing (by a small constant)
  2717. // to find an available slot, part of the structure could easily fill up
  2718. // and resort to linear time operations even when the overall load factor
  2719. // is only modestly high, like 70%. Even though each slot has its own CPU
  2720. // cache line, there appears to be a small locality benefit (e.g. TLB and
  2721. // paging) to iterating one by one, as long as we don't afoul of the
  2722. // linear hashing imbalance.
  2723. //
  2724. // In a traditional non-concurrent structure, we could keep a "free list"
  2725. // to ensure immediate access to an available slot, but maintaining such
  2726. // a structure could require more cross-thread coordination to ensure
  2727. // all entries are eventually available to all threads.
  2728. //
  2729. // The way we solve this problem is to use unit-increment linear probing
  2730. // with a small bound, and then fall back on big jumps to have a good
  2731. // chance of finding a slot in an under-populated region quickly if that
  2732. // doesn't work.
  2733. size_t i = 0;
  2734. constexpr size_t kMaxLinearProbe = 4;
  2735. for (; i < kMaxLinearProbe; i++) {
  2736. idx++;
  2737. if (idx >= used_length) {
  2738. idx -= used_length;
  2739. }
  2740. if (TryInsert(proto, arr[idx], initial_countdown, initial_take_ref,
  2741. &already_matches)) {
  2742. break;
  2743. }
  2744. if (already_matches) {
  2745. return nullptr;
  2746. }
  2747. }
  2748. if (i == kMaxLinearProbe) {
  2749. // Keep searching, but change to a search method that should quickly
  2750. // find any under-populated region. Switching to an increment based
  2751. // on the golden ratio helps with that, but we also inject some minor
  2752. // variation (less than 2%, 1 in 2^6) to avoid clustering effects on
  2753. // this larger increment (if it were a fixed value in steady state
  2754. // operation). Here we are primarily using upper bits of hashed_key[1]
  2755. // while home is based on lowest bits.
  2756. uint64_t incr_ratio = 0x9E3779B185EBCA87U + (proto.hashed_key[1] >> 6);
  2757. size_t incr = FastRange64(incr_ratio, used_length);
  2758. assert(incr > 0);
  2759. size_t start = idx;
  2760. for (;; i++) {
  2761. idx += incr;
  2762. if (idx >= used_length) {
  2763. // Wrap around (faster than %)
  2764. idx -= used_length;
  2765. }
  2766. if (idx == start) {
  2767. // We have just completed a cycle that might not have covered all
  2768. // slots. (incr and used_length could have common factors.)
  2769. // Increment for the next cycle, which eventually ensures complete
  2770. // iteration over the set of slots before repeating.
  2771. idx++;
  2772. if (idx >= used_length) {
  2773. idx -= used_length;
  2774. }
  2775. start++;
  2776. if (start >= used_length) {
  2777. start -= used_length;
  2778. }
  2779. if (i >= used_length) {
  2780. used_length = LengthInfoToUsedLength(length_info_.Load());
  2781. if (i >= used_length * 2) {
  2782. // Cycling back should not happen unless there is enough random
  2783. // churn in parallel that we happen to hit each slot at a time
  2784. // that it's occupied, which is really only feasible for small
  2785. // structures, though with linear probing to find empty slots,
  2786. // "small" here might be larger than for double hashing.
  2787. assert(used_length <= 256);
  2788. // Fall back on standalone insert in case something goes awry to
  2789. // cause this
  2790. return nullptr;
  2791. }
  2792. }
  2793. }
  2794. if (TryInsert(proto, arr[idx], initial_countdown, initial_take_ref,
  2795. &already_matches)) {
  2796. break;
  2797. }
  2798. if (already_matches) {
  2799. return nullptr;
  2800. }
  2801. }
  2802. }
  2803. }
  2804. // Now insert into chain using head pointer
  2805. uint64_t next_with_shift;
  2806. int home_shift = orig_home_shift;
  2807. // Might need to retry
  2808. for (int i = 0;; ++i) {
  2809. CHECK_TOO_MANY_ITERATIONS(i);
  2810. next_with_shift = arr[home].head_next_with_shift.Load();
  2811. int shift = GetShiftFromNextWithShift(next_with_shift);
  2812. if (UNLIKELY(shift != home_shift)) {
  2813. // NOTE: shift increases with table growth
  2814. if (shift > home_shift) {
  2815. // Must be grow in progress or completed since reading length_info.
  2816. // Pull out one more hash bit. (See Lookup() for why we can't
  2817. // safely jump to the shift that was read.)
  2818. home_shift++;
  2819. uint64_t hash_bit_mask = uint64_t{1} << (home_shift - 1);
  2820. assert((home & hash_bit_mask) == 0);
  2821. // BEGIN leftover updates to length_info_ for Grow()
  2822. size_t grow_home = home + hash_bit_mask;
  2823. assert(arr[grow_home].head_next_with_shift.Load() !=
  2824. HandleImpl::kUnusedMarker);
  2825. CatchUpLengthInfoNoWait(grow_home);
  2826. // END leftover updates to length_info_ for Grow()
  2827. home += proto.hashed_key[1] & hash_bit_mask;
  2828. continue;
  2829. } else {
  2830. // Should not happen because length_info_ is only updated after both
  2831. // old and new home heads are marked with new shift
  2832. assert(false);
  2833. }
  2834. }
  2835. // Values to update to
  2836. uint64_t head_next_with_shift = MakeNextWithShift(idx, home_shift);
  2837. uint64_t chain_next_with_shift = next_with_shift;
  2838. // Preserve the locked state in head, without propagating to chain next
  2839. // where it is meaningless (and not allowed)
  2840. if (UNLIKELY((next_with_shift & HandleImpl::kNextEndFlags) ==
  2841. HandleImpl::kHeadLocked)) {
  2842. head_next_with_shift |= HandleImpl::kHeadLocked;
  2843. chain_next_with_shift &= ~HandleImpl::kHeadLocked;
  2844. }
  2845. arr[idx].chain_next_with_shift.Store(chain_next_with_shift);
  2846. if (arr[home].head_next_with_shift.CasWeak(next_with_shift,
  2847. head_next_with_shift)) {
  2848. // Success
  2849. if (!take_ref) {
  2850. Unref(arr[idx]);
  2851. }
  2852. return arr + idx;
  2853. }
  2854. }
  2855. }
  2856. AutoHyperClockTable::HandleImpl* AutoHyperClockTable::Lookup(
  2857. const UniqueId64x2& hashed_key) {
  2858. // Lookups are wait-free with low occurrence of retries, back-tracking,
  2859. // and fallback. We do not have the benefit of holding a rewrite lock on
  2860. // the chain so must be prepared for many kinds of mayhem, most notably
  2861. // "falling off our chain" where a slot that Lookup has identified but
  2862. // has not read-referenced is removed from one chain and inserted into
  2863. // another. The full algorithm uses the following mitigation strategies to
  2864. // ensure every relevant entry inserted before this Lookup, and not yet
  2865. // evicted, is seen by Lookup, without excessive backtracking etc.:
  2866. // * Keep a known good read ref in the chain for "island hopping." When
  2867. // we observe that a concurrent write takes us off to another chain, we
  2868. // only need to fall back to our last known good read ref (most recent
  2869. // entry on the chain that is not "under construction," which is a transient
  2870. // state). We don't want to compound the CPU toil of a long chain with
  2871. // operations that might need to retry from scratch, with probability
  2872. // in proportion to chain length.
  2873. // * Only detect a chain is potentially incomplete because of a Grow in
  2874. // progress by looking at shift in the next pointer tags (rather than
  2875. // re-checking length_info_).
  2876. // * SplitForGrow, Insert, and PurgeImplLocked ensure that there are no
  2877. // transient states that might cause this full Lookup algorithm to skip over
  2878. // live entries.
  2879. // Reading length_info_ is not strictly required for Lookup, if we were
  2880. // to increment shift sizes until we see a shift size match on the
  2881. // relevant head pointer. Thus, reading with relaxed memory order gives
  2882. // us a safe and almost always up-to-date jump into finding the correct
  2883. // home and head.
  2884. size_t home;
  2885. int home_shift;
  2886. GetHomeIndexAndShift(length_info_.LoadRelaxed(), hashed_key[1], &home,
  2887. &home_shift);
  2888. assert(home_shift > 0);
  2889. // The full Lookup algorithm however is not great for hot path efficiency,
  2890. // because of the extra careful tracking described above. Overwhelmingly,
  2891. // we can find what we're looking for with a naive linked list traversal
  2892. // of the chain. Even if we "fall off our chain" to another, we don't
  2893. // violate memory safety. We just won't match the key we're looking for.
  2894. // And we would eventually reach an end state, possibly even experiencing a
  2895. // cycle as an entry is freed and reused during our traversal (though at
  2896. // any point in time the structure doesn't have cycles).
  2897. //
  2898. // So for hot path efficiency, we start with a naive Lookup attempt, and
  2899. // then fall back on full Lookup if we don't find the correct entry. To
  2900. // cap how much we invest into the naive Lookup, we simply cap the traversal
  2901. // length before falling back. Also, when we do fall back on full Lookup,
  2902. // we aren't paying much penalty by starting over. Much or most of the cost
  2903. // of Lookup is memory latency in following the chain pointers, and the
  2904. // naive Lookup has warmed the CPU cache for these entries, using as tight
  2905. // of a loop as possible.
  2906. HandleImpl* const arr = array_.Get();
  2907. uint64_t next_with_shift = arr[home].head_next_with_shift.LoadRelaxed();
  2908. for (size_t i = 0; !HandleImpl::IsEnd(next_with_shift) && i < 10; ++i) {
  2909. HandleImpl* h = &arr[GetNextFromNextWithShift(next_with_shift)];
  2910. // Attempt cheap key match without acquiring a read ref. This could give a
  2911. // false positive, which is re-checked after acquiring read ref, or false
  2912. // negative, which is re-checked in the full Lookup. Also, this is a
  2913. // technical UB data race according to TSAN, but we don't need to read
  2914. // a "correct" value here for correct overall behavior.
  2915. #ifdef __SANITIZE_THREAD__
  2916. bool probably_equal = Random::GetTLSInstance()->OneIn(2);
  2917. #else
  2918. bool probably_equal = h->hashed_key == hashed_key;
  2919. #endif
  2920. if (probably_equal) {
  2921. // Increment acquire counter for definitive check
  2922. uint64_t old_meta = h->meta.FetchAdd(ClockHandle::kAcquireIncrement);
  2923. // Check if it's a referencable (sharable) entry
  2924. if (LIKELY(old_meta & (uint64_t{ClockHandle::kStateShareableBit}
  2925. << ClockHandle::kStateShift))) {
  2926. assert(GetRefcount(old_meta + ClockHandle::kAcquireIncrement) > 0);
  2927. if (LIKELY(h->hashed_key == hashed_key) &&
  2928. LIKELY(old_meta & (uint64_t{ClockHandle::kStateVisibleBit}
  2929. << ClockHandle::kStateShift))) {
  2930. return h;
  2931. } else {
  2932. Unref(*h);
  2933. }
  2934. } else {
  2935. // For non-sharable states, incrementing the acquire counter has no
  2936. // effect so we don't need to undo it. Furthermore, we cannot safely
  2937. // undo it because we did not acquire a read reference to lock the entry
  2938. // in a Shareable state.
  2939. }
  2940. }
  2941. next_with_shift = h->chain_next_with_shift.LoadRelaxed();
  2942. }
  2943. // If we get here, falling back on full Lookup algorithm.
  2944. HandleImpl* h = nullptr;
  2945. HandleImpl* read_ref_on_chain = nullptr;
  2946. for (size_t i = 0;; ++i) {
  2947. CHECK_TOO_MANY_ITERATIONS(i);
  2948. // Read head or chain pointer
  2949. next_with_shift = h ? h->chain_next_with_shift.Load()
  2950. : arr[home].head_next_with_shift.Load();
  2951. int shift = GetShiftFromNextWithShift(next_with_shift);
  2952. // Make sure it's usable
  2953. size_t effective_home = home;
  2954. if (UNLIKELY(shift != home_shift)) {
  2955. // We have potentially gone awry somehow, but it's possible we're just
  2956. // hitting old data that is not yet completed Grow.
  2957. // NOTE: shift bits goes up with table growth.
  2958. if (shift < home_shift) {
  2959. // To avoid waiting on Grow in progress, an old shift amount needs
  2960. // to be processed as if we were still using it and (potentially
  2961. // different or the same) the old home.
  2962. // We can assert it's not too old, because each generation of Grow
  2963. // waits on its ancestor in the previous generation.
  2964. assert(shift + 1 == home_shift);
  2965. effective_home = GetHomeIndex(home, shift);
  2966. } else if (h == read_ref_on_chain) {
  2967. assert(shift > home_shift);
  2968. // At head or coming from an entry on our chain where we're holding
  2969. // a read reference. Thus, we know the newer shift applies to us.
  2970. // Newer shift might not yet be reflected in length_info_ (an atomicity
  2971. // gap in Grow), so operate as if it is. Note that other insertions
  2972. // could happen using this shift before length_info_ is updated, and
  2973. // it's possible (though unlikely) that multiple generations of Grow
  2974. // have occurred. If shift is more than one generation ahead of
  2975. // home_shift, it's possible that not all descendent homes have
  2976. // reached the `shift` generation. Thus, we need to advance only one
  2977. // shift at a time looking for a home+head with a matching shift
  2978. // amount.
  2979. home_shift++;
  2980. // Update home in case it has changed
  2981. home = GetHomeIndex(hashed_key[1], home_shift);
  2982. // This should be rare enough occurrence that it's simplest just
  2983. // to restart (TODO: improve in some cases?)
  2984. h = nullptr;
  2985. if (read_ref_on_chain) {
  2986. Unref(*read_ref_on_chain);
  2987. read_ref_on_chain = nullptr;
  2988. }
  2989. // Didn't make progress & retry
  2990. continue;
  2991. } else {
  2992. assert(shift > home_shift);
  2993. assert(h != nullptr);
  2994. // An "under (de)construction" entry has a new shift amount, which
  2995. // means we have either gotten off our chain or our home shift is out
  2996. // of date. If we revert back to saved ref, we will get updated info.
  2997. h = read_ref_on_chain;
  2998. // Didn't make progress & retry
  2999. continue;
  3000. }
  3001. }
  3002. // Check for end marker
  3003. if (HandleImpl::IsEnd(next_with_shift)) {
  3004. // To ensure we didn't miss anything in the chain, the end marker must
  3005. // point back to the correct home.
  3006. if (LIKELY(GetNextFromNextWithShift(next_with_shift) == effective_home)) {
  3007. // Complete, clean iteration of the chain, not found.
  3008. // Clean up.
  3009. if (read_ref_on_chain) {
  3010. Unref(*read_ref_on_chain);
  3011. }
  3012. return nullptr;
  3013. } else {
  3014. // Something went awry. Revert back to a safe point (if we have it)
  3015. h = read_ref_on_chain;
  3016. // Didn't make progress & retry
  3017. continue;
  3018. }
  3019. }
  3020. // Follow the next and check for full key match, home match, or neither
  3021. h = &arr[GetNextFromNextWithShift(next_with_shift)];
  3022. bool full_match_or_unknown = false;
  3023. if (MatchAndRef(&hashed_key, *h, shift, effective_home,
  3024. &full_match_or_unknown)) {
  3025. // Got a read ref on next (h).
  3026. //
  3027. // There is a very small chance that between getting the next pointer
  3028. // (now h) and doing MatchAndRef on it, another thread erased/evicted it
  3029. // reinserted it into the same chain, causing us to cycle back in the
  3030. // same chain and potentially see some entries again if we keep walking.
  3031. // Newly-inserted entries are inserted before older ones, so we are at
  3032. // least guaranteed not to miss anything. Here in Lookup, it's just a
  3033. // transient, slight hiccup in performance.
  3034. if (full_match_or_unknown) {
  3035. // Full match.
  3036. // Release old read ref on chain if applicable
  3037. if (read_ref_on_chain) {
  3038. // Pretend we never took the reference.
  3039. Unref(*read_ref_on_chain);
  3040. }
  3041. // Update the hit bit
  3042. if (eviction_callback_) {
  3043. h->meta.FetchOrRelaxed(uint64_t{1} << ClockHandle::kHitBitShift);
  3044. }
  3045. // All done.
  3046. return h;
  3047. } else if (UNLIKELY(shift != home_shift) &&
  3048. home != BottomNBits(h->hashed_key[1], home_shift)) {
  3049. // This chain is in a Grow operation and we've landed on an entry
  3050. // that belongs to the wrong destination chain. We can keep going, but
  3051. // there's a chance we'll need to backtrack back *before* this entry,
  3052. // if the Grow finishes before this Lookup. We cannot save this entry
  3053. // for backtracking because it might soon or already be on the wrong
  3054. // chain.
  3055. // NOTE: if we simply backtrack rather than continuing, we would
  3056. // be in a wait loop (not allowed in Lookup!) until the other thread
  3057. // finishes its Grow.
  3058. Unref(*h);
  3059. } else {
  3060. // Correct home location, so we are on the right chain.
  3061. // With new usable read ref, can release old one (if applicable).
  3062. if (read_ref_on_chain) {
  3063. // Pretend we never took the reference.
  3064. Unref(*read_ref_on_chain);
  3065. }
  3066. // And keep the new one.
  3067. read_ref_on_chain = h;
  3068. }
  3069. } else {
  3070. if (full_match_or_unknown) {
  3071. // Must have been an "under construction" entry. Can safely skip it,
  3072. // but there's a chance we'll have to backtrack later
  3073. } else {
  3074. // Home mismatch! Revert back to a safe point (if we have it)
  3075. h = read_ref_on_chain;
  3076. // Didn't make progress & retry
  3077. }
  3078. }
  3079. }
  3080. }
  3081. void AutoHyperClockTable::Remove(HandleImpl* h) {
  3082. assert((h->meta.Load() >> ClockHandle::kStateShift) ==
  3083. ClockHandle::kStateConstruction);
  3084. const HandleImpl& c_h = *h;
  3085. PurgeImpl(&c_h.hashed_key);
  3086. }
  3087. bool AutoHyperClockTable::TryEraseHandle(HandleImpl* h, bool holding_ref,
  3088. bool mark_invisible) {
  3089. uint64_t meta;
  3090. if (mark_invisible) {
  3091. // Set invisible
  3092. meta = h->meta.FetchAnd(
  3093. ~(uint64_t{ClockHandle::kStateVisibleBit} << ClockHandle::kStateShift));
  3094. // To local variable also
  3095. meta &=
  3096. ~(uint64_t{ClockHandle::kStateVisibleBit} << ClockHandle::kStateShift);
  3097. } else {
  3098. meta = h->meta.Load();
  3099. }
  3100. // Take ownership if no other refs
  3101. do {
  3102. if (GetRefcount(meta) != uint64_t{holding_ref}) {
  3103. // Not last ref at some point in time during this call
  3104. return false;
  3105. }
  3106. if ((meta & (uint64_t{ClockHandle::kStateShareableBit}
  3107. << ClockHandle::kStateShift)) == 0) {
  3108. // Someone else took ownership
  3109. return false;
  3110. }
  3111. // Note that if !holding_ref, there's a small chance that we release,
  3112. // another thread replaces this entry with another, reaches zero refs, and
  3113. // then we end up erasing that other entry. That's an acceptable risk /
  3114. // imprecision.
  3115. } while (!h->meta.CasWeak(meta, uint64_t{ClockHandle::kStateConstruction}
  3116. << ClockHandle::kStateShift));
  3117. // Took ownership
  3118. // TODO? Delay freeing?
  3119. h->FreeData(allocator_);
  3120. size_t total_charge = h->total_charge;
  3121. if (UNLIKELY(h->IsStandalone())) {
  3122. // Delete detached handle
  3123. delete h;
  3124. standalone_usage_.FetchSubRelaxed(total_charge);
  3125. } else {
  3126. Remove(h);
  3127. MarkEmpty(*h);
  3128. occupancy_.FetchSub(1U);
  3129. }
  3130. usage_.FetchSubRelaxed(total_charge);
  3131. assert(usage_.LoadRelaxed() < SIZE_MAX / 2);
  3132. return true;
  3133. }
  3134. bool AutoHyperClockTable::Release(HandleImpl* h, bool useful,
  3135. bool erase_if_last_ref) {
  3136. // In contrast with LRUCache's Release, this function won't delete the handle
  3137. // when the cache is above capacity and the reference is the last one. Space
  3138. // is only freed up by Evict/PurgeImpl (called by Insert when space
  3139. // is needed) and Erase. We do this to avoid an extra atomic read of the
  3140. // variable usage_.
  3141. uint64_t old_meta;
  3142. if (useful) {
  3143. // Increment release counter to indicate was used
  3144. old_meta = h->meta.FetchAdd(ClockHandle::kReleaseIncrement);
  3145. // Correct for possible (but rare) overflow
  3146. CorrectNearOverflow(old_meta, h->meta);
  3147. } else {
  3148. // Decrement acquire counter to pretend it never happened
  3149. old_meta = h->meta.FetchSub(ClockHandle::kAcquireIncrement);
  3150. }
  3151. assert((old_meta >> ClockHandle::kStateShift) &
  3152. ClockHandle::kStateShareableBit);
  3153. // No underflow
  3154. assert(((old_meta >> ClockHandle::kAcquireCounterShift) &
  3155. ClockHandle::kCounterMask) !=
  3156. ((old_meta >> ClockHandle::kReleaseCounterShift) &
  3157. ClockHandle::kCounterMask));
  3158. if ((erase_if_last_ref || UNLIKELY(old_meta >> ClockHandle::kStateShift ==
  3159. ClockHandle::kStateInvisible))) {
  3160. // FIXME: There's a chance here that another thread could replace this
  3161. // entry and we end up erasing the wrong one.
  3162. return TryEraseHandle(h, /*holding_ref=*/false, /*mark_invisible=*/false);
  3163. } else {
  3164. return false;
  3165. }
  3166. }
  3167. #ifndef NDEBUG
  3168. void AutoHyperClockTable::TEST_ReleaseN(HandleImpl* h, size_t n) {
  3169. if (n > 0) {
  3170. // Do n-1 simple releases first
  3171. TEST_ReleaseNMinus1(h, n);
  3172. // Then the last release might be more involved
  3173. Release(h, /*useful*/ true, /*erase_if_last_ref*/ false);
  3174. }
  3175. }
  3176. #endif
  3177. void AutoHyperClockTable::Erase(const UniqueId64x2& hashed_key) {
  3178. // Don't need to be efficient.
  3179. // Might be one match masking another, so loop.
  3180. while (HandleImpl* h = Lookup(hashed_key)) {
  3181. bool gone =
  3182. TryEraseHandle(h, /*holding_ref=*/true, /*mark_invisible=*/true);
  3183. if (!gone) {
  3184. // Only marked invisible, which is ok.
  3185. // Pretend we never took the reference from Lookup.
  3186. Unref(*h);
  3187. }
  3188. }
  3189. }
  3190. void AutoHyperClockTable::EraseUnRefEntries() {
  3191. size_t usable_size = GetTableSize();
  3192. for (size_t i = 0; i < usable_size; i++) {
  3193. HandleImpl& h = array_[i];
  3194. uint64_t old_meta = h.meta.LoadRelaxed();
  3195. if (old_meta & (uint64_t{ClockHandle::kStateShareableBit}
  3196. << ClockHandle::kStateShift) &&
  3197. GetRefcount(old_meta) == 0 &&
  3198. h.meta.CasStrong(old_meta, uint64_t{ClockHandle::kStateConstruction}
  3199. << ClockHandle::kStateShift)) {
  3200. // Took ownership
  3201. h.FreeData(allocator_);
  3202. usage_.FetchSubRelaxed(h.total_charge);
  3203. // NOTE: could be more efficient with a dedicated variant of
  3204. // PurgeImpl, but this is not a common operation
  3205. Remove(&h);
  3206. MarkEmpty(h);
  3207. occupancy_.FetchSub(1U);
  3208. }
  3209. }
  3210. }
  3211. void AutoHyperClockTable::Evict(size_t requested_charge, InsertState& state,
  3212. EvictionData* data) {
  3213. // precondition
  3214. assert(requested_charge > 0);
  3215. // We need the clock pointer to seemlessly "wrap around" at the end of the
  3216. // table, and to be reasonably stable under Grow operations. This is
  3217. // challenging when the linear hashing progressively opens additional
  3218. // most-significant-hash-bits in determining home locations.
  3219. // TODO: make a tuning parameter?
  3220. // Up to 2x this number of homes will be evicted per step. In very rare
  3221. // cases, possibly more, as homes of an out-of-date generation will be
  3222. // resolved to multiple in a newer generation.
  3223. constexpr size_t step_size = 4;
  3224. // A clock_pointer_mask_ field separate from length_info_ enables us to use
  3225. // the same mask (way of dividing up the space among evicting threads) for
  3226. // iterating over the whole structure before considering changing the mask
  3227. // at the beginning of each pass. This ensures we do not have a large portion
  3228. // of the space that receives redundant or missed clock updates. However,
  3229. // with two variables, for each update to clock_pointer_mask (< 64 ever in
  3230. // the life of the cache), there will be a brief period where concurrent
  3231. // eviction threads could use the old mask value, possibly causing redundant
  3232. // or missed clock updates for a *small* portion of the table.
  3233. size_t clock_pointer_mask = clock_pointer_mask_.LoadRelaxed();
  3234. uint64_t max_clock_pointer = 0; // unset
  3235. // TODO: consider updating during a long eviction
  3236. size_t used_length = LengthInfoToUsedLength(state.saved_length_info);
  3237. autovector<HandleImpl*> to_finish_eviction;
  3238. // Loop until enough freed, or limit reached (see bottom of loop)
  3239. for (;;) {
  3240. // First (concurrent) increment clock pointer
  3241. uint64_t old_clock_pointer = clock_pointer_.FetchAddRelaxed(step_size);
  3242. if (UNLIKELY((old_clock_pointer & clock_pointer_mask) == 0)) {
  3243. // Back at the beginning. See if clock_pointer_mask should be updated.
  3244. uint64_t mask = BottomNBits(
  3245. UINT64_MAX, LengthInfoToMinShift(state.saved_length_info));
  3246. if (clock_pointer_mask != mask) {
  3247. clock_pointer_mask = static_cast<size_t>(mask);
  3248. clock_pointer_mask_.StoreRelaxed(clock_pointer_mask);
  3249. }
  3250. }
  3251. size_t major_step = clock_pointer_mask + 1;
  3252. assert((major_step & clock_pointer_mask) == 0);
  3253. for (size_t base_home = old_clock_pointer & clock_pointer_mask;
  3254. base_home < used_length; base_home += major_step) {
  3255. for (size_t i = 0; i < step_size; i++) {
  3256. size_t home = base_home + i;
  3257. if (home >= used_length) {
  3258. break;
  3259. }
  3260. PurgeImpl(&to_finish_eviction, home, data);
  3261. }
  3262. }
  3263. for (HandleImpl* h : to_finish_eviction) {
  3264. TrackAndReleaseEvictedEntry(h);
  3265. // NOTE: setting likely_empty_slot here can cause us to reduce the
  3266. // portion of "at home" entries, probably because an evicted entry
  3267. // is more likely to come back than a random new entry and would be
  3268. // unable to go into its home slot.
  3269. }
  3270. to_finish_eviction.clear();
  3271. // Loop exit conditions
  3272. if (data->freed_charge >= requested_charge) {
  3273. return;
  3274. }
  3275. if (max_clock_pointer == 0) {
  3276. // Cap the eviction effort at this thread (along with those operating in
  3277. // parallel) circling through the whole structure kMaxCountdown times.
  3278. // In other words, this eviction run must find something/anything that is
  3279. // unreferenced at start of and during the eviction run that isn't
  3280. // reclaimed by a concurrent eviction run.
  3281. // TODO: Does HyperClockCache need kMaxCountdown + 1?
  3282. max_clock_pointer =
  3283. old_clock_pointer +
  3284. (uint64_t{ClockHandle::kMaxCountdown + 1} * major_step);
  3285. }
  3286. if (old_clock_pointer + step_size >= max_clock_pointer) {
  3287. return;
  3288. }
  3289. if (IsEvictionEffortExceeded(*data)) {
  3290. eviction_effort_exceeded_count_.FetchAddRelaxed(1);
  3291. return;
  3292. }
  3293. }
  3294. }
  3295. size_t AutoHyperClockTable::CalcMaxUsableLength(
  3296. size_t capacity, size_t min_avg_value_size,
  3297. CacheMetadataChargePolicy metadata_charge_policy) {
  3298. double min_avg_slot_charge = min_avg_value_size * kMaxLoadFactor;
  3299. if (metadata_charge_policy == kFullChargeCacheMetadata) {
  3300. min_avg_slot_charge += sizeof(HandleImpl);
  3301. }
  3302. assert(min_avg_slot_charge > 0.0);
  3303. size_t num_slots =
  3304. static_cast<size_t>(capacity / min_avg_slot_charge + 0.999999);
  3305. const size_t slots_per_page = kPresumedPageSize / sizeof(HandleImpl);
  3306. // Round up to page size
  3307. return ((num_slots + slots_per_page - 1) / slots_per_page) * slots_per_page;
  3308. }
  3309. namespace {
  3310. bool IsHeadNonempty(const AutoHyperClockTable::HandleImpl& h) {
  3311. return !AutoHyperClockTable::HandleImpl::IsEnd(
  3312. h.head_next_with_shift.LoadRelaxed());
  3313. }
  3314. bool IsEntryAtHome(const AutoHyperClockTable::HandleImpl& h, int shift,
  3315. size_t home) {
  3316. if (MatchAndRef(nullptr, h, shift, home)) {
  3317. Unref(h);
  3318. return true;
  3319. } else {
  3320. return false;
  3321. }
  3322. }
  3323. } // namespace
  3324. void AutoHyperClockCache::ReportProblems(
  3325. const std::shared_ptr<Logger>& info_log) const {
  3326. BaseHyperClockCache::ReportProblems(info_log);
  3327. if (info_log->GetInfoLogLevel() <= InfoLogLevel::DEBUG_LEVEL) {
  3328. LoadVarianceStats head_stats;
  3329. size_t entry_at_home_count = 0;
  3330. uint64_t yield_count = 0;
  3331. this->ForEachShard([&](const Shard* shard) {
  3332. size_t count = shard->GetTableAddressCount();
  3333. uint64_t length_info = UsedLengthToLengthInfo(count);
  3334. for (size_t i = 0; i < count; ++i) {
  3335. const auto& h = *shard->GetTable().HandlePtr(i);
  3336. head_stats.Add(IsHeadNonempty(h));
  3337. int shift;
  3338. size_t home;
  3339. GetHomeIndexAndShift(length_info, i, &home, &shift);
  3340. assert(home == i);
  3341. entry_at_home_count += IsEntryAtHome(h, shift, home);
  3342. }
  3343. yield_count += shard->GetTable().GetYieldCount();
  3344. });
  3345. ROCKS_LOG_AT_LEVEL(info_log, InfoLogLevel::DEBUG_LEVEL,
  3346. "Head occupancy stats: %s", head_stats.Report().c_str());
  3347. ROCKS_LOG_AT_LEVEL(info_log, InfoLogLevel::DEBUG_LEVEL,
  3348. "Entries at home count: %zu", entry_at_home_count);
  3349. ROCKS_LOG_AT_LEVEL(info_log, InfoLogLevel::DEBUG_LEVEL,
  3350. "Yield count: %" PRIu64, yield_count);
  3351. }
  3352. }
  3353. } // namespace clock_cache
  3354. // DEPRECATED (see public API)
  3355. std::shared_ptr<Cache> NewClockCache(
  3356. size_t capacity, int num_shard_bits, bool strict_capacity_limit,
  3357. CacheMetadataChargePolicy metadata_charge_policy) {
  3358. return NewLRUCache(capacity, num_shard_bits, strict_capacity_limit,
  3359. /* high_pri_pool_ratio */ 0.5, nullptr,
  3360. kDefaultToAdaptiveMutex, metadata_charge_policy,
  3361. /* low_pri_pool_ratio */ 0.0);
  3362. }
  3363. std::shared_ptr<Cache> HyperClockCacheOptions::MakeSharedCache() const {
  3364. // For sanitized options
  3365. HyperClockCacheOptions opts = *this;
  3366. if (opts.num_shard_bits >= 20) {
  3367. return nullptr; // The cache cannot be sharded into too many fine pieces.
  3368. }
  3369. if (opts.num_shard_bits < 0) {
  3370. // Use larger shard size to reduce risk of large entries clustering
  3371. // or skewing individual shards.
  3372. constexpr size_t min_shard_size = 32U * 1024U * 1024U;
  3373. opts.num_shard_bits =
  3374. GetDefaultCacheShardBits(opts.capacity, min_shard_size);
  3375. }
  3376. std::shared_ptr<Cache> cache;
  3377. if (opts.estimated_entry_charge == 0) {
  3378. cache = std::make_shared<clock_cache::AutoHyperClockCache>(opts);
  3379. } else {
  3380. cache = std::make_shared<clock_cache::FixedHyperClockCache>(opts);
  3381. }
  3382. if (opts.secondary_cache) {
  3383. cache = std::make_shared<CacheWithSecondaryAdapter>(cache,
  3384. opts.secondary_cache);
  3385. }
  3386. return cache;
  3387. }
  3388. } // namespace ROCKSDB_NAMESPACE