block_cache_tier_file.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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. #include "utilities/persistent_cache/block_cache_tier_file.h"
  7. #ifndef OS_WIN
  8. #include <unistd.h>
  9. #endif
  10. #include <functional>
  11. #include <memory>
  12. #include <vector>
  13. #include "env/composite_env_wrapper.h"
  14. #include "logging/logging.h"
  15. #include "port/port.h"
  16. #include "util/crc32c.h"
  17. namespace ROCKSDB_NAMESPACE {
  18. //
  19. // File creation factories
  20. //
  21. Status NewWritableCacheFile(Env* const env, const std::string& filepath,
  22. std::unique_ptr<WritableFile>* file,
  23. const bool use_direct_writes = false) {
  24. EnvOptions opt;
  25. opt.use_direct_writes = use_direct_writes;
  26. Status s = env->NewWritableFile(filepath, file, opt);
  27. return s;
  28. }
  29. Status NewRandomAccessCacheFile(Env* const env, const std::string& filepath,
  30. std::unique_ptr<RandomAccessFile>* file,
  31. const bool use_direct_reads = true) {
  32. assert(env);
  33. EnvOptions opt;
  34. opt.use_direct_reads = use_direct_reads;
  35. Status s = env->NewRandomAccessFile(filepath, file, opt);
  36. return s;
  37. }
  38. //
  39. // BlockCacheFile
  40. //
  41. Status BlockCacheFile::Delete(uint64_t* size) {
  42. assert(env_);
  43. Status status = env_->GetFileSize(Path(), size);
  44. if (!status.ok()) {
  45. return status;
  46. }
  47. return env_->DeleteFile(Path());
  48. }
  49. //
  50. // CacheRecord
  51. //
  52. // Cache record represents the record on disk
  53. //
  54. // +--------+---------+----------+------------+---------------+-------------+
  55. // | magic | crc | key size | value size | key data | value data |
  56. // +--------+---------+----------+------------+---------------+-------------+
  57. // <-- 4 --><-- 4 --><-- 4 --><-- 4 --><-- key size --><-- v-size -->
  58. //
  59. struct CacheRecordHeader {
  60. CacheRecordHeader()
  61. : magic_(0), crc_(0), key_size_(0), val_size_(0) {}
  62. CacheRecordHeader(const uint32_t magic, const uint32_t key_size,
  63. const uint32_t val_size)
  64. : magic_(magic), crc_(0), key_size_(key_size), val_size_(val_size) {}
  65. uint32_t magic_;
  66. uint32_t crc_;
  67. uint32_t key_size_;
  68. uint32_t val_size_;
  69. };
  70. struct CacheRecord {
  71. CacheRecord() {}
  72. CacheRecord(const Slice& key, const Slice& val)
  73. : hdr_(MAGIC, static_cast<uint32_t>(key.size()),
  74. static_cast<uint32_t>(val.size())),
  75. key_(key),
  76. val_(val) {
  77. hdr_.crc_ = ComputeCRC();
  78. }
  79. uint32_t ComputeCRC() const;
  80. bool Serialize(std::vector<CacheWriteBuffer*>* bufs, size_t* woff);
  81. bool Deserialize(const Slice& buf);
  82. static uint32_t CalcSize(const Slice& key, const Slice& val) {
  83. return static_cast<uint32_t>(sizeof(CacheRecordHeader) + key.size() +
  84. val.size());
  85. }
  86. static const uint32_t MAGIC = 0xfefa;
  87. bool Append(std::vector<CacheWriteBuffer*>* bufs, size_t* woff,
  88. const char* data, const size_t size);
  89. CacheRecordHeader hdr_;
  90. Slice key_;
  91. Slice val_;
  92. };
  93. static_assert(sizeof(CacheRecordHeader) == 16, "DataHeader is not aligned");
  94. uint32_t CacheRecord::ComputeCRC() const {
  95. uint32_t crc = 0;
  96. CacheRecordHeader tmp = hdr_;
  97. tmp.crc_ = 0;
  98. crc = crc32c::Extend(crc, reinterpret_cast<const char*>(&tmp), sizeof(tmp));
  99. crc = crc32c::Extend(crc, reinterpret_cast<const char*>(key_.data()),
  100. key_.size());
  101. crc = crc32c::Extend(crc, reinterpret_cast<const char*>(val_.data()),
  102. val_.size());
  103. return crc;
  104. }
  105. bool CacheRecord::Serialize(std::vector<CacheWriteBuffer*>* bufs,
  106. size_t* woff) {
  107. assert(bufs->size());
  108. return Append(bufs, woff, reinterpret_cast<const char*>(&hdr_),
  109. sizeof(hdr_)) &&
  110. Append(bufs, woff, reinterpret_cast<const char*>(key_.data()),
  111. key_.size()) &&
  112. Append(bufs, woff, reinterpret_cast<const char*>(val_.data()),
  113. val_.size());
  114. }
  115. bool CacheRecord::Append(std::vector<CacheWriteBuffer*>* bufs, size_t* woff,
  116. const char* data, const size_t data_size) {
  117. assert(*woff < bufs->size());
  118. const char* p = data;
  119. size_t size = data_size;
  120. while (size && *woff < bufs->size()) {
  121. CacheWriteBuffer* buf = (*bufs)[*woff];
  122. const size_t free = buf->Free();
  123. if (size <= free) {
  124. buf->Append(p, size);
  125. size = 0;
  126. } else {
  127. buf->Append(p, free);
  128. p += free;
  129. size -= free;
  130. assert(!buf->Free());
  131. assert(buf->Used() == buf->Capacity());
  132. }
  133. if (!buf->Free()) {
  134. *woff += 1;
  135. }
  136. }
  137. assert(!size);
  138. return !size;
  139. }
  140. bool CacheRecord::Deserialize(const Slice& data) {
  141. assert(data.size() >= sizeof(CacheRecordHeader));
  142. if (data.size() < sizeof(CacheRecordHeader)) {
  143. return false;
  144. }
  145. memcpy(&hdr_, data.data(), sizeof(hdr_));
  146. assert(hdr_.key_size_ + hdr_.val_size_ + sizeof(hdr_) == data.size());
  147. if (hdr_.key_size_ + hdr_.val_size_ + sizeof(hdr_) != data.size()) {
  148. return false;
  149. }
  150. key_ = Slice(data.data_ + sizeof(hdr_), hdr_.key_size_);
  151. val_ = Slice(key_.data_ + hdr_.key_size_, hdr_.val_size_);
  152. if (!(hdr_.magic_ == MAGIC && ComputeCRC() == hdr_.crc_)) {
  153. fprintf(stderr, "** magic %d ** \n", hdr_.magic_);
  154. fprintf(stderr, "** key_size %d ** \n", hdr_.key_size_);
  155. fprintf(stderr, "** val_size %d ** \n", hdr_.val_size_);
  156. fprintf(stderr, "** key %s ** \n", key_.ToString().c_str());
  157. fprintf(stderr, "** val %s ** \n", val_.ToString().c_str());
  158. for (size_t i = 0; i < hdr_.val_size_; ++i) {
  159. fprintf(stderr, "%d.", (uint8_t)val_.data()[i]);
  160. }
  161. fprintf(stderr, "\n** cksum %d != %d **", hdr_.crc_, ComputeCRC());
  162. }
  163. assert(hdr_.magic_ == MAGIC && ComputeCRC() == hdr_.crc_);
  164. return hdr_.magic_ == MAGIC && ComputeCRC() == hdr_.crc_;
  165. }
  166. //
  167. // RandomAccessFile
  168. //
  169. bool RandomAccessCacheFile::Open(const bool enable_direct_reads) {
  170. WriteLock _(&rwlock_);
  171. return OpenImpl(enable_direct_reads);
  172. }
  173. bool RandomAccessCacheFile::OpenImpl(const bool enable_direct_reads) {
  174. rwlock_.AssertHeld();
  175. ROCKS_LOG_DEBUG(log_, "Opening cache file %s", Path().c_str());
  176. std::unique_ptr<RandomAccessFile> file;
  177. Status status =
  178. NewRandomAccessCacheFile(env_, Path(), &file, enable_direct_reads);
  179. if (!status.ok()) {
  180. Error(log_, "Error opening random access file %s. %s", Path().c_str(),
  181. status.ToString().c_str());
  182. return false;
  183. }
  184. freader_.reset(new RandomAccessFileReader(
  185. NewLegacyRandomAccessFileWrapper(file), Path(), env_));
  186. return true;
  187. }
  188. bool RandomAccessCacheFile::Read(const LBA& lba, Slice* key, Slice* val,
  189. char* scratch) {
  190. ReadLock _(&rwlock_);
  191. assert(lba.cache_id_ == cache_id_);
  192. if (!freader_) {
  193. return false;
  194. }
  195. Slice result;
  196. Status s = freader_->Read(lba.off_, lba.size_, &result, scratch);
  197. if (!s.ok()) {
  198. Error(log_, "Error reading from file %s. %s", Path().c_str(),
  199. s.ToString().c_str());
  200. return false;
  201. }
  202. assert(result.data() == scratch);
  203. return ParseRec(lba, key, val, scratch);
  204. }
  205. bool RandomAccessCacheFile::ParseRec(const LBA& lba, Slice* key, Slice* val,
  206. char* scratch) {
  207. Slice data(scratch, lba.size_);
  208. CacheRecord rec;
  209. if (!rec.Deserialize(data)) {
  210. assert(!"Error deserializing data");
  211. Error(log_, "Error de-serializing record from file %s off %d",
  212. Path().c_str(), lba.off_);
  213. return false;
  214. }
  215. *key = Slice(rec.key_);
  216. *val = Slice(rec.val_);
  217. return true;
  218. }
  219. //
  220. // WriteableCacheFile
  221. //
  222. WriteableCacheFile::~WriteableCacheFile() {
  223. WriteLock _(&rwlock_);
  224. if (!eof_) {
  225. // This file never flushed. We give priority to shutdown since this is a
  226. // cache
  227. // TODO(krad): Figure a way to flush the pending data
  228. if (file_) {
  229. assert(refs_ == 1);
  230. --refs_;
  231. }
  232. }
  233. assert(!refs_);
  234. ClearBuffers();
  235. }
  236. bool WriteableCacheFile::Create(const bool /*enable_direct_writes*/,
  237. const bool enable_direct_reads) {
  238. WriteLock _(&rwlock_);
  239. enable_direct_reads_ = enable_direct_reads;
  240. ROCKS_LOG_DEBUG(log_, "Creating new cache %s (max size is %d B)",
  241. Path().c_str(), max_size_);
  242. assert(env_);
  243. Status s = env_->FileExists(Path());
  244. if (s.ok()) {
  245. ROCKS_LOG_WARN(log_, "File %s already exists. %s", Path().c_str(),
  246. s.ToString().c_str());
  247. }
  248. s = NewWritableCacheFile(env_, Path(), &file_);
  249. if (!s.ok()) {
  250. ROCKS_LOG_WARN(log_, "Unable to create file %s. %s", Path().c_str(),
  251. s.ToString().c_str());
  252. return false;
  253. }
  254. assert(!refs_);
  255. ++refs_;
  256. return true;
  257. }
  258. bool WriteableCacheFile::Append(const Slice& key, const Slice& val, LBA* lba) {
  259. WriteLock _(&rwlock_);
  260. if (eof_) {
  261. // We can't append since the file is full
  262. return false;
  263. }
  264. // estimate the space required to store the (key, val)
  265. uint32_t rec_size = CacheRecord::CalcSize(key, val);
  266. if (!ExpandBuffer(rec_size)) {
  267. // unable to expand the buffer
  268. ROCKS_LOG_DEBUG(log_, "Error expanding buffers. size=%d", rec_size);
  269. return false;
  270. }
  271. lba->cache_id_ = cache_id_;
  272. lba->off_ = disk_woff_;
  273. lba->size_ = rec_size;
  274. CacheRecord rec(key, val);
  275. if (!rec.Serialize(&bufs_, &buf_woff_)) {
  276. // unexpected error: unable to serialize the data
  277. assert(!"Error serializing record");
  278. return false;
  279. }
  280. disk_woff_ += rec_size;
  281. eof_ = disk_woff_ >= max_size_;
  282. // dispatch buffer for flush
  283. DispatchBuffer();
  284. return true;
  285. }
  286. bool WriteableCacheFile::ExpandBuffer(const size_t size) {
  287. rwlock_.AssertHeld();
  288. assert(!eof_);
  289. // determine if there is enough space
  290. size_t free = 0; // compute the free space left in buffer
  291. for (size_t i = buf_woff_; i < bufs_.size(); ++i) {
  292. free += bufs_[i]->Free();
  293. if (size <= free) {
  294. // we have enough space in the buffer
  295. return true;
  296. }
  297. }
  298. // expand the buffer until there is enough space to write `size` bytes
  299. assert(free < size);
  300. assert(alloc_);
  301. while (free < size) {
  302. CacheWriteBuffer* const buf = alloc_->Allocate();
  303. if (!buf) {
  304. ROCKS_LOG_DEBUG(log_, "Unable to allocate buffers");
  305. return false;
  306. }
  307. size_ += static_cast<uint32_t>(buf->Free());
  308. free += buf->Free();
  309. bufs_.push_back(buf);
  310. }
  311. assert(free >= size);
  312. return true;
  313. }
  314. void WriteableCacheFile::DispatchBuffer() {
  315. rwlock_.AssertHeld();
  316. assert(bufs_.size());
  317. assert(buf_doff_ <= buf_woff_);
  318. assert(buf_woff_ <= bufs_.size());
  319. if (pending_ios_) {
  320. return;
  321. }
  322. if (!eof_ && buf_doff_ == buf_woff_) {
  323. // dispatch buffer is pointing to write buffer and we haven't hit eof
  324. return;
  325. }
  326. assert(eof_ || buf_doff_ < buf_woff_);
  327. assert(buf_doff_ < bufs_.size());
  328. assert(file_);
  329. assert(alloc_);
  330. auto* buf = bufs_[buf_doff_];
  331. const uint64_t file_off = buf_doff_ * alloc_->BufferSize();
  332. assert(!buf->Free() ||
  333. (eof_ && buf_doff_ == buf_woff_ && buf_woff_ < bufs_.size()));
  334. // we have reached end of file, and there is space in the last buffer
  335. // pad it with zero for direct IO
  336. buf->FillTrailingZeros();
  337. assert(buf->Used() % kFileAlignmentSize == 0);
  338. writer_->Write(file_.get(), buf, file_off,
  339. std::bind(&WriteableCacheFile::BufferWriteDone, this));
  340. pending_ios_++;
  341. buf_doff_++;
  342. }
  343. void WriteableCacheFile::BufferWriteDone() {
  344. WriteLock _(&rwlock_);
  345. assert(bufs_.size());
  346. pending_ios_--;
  347. if (buf_doff_ < bufs_.size()) {
  348. DispatchBuffer();
  349. }
  350. if (eof_ && buf_doff_ >= bufs_.size() && !pending_ios_) {
  351. // end-of-file reached, move to read mode
  352. CloseAndOpenForReading();
  353. }
  354. }
  355. void WriteableCacheFile::CloseAndOpenForReading() {
  356. // Our env abstraction do not allow reading from a file opened for appending
  357. // We need close the file and re-open it for reading
  358. Close();
  359. RandomAccessCacheFile::OpenImpl(enable_direct_reads_);
  360. }
  361. bool WriteableCacheFile::ReadBuffer(const LBA& lba, Slice* key, Slice* block,
  362. char* scratch) {
  363. rwlock_.AssertHeld();
  364. if (!ReadBuffer(lba, scratch)) {
  365. Error(log_, "Error reading from buffer. cache=%d off=%d", cache_id_,
  366. lba.off_);
  367. return false;
  368. }
  369. return ParseRec(lba, key, block, scratch);
  370. }
  371. bool WriteableCacheFile::ReadBuffer(const LBA& lba, char* data) {
  372. rwlock_.AssertHeld();
  373. assert(lba.off_ < disk_woff_);
  374. assert(alloc_);
  375. // we read from the buffers like reading from a flat file. The list of buffers
  376. // are treated as contiguous stream of data
  377. char* tmp = data;
  378. size_t pending_nbytes = lba.size_;
  379. // start buffer
  380. size_t start_idx = lba.off_ / alloc_->BufferSize();
  381. // offset into the start buffer
  382. size_t start_off = lba.off_ % alloc_->BufferSize();
  383. assert(start_idx <= buf_woff_);
  384. for (size_t i = start_idx; pending_nbytes && i < bufs_.size(); ++i) {
  385. assert(i <= buf_woff_);
  386. auto* buf = bufs_[i];
  387. assert(i == buf_woff_ || !buf->Free());
  388. // bytes to write to the buffer
  389. size_t nbytes = pending_nbytes > (buf->Used() - start_off)
  390. ? (buf->Used() - start_off)
  391. : pending_nbytes;
  392. memcpy(tmp, buf->Data() + start_off, nbytes);
  393. // left over to be written
  394. pending_nbytes -= nbytes;
  395. start_off = 0;
  396. tmp += nbytes;
  397. }
  398. assert(!pending_nbytes);
  399. if (pending_nbytes) {
  400. return false;
  401. }
  402. assert(tmp == data + lba.size_);
  403. return true;
  404. }
  405. void WriteableCacheFile::Close() {
  406. rwlock_.AssertHeld();
  407. assert(size_ >= max_size_);
  408. assert(disk_woff_ >= max_size_);
  409. assert(buf_doff_ == bufs_.size());
  410. assert(bufs_.size() - buf_woff_ <= 1);
  411. assert(!pending_ios_);
  412. Info(log_, "Closing file %s. size=%d written=%d", Path().c_str(), size_,
  413. disk_woff_);
  414. ClearBuffers();
  415. file_.reset();
  416. assert(refs_);
  417. --refs_;
  418. }
  419. void WriteableCacheFile::ClearBuffers() {
  420. assert(alloc_);
  421. for (size_t i = 0; i < bufs_.size(); ++i) {
  422. alloc_->Deallocate(bufs_[i]);
  423. }
  424. bufs_.clear();
  425. }
  426. //
  427. // ThreadedFileWriter implementation
  428. //
  429. ThreadedWriter::ThreadedWriter(PersistentCacheTier* const cache,
  430. const size_t qdepth, const size_t io_size)
  431. : Writer(cache), io_size_(io_size) {
  432. for (size_t i = 0; i < qdepth; ++i) {
  433. port::Thread th(&ThreadedWriter::ThreadMain, this);
  434. threads_.push_back(std::move(th));
  435. }
  436. }
  437. void ThreadedWriter::Stop() {
  438. // notify all threads to exit
  439. for (size_t i = 0; i < threads_.size(); ++i) {
  440. q_.Push(IO(/*signal=*/true));
  441. }
  442. // wait for all threads to exit
  443. for (auto& th : threads_) {
  444. th.join();
  445. assert(!th.joinable());
  446. }
  447. threads_.clear();
  448. }
  449. void ThreadedWriter::Write(WritableFile* const file, CacheWriteBuffer* buf,
  450. const uint64_t file_off,
  451. const std::function<void()> callback) {
  452. q_.Push(IO(file, buf, file_off, callback));
  453. }
  454. void ThreadedWriter::ThreadMain() {
  455. while (true) {
  456. // Fetch the IO to process
  457. IO io(q_.Pop());
  458. if (io.signal_) {
  459. // that's secret signal to exit
  460. break;
  461. }
  462. // Reserve space for writing the buffer
  463. while (!cache_->Reserve(io.buf_->Used())) {
  464. // We can fail to reserve space if every file in the system
  465. // is being currently accessed
  466. /* sleep override */
  467. Env::Default()->SleepForMicroseconds(1000000);
  468. }
  469. DispatchIO(io);
  470. io.callback_();
  471. }
  472. }
  473. void ThreadedWriter::DispatchIO(const IO& io) {
  474. size_t written = 0;
  475. while (written < io.buf_->Used()) {
  476. Slice data(io.buf_->Data() + written, io_size_);
  477. Status s = io.file_->Append(data);
  478. assert(s.ok());
  479. if (!s.ok()) {
  480. // That is definite IO error to device. There is not much we can
  481. // do but ignore the failure. This can lead to corruption of data on
  482. // disk, but the cache will skip while reading
  483. fprintf(stderr, "Error writing data to file. %s\n", s.ToString().c_str());
  484. }
  485. written += io_size_;
  486. }
  487. }
  488. } // namespace ROCKSDB_NAMESPACE
  489. #endif