Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2011 The LevelDB Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file. See the AUTHORS file for names of contributors.4//5// The representation of a DBImpl consists of a set of Versions. The6// newest version is called "current". Older versions may be kept7// around to provide a consistent view to live iterators.8//9// Each Version keeps track of a set of Table files per level. The10// entire set of versions is maintained in a VersionSet.11//12// Version,VersionSet are thread-compatible, but require external13// synchronization on all accesses.15#ifndef STORAGE_LEVELDB_DB_VERSION_SET_H_16#define STORAGE_LEVELDB_DB_VERSION_SET_H_18#include <map>19#include <set>20#include <vector>22#include "db/dbformat.h"23#include "db/version_edit.h"24#include "port/port.h"25#include "port/thread_annotations.h"27namespace leveldb {29namespace log {30class Writer;31}33class Compaction;34class Iterator;35class MemTable;36class TableBuilder;37class TableCache;38class Version;39class VersionSet;40class WritableFile;42// Return the smallest index i such that files[i]->largest >= key.43// Return files.size() if there is no such file.44// REQUIRES: "files" contains a sorted list of non-overlapping files.45int FindFile(const InternalKeyComparator& icmp,46const std::vector<FileMetaData*>& files, const Slice& key);48// Returns true iff some file in "files" overlaps the user key range49// [*smallest,*largest].50// smallest==nullptr represents a key smaller than all keys in the DB.51// largest==nullptr represents a key largest than all keys in the DB.52// REQUIRES: If disjoint_sorted_files, files[] contains disjoint ranges53// in sorted order.54bool SomeFileOverlapsRange(const InternalKeyComparator& icmp,55bool disjoint_sorted_files,56const std::vector<FileMetaData*>& files,57const Slice* smallest_user_key,58const Slice* largest_user_key);60class Version {61public:62// Lookup the value for key. If found, store it in *val and63// return OK. Else return a non-OK status. Fills *stats.64// REQUIRES: lock is not held65struct GetStats {66FileMetaData* seek_file;67int seek_file_level;68};70// Append to *iters a sequence of iterators that will71// yield the contents of this Version when merged together.72// REQUIRES: This version has been saved (see VersionSet::SaveTo)73void AddIterators(const ReadOptions&, std::vector<Iterator*>* iters);75Status Get(const ReadOptions&, const LookupKey& key, std::string* val,76GetStats* stats);78// Adds "stats" into the current state. Returns true if a new79// compaction may need to be triggered, false otherwise.80// REQUIRES: lock is held81bool UpdateStats(const GetStats& stats);83// Record a sample of bytes read at the specified internal key.84// Samples are taken approximately once every config::kReadBytesPeriod85// bytes. Returns true if a new compaction may need to be triggered.86// REQUIRES: lock is held87bool RecordReadSample(Slice key);89// Reference count management (so Versions do not disappear out from90// under live iterators)91void Ref();92void Unref();94void GetOverlappingInputs(95int level,96const InternalKey* begin, // nullptr means before all keys97const InternalKey* end, // nullptr means after all keys98std::vector<FileMetaData*>* inputs);100// Returns true iff some file in the specified level overlaps101// some part of [*smallest_user_key,*largest_user_key].102// smallest_user_key==nullptr represents a key smaller than all the DB's keys.103// largest_user_key==nullptr represents a key largest than all the DB's keys.104bool OverlapInLevel(int level, const Slice* smallest_user_key,105const Slice* largest_user_key);107// Return the level at which we should place a new memtable compaction108// result that covers the range [smallest_user_key,largest_user_key].109int PickLevelForMemTableOutput(const Slice& smallest_user_key,110const Slice& largest_user_key);112int NumFiles(int level) const { return files_[level].size(); }114// Return a human readable string that describes this version's contents.115std::string DebugString() const;117private:118friend class Compaction;119friend class VersionSet;121class LevelFileNumIterator;123explicit Version(VersionSet* vset)124: vset_(vset),125next_(this),126prev_(this),127refs_(0),128file_to_compact_(nullptr),129file_to_compact_level_(-1),130compaction_score_(-1),131compaction_level_(-1) {}133Version(const Version&) = delete;134Version& operator=(const Version&) = delete;136~Version();138Iterator* NewConcatenatingIterator(const ReadOptions&, int level) const;140// Call func(arg, level, f) for every file that overlaps user_key in141// order from newest to oldest. If an invocation of func returns142// false, makes no more calls.143//144// REQUIRES: user portion of internal_key == user_key.145void ForEachOverlapping(Slice user_key, Slice internal_key, void* arg,146bool (*func)(void*, int, FileMetaData*));148VersionSet* vset_; // VersionSet to which this Version belongs149Version* next_; // Next version in linked list150Version* prev_; // Previous version in linked list151int refs_; // Number of live refs to this version153// List of files per level154std::vector<FileMetaData*> files_[config::kNumLevels];156// Next file to compact based on seek stats.157FileMetaData* file_to_compact_;158int file_to_compact_level_;160// Level that should be compacted next and its compaction score.161// Score < 1 means compaction is not strictly needed. These fields162// are initialized by Finalize().163double compaction_score_;164int compaction_level_;165};167class VersionSet {168public:169VersionSet(const std::string& dbname, const Options* options,170TableCache* table_cache, const InternalKeyComparator*);171VersionSet(const VersionSet&) = delete;172VersionSet& operator=(const VersionSet&) = delete;174~VersionSet();176// Apply *edit to the current version to form a new descriptor that177// is both saved to persistent state and installed as the new178// current version. Will release *mu while actually writing to the file.179// REQUIRES: *mu is held on entry.180// REQUIRES: no other thread concurrently calls LogAndApply()181Status LogAndApply(VersionEdit* edit, port::Mutex* mu)182EXCLUSIVE_LOCKS_REQUIRED(mu);184// Recover the last saved descriptor from persistent storage.185Status Recover(bool* save_manifest);187// Return the current version.188Version* current() const { return current_; }190// Return the current manifest file number191uint64_t ManifestFileNumber() const { return manifest_file_number_; }193// Allocate and return a new file number194uint64_t NewFileNumber() { return next_file_number_++; }196// Arrange to reuse "file_number" unless a newer file number has197// already been allocated.198// REQUIRES: "file_number" was returned by a call to NewFileNumber().199void ReuseFileNumber(uint64_t file_number) {200if (next_file_number_ == file_number + 1) {201next_file_number_ = file_number;202}203}205// Return the number of Table files at the specified level.206int NumLevelFiles(int level) const;208// Return the combined file size of all files at the specified level.209int64_t NumLevelBytes(int level) const;211// Return the last sequence number.212uint64_t LastSequence() const { return last_sequence_; }214// Set the last sequence number to s.215void SetLastSequence(uint64_t s) {216assert(s >= last_sequence_);217last_sequence_ = s;218}220// Mark the specified file number as used.221void MarkFileNumberUsed(uint64_t number);223// Return the current log file number.224uint64_t LogNumber() const { return log_number_; }226// Return the log file number for the log file that is currently227// being compacted, or zero if there is no such log file.228uint64_t PrevLogNumber() const { return prev_log_number_; }230// Pick level and inputs for a new compaction.231// Returns nullptr if there is no compaction to be done.232// Otherwise returns a pointer to a heap-allocated object that233// describes the compaction. Caller should delete the result.234Compaction* PickCompaction();236// Return a compaction object for compacting the range [begin,end] in237// the specified level. Returns nullptr if there is nothing in that238// level that overlaps the specified range. Caller should delete239// the result.240Compaction* CompactRange(int level, const InternalKey* begin,241const InternalKey* end);243// Return the maximum overlapping data (in bytes) at next level for any244// file at a level >= 1.245int64_t MaxNextLevelOverlappingBytes();247// Create an iterator that reads over the compaction inputs for "*c".248// The caller should delete the iterator when no longer needed.249Iterator* MakeInputIterator(Compaction* c);
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.