lru_cache.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. #pragma once
  10. #include <string>
  11. #include "cache/sharded_cache.h"
  12. #include "port/malloc.h"
  13. #include "port/port.h"
  14. #include "util/autovector.h"
  15. namespace ROCKSDB_NAMESPACE {
  16. // LRU cache implementation. This class is not thread-safe.
  17. // An entry is a variable length heap-allocated structure.
  18. // Entries are referenced by cache and/or by any external entity.
  19. // The cache keeps all its entries in a hash table. Some elements
  20. // are also stored on LRU list.
  21. //
  22. // LRUHandle can be in these states:
  23. // 1. Referenced externally AND in hash table.
  24. // In that case the entry is *not* in the LRU list
  25. // (refs >= 1 && in_cache == true)
  26. // 2. Not referenced externally AND in hash table.
  27. // In that case the entry is in the LRU list and can be freed.
  28. // (refs == 0 && in_cache == true)
  29. // 3. Referenced externally AND not in hash table.
  30. // In that case the entry is not in the LRU list and not in hash table.
  31. // The entry can be freed when refs becomes 0.
  32. // (refs >= 1 && in_cache == false)
  33. //
  34. // All newly created LRUHandles are in state 1. If you call
  35. // LRUCacheShard::Release on entry in state 1, it will go into state 2.
  36. // To move from state 1 to state 3, either call LRUCacheShard::Erase or
  37. // LRUCacheShard::Insert with the same key (but possibly different value).
  38. // To move from state 2 to state 1, use LRUCacheShard::Lookup.
  39. // Before destruction, make sure that no handles are in state 1. This means
  40. // that any successful LRUCacheShard::Lookup/LRUCacheShard::Insert have a
  41. // matching LRUCache::Release (to move into state 2) or LRUCacheShard::Erase
  42. // (to move into state 3).
  43. struct LRUHandle {
  44. void* value;
  45. void (*deleter)(const Slice&, void* value);
  46. LRUHandle* next_hash;
  47. LRUHandle* next;
  48. LRUHandle* prev;
  49. size_t charge; // TODO(opt): Only allow uint32_t?
  50. size_t key_length;
  51. // The hash of key(). Used for fast sharding and comparisons.
  52. uint32_t hash;
  53. // The number of external refs to this entry. The cache itself is not counted.
  54. uint32_t refs;
  55. enum Flags : uint8_t {
  56. // Whether this entry is referenced by the hash table.
  57. IN_CACHE = (1 << 0),
  58. // Whether this entry is high priority entry.
  59. IS_HIGH_PRI = (1 << 1),
  60. // Whether this entry is in high-pri pool.
  61. IN_HIGH_PRI_POOL = (1 << 2),
  62. // Wwhether this entry has had any lookups (hits).
  63. HAS_HIT = (1 << 3),
  64. };
  65. uint8_t flags;
  66. // Beginning of the key (MUST BE THE LAST FIELD IN THIS STRUCT!)
  67. char key_data[1];
  68. Slice key() const { return Slice(key_data, key_length); }
  69. // Increase the reference count by 1.
  70. void Ref() { refs++; }
  71. // Just reduce the reference count by 1. Return true if it was last reference.
  72. bool Unref() {
  73. assert(refs > 0);
  74. refs--;
  75. return refs == 0;
  76. }
  77. // Return true if there are external refs, false otherwise.
  78. bool HasRefs() const { return refs > 0; }
  79. bool InCache() const { return flags & IN_CACHE; }
  80. bool IsHighPri() const { return flags & IS_HIGH_PRI; }
  81. bool InHighPriPool() const { return flags & IN_HIGH_PRI_POOL; }
  82. bool HasHit() const { return flags & HAS_HIT; }
  83. void SetInCache(bool in_cache) {
  84. if (in_cache) {
  85. flags |= IN_CACHE;
  86. } else {
  87. flags &= ~IN_CACHE;
  88. }
  89. }
  90. void SetPriority(Cache::Priority priority) {
  91. if (priority == Cache::Priority::HIGH) {
  92. flags |= IS_HIGH_PRI;
  93. } else {
  94. flags &= ~IS_HIGH_PRI;
  95. }
  96. }
  97. void SetInHighPriPool(bool in_high_pri_pool) {
  98. if (in_high_pri_pool) {
  99. flags |= IN_HIGH_PRI_POOL;
  100. } else {
  101. flags &= ~IN_HIGH_PRI_POOL;
  102. }
  103. }
  104. void SetHit() { flags |= HAS_HIT; }
  105. void Free() {
  106. assert(refs == 0);
  107. if (deleter) {
  108. (*deleter)(key(), value);
  109. }
  110. delete[] reinterpret_cast<char*>(this);
  111. }
  112. // Caclculate the memory usage by metadata
  113. inline size_t CalcTotalCharge(
  114. CacheMetadataChargePolicy metadata_charge_policy) {
  115. size_t meta_charge = 0;
  116. if (metadata_charge_policy == kFullChargeCacheMetadata) {
  117. #ifdef ROCKSDB_MALLOC_USABLE_SIZE
  118. meta_charge += malloc_usable_size(static_cast<void*>(this));
  119. #else
  120. // This is the size that is used when a new handle is created
  121. meta_charge += sizeof(LRUHandle) - 1 + key_length;
  122. #endif
  123. }
  124. return charge + meta_charge;
  125. }
  126. };
  127. // We provide our own simple hash table since it removes a whole bunch
  128. // of porting hacks and is also faster than some of the built-in hash
  129. // table implementations in some of the compiler/runtime combinations
  130. // we have tested. E.g., readrandom speeds up by ~5% over the g++
  131. // 4.4.3's builtin hashtable.
  132. class LRUHandleTable {
  133. public:
  134. LRUHandleTable();
  135. ~LRUHandleTable();
  136. LRUHandle* Lookup(const Slice& key, uint32_t hash);
  137. LRUHandle* Insert(LRUHandle* h);
  138. LRUHandle* Remove(const Slice& key, uint32_t hash);
  139. template <typename T>
  140. void ApplyToAllCacheEntries(T func) {
  141. for (uint32_t i = 0; i < length_; i++) {
  142. LRUHandle* h = list_[i];
  143. while (h != nullptr) {
  144. auto n = h->next_hash;
  145. assert(h->InCache());
  146. func(h);
  147. h = n;
  148. }
  149. }
  150. }
  151. private:
  152. // Return a pointer to slot that points to a cache entry that
  153. // matches key/hash. If there is no such cache entry, return a
  154. // pointer to the trailing slot in the corresponding linked list.
  155. LRUHandle** FindPointer(const Slice& key, uint32_t hash);
  156. void Resize();
  157. // The table consists of an array of buckets where each bucket is
  158. // a linked list of cache entries that hash into the bucket.
  159. LRUHandle** list_;
  160. uint32_t length_;
  161. uint32_t elems_;
  162. };
  163. // A single shard of sharded cache.
  164. class ALIGN_AS(CACHE_LINE_SIZE) LRUCacheShard final : public CacheShard {
  165. public:
  166. LRUCacheShard(size_t capacity, bool strict_capacity_limit,
  167. double high_pri_pool_ratio, bool use_adaptive_mutex,
  168. CacheMetadataChargePolicy metadata_charge_policy);
  169. virtual ~LRUCacheShard() override = default;
  170. // Separate from constructor so caller can easily make an array of LRUCache
  171. // if current usage is more than new capacity, the function will attempt to
  172. // free the needed space
  173. virtual void SetCapacity(size_t capacity) override;
  174. // Set the flag to reject insertion if cache if full.
  175. virtual void SetStrictCapacityLimit(bool strict_capacity_limit) override;
  176. // Set percentage of capacity reserved for high-pri cache entries.
  177. void SetHighPriorityPoolRatio(double high_pri_pool_ratio);
  178. // Like Cache methods, but with an extra "hash" parameter.
  179. virtual Status Insert(const Slice& key, uint32_t hash, void* value,
  180. size_t charge,
  181. void (*deleter)(const Slice& key, void* value),
  182. Cache::Handle** handle,
  183. Cache::Priority priority) override;
  184. virtual Cache::Handle* Lookup(const Slice& key, uint32_t hash) override;
  185. virtual bool Ref(Cache::Handle* handle) override;
  186. virtual bool Release(Cache::Handle* handle,
  187. bool force_erase = false) override;
  188. virtual void Erase(const Slice& key, uint32_t hash) override;
  189. // Although in some platforms the update of size_t is atomic, to make sure
  190. // GetUsage() and GetPinnedUsage() work correctly under any platform, we'll
  191. // protect them with mutex_.
  192. virtual size_t GetUsage() const override;
  193. virtual size_t GetPinnedUsage() const override;
  194. virtual void ApplyToAllCacheEntries(void (*callback)(void*, size_t),
  195. bool thread_safe) override;
  196. virtual void EraseUnRefEntries() override;
  197. virtual std::string GetPrintableOptions() const override;
  198. void TEST_GetLRUList(LRUHandle** lru, LRUHandle** lru_low_pri);
  199. // Retrieves number of elements in LRU, for unit test purpose only
  200. // not threadsafe
  201. size_t TEST_GetLRUSize();
  202. // Retrives high pri pool ratio
  203. double GetHighPriPoolRatio();
  204. private:
  205. void LRU_Remove(LRUHandle* e);
  206. void LRU_Insert(LRUHandle* e);
  207. // Overflow the last entry in high-pri pool to low-pri pool until size of
  208. // high-pri pool is no larger than the size specify by high_pri_pool_pct.
  209. void MaintainPoolSize();
  210. // Free some space following strict LRU policy until enough space
  211. // to hold (usage_ + charge) is freed or the lru list is empty
  212. // This function is not thread safe - it needs to be executed while
  213. // holding the mutex_
  214. void EvictFromLRU(size_t charge, autovector<LRUHandle*>* deleted);
  215. // Initialized before use.
  216. size_t capacity_;
  217. // Memory size for entries in high-pri pool.
  218. size_t high_pri_pool_usage_;
  219. // Whether to reject insertion if cache reaches its full capacity.
  220. bool strict_capacity_limit_;
  221. // Ratio of capacity reserved for high priority cache entries.
  222. double high_pri_pool_ratio_;
  223. // High-pri pool size, equals to capacity * high_pri_pool_ratio.
  224. // Remember the value to avoid recomputing each time.
  225. double high_pri_pool_capacity_;
  226. // Dummy head of LRU list.
  227. // lru.prev is newest entry, lru.next is oldest entry.
  228. // LRU contains items which can be evicted, ie reference only by cache
  229. LRUHandle lru_;
  230. // Pointer to head of low-pri pool in LRU list.
  231. LRUHandle* lru_low_pri_;
  232. // ------------^^^^^^^^^^^^^-----------
  233. // Not frequently modified data members
  234. // ------------------------------------
  235. //
  236. // We separate data members that are updated frequently from the ones that
  237. // are not frequently updated so that they don't share the same cache line
  238. // which will lead into false cache sharing
  239. //
  240. // ------------------------------------
  241. // Frequently modified data members
  242. // ------------vvvvvvvvvvvvv-----------
  243. LRUHandleTable table_;
  244. // Memory size for entries residing in the cache
  245. size_t usage_;
  246. // Memory size for entries residing only in the LRU list
  247. size_t lru_usage_;
  248. // mutex_ protects the following state.
  249. // We don't count mutex_ as the cache's internal state so semantically we
  250. // don't mind mutex_ invoking the non-const actions.
  251. mutable port::Mutex mutex_;
  252. };
  253. class LRUCache
  254. #ifdef NDEBUG
  255. final
  256. #endif
  257. : public ShardedCache {
  258. public:
  259. LRUCache(size_t capacity, int num_shard_bits, bool strict_capacity_limit,
  260. double high_pri_pool_ratio,
  261. std::shared_ptr<MemoryAllocator> memory_allocator = nullptr,
  262. bool use_adaptive_mutex = kDefaultToAdaptiveMutex,
  263. CacheMetadataChargePolicy metadata_charge_policy =
  264. kDontChargeCacheMetadata);
  265. virtual ~LRUCache();
  266. virtual const char* Name() const override { return "LRUCache"; }
  267. virtual CacheShard* GetShard(int shard) override;
  268. virtual const CacheShard* GetShard(int shard) const override;
  269. virtual void* Value(Handle* handle) override;
  270. virtual size_t GetCharge(Handle* handle) const override;
  271. virtual uint32_t GetHash(Handle* handle) const override;
  272. virtual void DisownData() override;
  273. // Retrieves number of elements in LRU, for unit test purpose only
  274. size_t TEST_GetLRUSize();
  275. // Retrives high pri pool ratio
  276. double GetHighPriPoolRatio();
  277. private:
  278. LRUCacheShard* shards_ = nullptr;
  279. int num_shards_ = 0;
  280. };
  281. } // namespace ROCKSDB_NAMESPACE