1 //  Copyright (c) 2013, 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 #ifndef ROCKSDB_LITE
6 
7 #include "utilities/persistent_cache/block_cache_tier_metadata.h"
8 
9 #include <functional>
10 
11 namespace ROCKSDB_NAMESPACE {
12 
Insert(BlockCacheFile * file)13 bool BlockCacheTierMetadata::Insert(BlockCacheFile* file) {
14   return cache_file_index_.Insert(file);
15 }
16 
Lookup(const uint32_t cache_id)17 BlockCacheFile* BlockCacheTierMetadata::Lookup(const uint32_t cache_id) {
18   BlockCacheFile* ret = nullptr;
19   BlockCacheFile lookup_key(cache_id);
20   bool ok = cache_file_index_.Find(&lookup_key, &ret);
21   if (ok) {
22     assert(ret->refs_);
23     return ret;
24   }
25   return nullptr;
26 }
27 
Evict()28 BlockCacheFile* BlockCacheTierMetadata::Evict() {
29   using std::placeholders::_1;
30   auto fn = std::bind(&BlockCacheTierMetadata::RemoveAllKeys, this, _1);
31   return cache_file_index_.Evict(fn);
32 }
33 
Clear()34 void BlockCacheTierMetadata::Clear() {
35   cache_file_index_.Clear([](BlockCacheFile* arg){ delete arg; });
36   block_index_.Clear([](BlockInfo* arg){ delete arg; });
37 }
38 
Insert(const Slice & key,const LBA & lba)39 BlockInfo* BlockCacheTierMetadata::Insert(const Slice& key, const LBA& lba) {
40   std::unique_ptr<BlockInfo> binfo(new BlockInfo(key, lba));
41   if (!block_index_.Insert(binfo.get())) {
42     return nullptr;
43   }
44   return binfo.release();
45 }
46 
Lookup(const Slice & key,LBA * lba)47 bool BlockCacheTierMetadata::Lookup(const Slice& key, LBA* lba) {
48   BlockInfo lookup_key(key);
49   BlockInfo* block;
50   port::RWMutex* rlock = nullptr;
51   if (!block_index_.Find(&lookup_key, &block, &rlock)) {
52     return false;
53   }
54 
55   ReadUnlock _(rlock);
56   assert(block->key_ == key.ToString());
57   if (lba) {
58     *lba = block->lba_;
59   }
60   return true;
61 }
62 
Remove(const Slice & key)63 BlockInfo* BlockCacheTierMetadata::Remove(const Slice& key) {
64   BlockInfo lookup_key(key);
65   BlockInfo* binfo = nullptr;
66   bool ok __attribute__((__unused__));
67   ok = block_index_.Erase(&lookup_key, &binfo);
68   assert(ok);
69   return binfo;
70 }
71 
RemoveAllKeys(BlockCacheFile * f)72 void BlockCacheTierMetadata::RemoveAllKeys(BlockCacheFile* f) {
73   for (BlockInfo* binfo : f->block_infos()) {
74     BlockInfo* tmp = nullptr;
75     bool status = block_index_.Erase(binfo, &tmp);
76     (void)status;
77     assert(status);
78     assert(tmp == binfo);
79     delete binfo;
80   }
81   f->block_infos().clear();
82 }
83 
84 }  // namespace ROCKSDB_NAMESPACE
85 
86 #endif
87