Coverage Report

Created: 2025-11-24 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/leveldb/db/db_impl.cc
Line
Count
Source
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 be
3
// found in the LICENSE file. See the AUTHORS file for names of contributors.
4
5
#include "db/db_impl.h"
6
7
#include <algorithm>
8
#include <atomic>
9
#include <cstdint>
10
#include <cstdio>
11
#include <set>
12
#include <string>
13
#include <vector>
14
15
#include "db/builder.h"
16
#include "db/db_iter.h"
17
#include "db/dbformat.h"
18
#include "db/filename.h"
19
#include "db/log_reader.h"
20
#include "db/log_writer.h"
21
#include "db/memtable.h"
22
#include "db/table_cache.h"
23
#include "db/version_set.h"
24
#include "db/write_batch_internal.h"
25
#include "leveldb/db.h"
26
#include "leveldb/env.h"
27
#include "leveldb/status.h"
28
#include "leveldb/table.h"
29
#include "leveldb/table_builder.h"
30
#include "port/port.h"
31
#include "table/block.h"
32
#include "table/merger.h"
33
#include "table/two_level_iterator.h"
34
#include "util/coding.h"
35
#include "util/logging.h"
36
#include "util/mutexlock.h"
37
38
namespace leveldb {
39
40
const int kNumNonTableCacheFiles = 10;
41
42
// Information kept for every waiting writer
43
struct DBImpl::Writer {
44
  explicit Writer(port::Mutex* mu)
45
1.96M
      : batch(nullptr), sync(false), done(false), cv(mu) {}
46
47
  Status status;
48
  WriteBatch* batch;
49
  bool sync;
50
  bool done;
51
  port::CondVar cv;
52
};
53
54
struct DBImpl::CompactionState {
55
  // Files produced by compaction
56
  struct Output {
57
    uint64_t number;
58
    uint64_t file_size;
59
    InternalKey smallest, largest;
60
  };
61
62
293k
  Output* current_output() { return &outputs[outputs.size() - 1]; }
63
64
  explicit CompactionState(Compaction* c)
65
26.9k
      : compaction(c),
66
26.9k
        smallest_snapshot(0),
67
26.9k
        outfile(nullptr),
68
26.9k
        builder(nullptr),
69
26.9k
        total_bytes(0) {}
70
71
  Compaction* const compaction;
72
73
  // Sequence numbers < smallest_snapshot are not significant since we
74
  // will never have to service a snapshot below smallest_snapshot.
75
  // Therefore if we have seen a sequence number S <= smallest_snapshot,
76
  // we can drop all entries for the same key with sequence numbers < S.
77
  SequenceNumber smallest_snapshot;
78
79
  std::vector<Output> outputs;
80
81
  // State kept for output being generated
82
  WritableFile* outfile;
83
  TableBuilder* builder;
84
85
  uint64_t total_bytes;
86
};
87
88
// Fix user-supplied options to be reasonable
89
template <class T, class V>
90
452k
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
452k
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
452k
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
452k
}
db_impl.cc:void leveldb::ClipToRange<int, int>(int*, int, int)
Line
Count
Source
90
113k
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
113k
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
113k
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
113k
}
db_impl.cc:void leveldb::ClipToRange<unsigned long, int>(unsigned long*, int, int)
Line
Count
Source
90
339k
static void ClipToRange(T* ptr, V minvalue, V maxvalue) {
91
339k
  if (static_cast<V>(*ptr) > maxvalue) *ptr = maxvalue;
92
339k
  if (static_cast<V>(*ptr) < minvalue) *ptr = minvalue;
93
339k
}
94
Options SanitizeOptions(const std::string& dbname,
95
                        const InternalKeyComparator* icmp,
96
                        const InternalFilterPolicy* ipolicy,
97
113k
                        const Options& src) {
98
113k
  Options result = src;
99
113k
  result.comparator = icmp;
100
113k
  result.filter_policy = (src.filter_policy != nullptr) ? ipolicy : nullptr;
101
113k
  ClipToRange(&result.max_open_files, 64 + kNumNonTableCacheFiles, 50000);
102
113k
  ClipToRange(&result.write_buffer_size, 64 << 10, 1 << 30);
103
113k
  ClipToRange(&result.max_file_size, 1 << 20, 1 << 30);
104
113k
  ClipToRange(&result.block_size, 1 << 10, 4 << 20);
105
113k
  if (result.info_log == nullptr) {
106
    // Open a log file in the same directory as the db
107
113k
    src.env->CreateDir(dbname);  // In case it does not exist
108
113k
    src.env->RenameFile(InfoLogFileName(dbname), OldInfoLogFileName(dbname));
109
113k
    Status s = src.env->NewLogger(InfoLogFileName(dbname), &result.info_log);
110
113k
    if (!s.ok()) {
111
      // No place suitable for logging
112
0
      result.info_log = nullptr;
113
0
    }
114
113k
  }
115
113k
  if (result.block_cache == nullptr) {
116
113k
    result.block_cache = NewLRUCache(8 << 20);
117
113k
  }
118
113k
  return result;
119
113k
}
120
121
113k
static int TableCacheSize(const Options& sanitized_options) {
122
  // Reserve ten files or so for other uses and give the rest to TableCache.
123
113k
  return sanitized_options.max_open_files - kNumNonTableCacheFiles;
124
113k
}
125
126
DBImpl::DBImpl(const Options& raw_options, const std::string& dbname)
127
113k
    : env_(raw_options.env),
128
113k
      internal_comparator_(raw_options.comparator),
129
113k
      internal_filter_policy_(raw_options.filter_policy),
130
113k
      options_(SanitizeOptions(dbname, &internal_comparator_,
131
113k
                               &internal_filter_policy_, raw_options)),
132
113k
      owns_info_log_(options_.info_log != raw_options.info_log),
133
113k
      owns_cache_(options_.block_cache != raw_options.block_cache),
134
113k
      dbname_(dbname),
135
113k
      table_cache_(new TableCache(dbname_, options_, TableCacheSize(options_))),
136
113k
      db_lock_(nullptr),
137
113k
      shutting_down_(false),
138
113k
      background_work_finished_signal_(&mutex_),
139
113k
      mem_(nullptr),
140
113k
      imm_(nullptr),
141
113k
      has_imm_(false),
142
113k
      logfile_(nullptr),
143
113k
      logfile_number_(0),
144
113k
      log_(nullptr),
145
113k
      seed_(0),
146
113k
      tmp_batch_(new WriteBatch),
147
113k
      background_compaction_scheduled_(false),
148
113k
      manual_compaction_(nullptr),
149
113k
      versions_(new VersionSet(dbname_, &options_, table_cache_,
150
113k
                               &internal_comparator_)) {}
151
152
113k
DBImpl::~DBImpl() {
153
  // Wait for background work to finish.
154
113k
  mutex_.Lock();
155
113k
  shutting_down_.store(true, std::memory_order_release);
156
143k
  while (background_compaction_scheduled_) {
157
30.8k
    background_work_finished_signal_.Wait();
158
30.8k
  }
159
113k
  mutex_.Unlock();
160
161
113k
  if (db_lock_ != nullptr) {
162
113k
    env_->UnlockFile(db_lock_);
163
113k
  }
164
165
113k
  delete versions_;
166
113k
  if (mem_ != nullptr) mem_->Unref();
167
113k
  if (imm_ != nullptr) imm_->Unref();
168
113k
  delete tmp_batch_;
169
113k
  delete log_;
170
113k
  delete logfile_;
171
113k
  delete table_cache_;
172
173
113k
  if (owns_info_log_) {
174
113k
    delete options_.info_log;
175
113k
  }
176
113k
  if (owns_cache_) {
177
113k
    delete options_.block_cache;
178
113k
  }
179
113k
}
180
181
5.01k
Status DBImpl::NewDB() {
182
5.01k
  VersionEdit new_db;
183
5.01k
  new_db.SetComparatorName(user_comparator()->Name());
184
5.01k
  new_db.SetLogNumber(0);
185
5.01k
  new_db.SetNextFile(2);
186
5.01k
  new_db.SetLastSequence(0);
187
188
5.01k
  const std::string manifest = DescriptorFileName(dbname_, 1);
189
5.01k
  WritableFile* file;
190
5.01k
  Status s = env_->NewWritableFile(manifest, &file);
191
5.01k
  if (!s.ok()) {
192
0
    return s;
193
0
  }
194
5.01k
  {
195
5.01k
    log::Writer log(file);
196
5.01k
    std::string record;
197
5.01k
    new_db.EncodeTo(&record);
198
5.01k
    s = log.AddRecord(record);
199
5.01k
    if (s.ok()) {
200
5.01k
      s = file->Sync();
201
5.01k
    }
202
5.01k
    if (s.ok()) {
203
5.01k
      s = file->Close();
204
5.01k
    }
205
5.01k
  }
206
5.01k
  delete file;
207
5.01k
  if (s.ok()) {
208
    // Make "CURRENT" file that points to the new manifest file.
209
5.01k
    s = SetCurrentFile(env_, dbname_, 1);
210
5.01k
  } else {
211
0
    env_->RemoveFile(manifest);
212
0
  }
213
5.01k
  return s;
214
5.01k
}
215
216
1.41M
void DBImpl::MaybeIgnoreError(Status* s) const {
217
1.41M
  if (s->ok() || options_.paranoid_checks) {
218
    // No change needed
219
1.41M
  } else {
220
0
    Log(options_.info_log, "Ignoring error %s", s->ToString().c_str());
221
0
    *s = Status::OK();
222
0
  }
223
1.41M
}
224
225
171k
void DBImpl::RemoveObsoleteFiles() {
226
171k
  mutex_.AssertHeld();
227
228
171k
  if (!bg_error_.ok()) {
229
    // After a background error, we don't know whether a new version may
230
    // or may not have been committed, so we cannot safely garbage collect.
231
6.67k
    return;
232
6.67k
  }
233
234
  // Make a set of all of the live files
235
165k
  std::set<uint64_t> live = pending_outputs_;
236
165k
  versions_->AddLiveFiles(&live);
237
238
165k
  std::vector<std::string> filenames;
239
165k
  env_->GetChildren(dbname_, &filenames);  // Ignoring errors on purpose
240
165k
  uint64_t number;
241
165k
  FileType type;
242
165k
  std::vector<std::string> files_to_delete;
243
2.72M
  for (std::string& filename : filenames) {
244
2.72M
    if (ParseFileName(filename, &number, &type)) {
245
2.39M
      bool keep = true;
246
2.39M
      switch (type) {
247
304k
        case kLogFile:
248
304k
          keep = ((number >= versions_->LogNumber()) ||
249
139k
                  (number == versions_->PrevLogNumber()));
250
304k
          break;
251
278k
        case kDescriptorFile:
252
          // Keep my manifest file, and any newer incarnations'
253
          // (in case there is a race that allows other incarnations)
254
278k
          keep = (number >= versions_->ManifestFileNumber());
255
278k
          break;
256
1.16M
        case kTableFile:
257
1.16M
          keep = (live.find(number) != live.end());
258
1.16M
          break;
259
0
        case kTempFile:
260
          // Any temp files that are currently being written to must
261
          // be recorded in pending_outputs_, which is inserted into "live"
262
0
          keep = (live.find(number) != live.end());
263
0
          break;
264
165k
        case kCurrentFile:
265
330k
        case kDBLockFile:
266
651k
        case kInfoLogFile:
267
651k
          keep = true;
268
651k
          break;
269
2.39M
      }
270
271
2.39M
      if (!keep) {
272
319k
        files_to_delete.push_back(std::move(filename));
273
319k
        if (type == kTableFile) {
274
66.5k
          table_cache_->Evict(number);
275
66.5k
        }
276
319k
        Log(options_.info_log, "Delete type=%d #%lld\n", static_cast<int>(type),
277
319k
            static_cast<unsigned long long>(number));
278
319k
      }
279
2.39M
    }
280
2.72M
  }
281
282
  // While deleting all files unblock other threads. All files being deleted
283
  // have unique names which will not collide with newly created files and
284
  // are therefore safe to delete while allowing other threads to proceed.
285
165k
  mutex_.Unlock();
286
319k
  for (const std::string& filename : files_to_delete) {
287
319k
    env_->RemoveFile(dbname_ + "/" + filename);
288
319k
  }
289
165k
  mutex_.Lock();
290
165k
}
291
292
113k
Status DBImpl::Recover(VersionEdit* edit, bool* save_manifest) {
293
113k
  mutex_.AssertHeld();
294
295
  // Ignore error from CreateDir since the creation of the DB is
296
  // committed only when the descriptor is created, and this directory
297
  // may already exist from a previous failed creation attempt.
298
113k
  env_->CreateDir(dbname_);
299
113k
  assert(db_lock_ == nullptr);
300
113k
  Status s = env_->LockFile(LockFileName(dbname_), &db_lock_);
301
113k
  if (!s.ok()) {
302
0
    return s;
303
0
  }
304
305
113k
  if (!env_->FileExists(CurrentFileName(dbname_))) {
306
5.01k
    if (options_.create_if_missing) {
307
5.01k
      Log(options_.info_log, "Creating DB %s since it was missing.",
308
5.01k
          dbname_.c_str());
309
5.01k
      s = NewDB();
310
5.01k
      if (!s.ok()) {
311
0
        return s;
312
0
      }
313
5.01k
    } else {
314
0
      return Status::InvalidArgument(
315
0
          dbname_, "does not exist (create_if_missing is false)");
316
0
    }
317
108k
  } else {
318
108k
    if (options_.error_if_exists) {
319
0
      return Status::InvalidArgument(dbname_,
320
0
                                     "exists (error_if_exists is true)");
321
0
    }
322
108k
  }
323
324
113k
  s = versions_->Recover(save_manifest);
325
113k
  if (!s.ok()) {
326
0
    return s;
327
0
  }
328
113k
  SequenceNumber max_sequence(0);
329
330
  // Recover from all newer log files than the ones named in the
331
  // descriptor (new log files may have been added by the previous
332
  // incarnation without registering them in the descriptor).
333
  //
334
  // Note that PrevLogNumber() is no longer used, but we pay
335
  // attention to it in case we are recovering a database
336
  // produced by an older version of leveldb.
337
113k
  const uint64_t min_log = versions_->LogNumber();
338
113k
  const uint64_t prev_log = versions_->PrevLogNumber();
339
113k
  std::vector<std::string> filenames;
340
113k
  s = env_->GetChildren(dbname_, &filenames);
341
113k
  if (!s.ok()) {
342
0
    return s;
343
0
  }
344
113k
  std::set<uint64_t> expected;
345
113k
  versions_->AddLiveFiles(&expected);
346
113k
  uint64_t number;
347
113k
  FileType type;
348
113k
  std::vector<uint64_t> logs;
349
1.79M
  for (size_t i = 0; i < filenames.size(); i++) {
350
1.67M
    if (ParseFileName(filenames[i], &number, &type)) {
351
1.45M
      expected.erase(number);
352
1.45M
      if (type == kLogFile && ((number >= min_log) || (number == prev_log)))
353
108k
        logs.push_back(number);
354
1.45M
    }
355
1.67M
  }
356
113k
  if (!expected.empty()) {
357
0
    char buf[50];
358
0
    std::snprintf(buf, sizeof(buf), "%d missing files; e.g.",
359
0
                  static_cast<int>(expected.size()));
360
0
    return Status::Corruption(buf, TableFileName(dbname_, *(expected.begin())));
361
0
  }
362
363
  // Recover in the order in which the logs were generated
364
113k
  std::sort(logs.begin(), logs.end());
365
221k
  for (size_t i = 0; i < logs.size(); i++) {
366
108k
    s = RecoverLogFile(logs[i], (i == logs.size() - 1), save_manifest, edit,
367
108k
                       &max_sequence);
368
108k
    if (!s.ok()) {
369
0
      return s;
370
0
    }
371
372
    // The previous incarnation may not have written any MANIFEST
373
    // records after allocating this log number.  So we manually
374
    // update the file number allocation counter in VersionSet.
375
108k
    versions_->MarkFileNumberUsed(logs[i]);
376
108k
  }
377
378
113k
  if (versions_->LastSequence() < max_sequence) {
379
34.9k
    versions_->SetLastSequence(max_sequence);
380
34.9k
  }
381
382
113k
  return Status::OK();
383
113k
}
384
385
Status DBImpl::RecoverLogFile(uint64_t log_number, bool last_log,
386
                              bool* save_manifest, VersionEdit* edit,
387
108k
                              SequenceNumber* max_sequence) {
388
108k
  struct LogReporter : public log::Reader::Reporter {
389
108k
    Env* env;
390
108k
    Logger* info_log;
391
108k
    const char* fname;
392
108k
    Status* status;  // null if options_.paranoid_checks==false
393
108k
    void Corruption(size_t bytes, const Status& s) override {
394
0
      Log(info_log, "%s%s: dropping %d bytes; %s",
395
0
          (this->status == nullptr ? "(ignoring error) " : ""), fname,
396
0
          static_cast<int>(bytes), s.ToString().c_str());
397
0
      if (this->status != nullptr && this->status->ok()) *this->status = s;
398
0
    }
399
108k
  };
400
401
108k
  mutex_.AssertHeld();
402
403
  // Open the log file
404
108k
  std::string fname = LogFileName(dbname_, log_number);
405
108k
  SequentialFile* file;
406
108k
  Status status = env_->NewSequentialFile(fname, &file);
407
108k
  if (!status.ok()) {
408
0
    MaybeIgnoreError(&status);
409
0
    return status;
410
0
  }
411
412
  // Create the log reader.
413
108k
  LogReporter reporter;
414
108k
  reporter.env = env_;
415
108k
  reporter.info_log = options_.info_log;
416
108k
  reporter.fname = fname.c_str();
417
108k
  reporter.status = (options_.paranoid_checks ? &status : nullptr);
418
  // We intentionally make log::Reader do checksumming even if
419
  // paranoid_checks==false so that corruptions cause entire commits
420
  // to be skipped instead of propagating bad information (like overly
421
  // large sequence numbers).
422
108k
  log::Reader reader(file, &reporter, true /*checksum*/, 0 /*initial_offset*/);
423
108k
  Log(options_.info_log, "Recovering log #%llu",
424
108k
      (unsigned long long)log_number);
425
426
  // Read all the records and add to a memtable
427
108k
  std::string scratch;
428
108k
  Slice record;
429
108k
  WriteBatch batch;
430
108k
  int compactions = 0;
431
108k
  MemTable* mem = nullptr;
432
1.52M
  while (reader.ReadRecord(&record, &scratch) && status.ok()) {
433
1.41M
    if (record.size() < 12) {
434
0
      reporter.Corruption(record.size(),
435
0
                          Status::Corruption("log record too small"));
436
0
      continue;
437
0
    }
438
1.41M
    WriteBatchInternal::SetContents(&batch, record);
439
440
1.41M
    if (mem == nullptr) {
441
41.6k
      mem = new MemTable(internal_comparator_);
442
41.6k
      mem->Ref();
443
41.6k
    }
444
1.41M
    status = WriteBatchInternal::InsertInto(&batch, mem);
445
1.41M
    MaybeIgnoreError(&status);
446
1.41M
    if (!status.ok()) {
447
0
      break;
448
0
    }
449
1.41M
    const SequenceNumber last_seq = WriteBatchInternal::Sequence(&batch) +
450
1.41M
                                    WriteBatchInternal::Count(&batch) - 1;
451
1.41M
    if (last_seq > *max_sequence) {
452
1.41M
      *max_sequence = last_seq;
453
1.41M
    }
454
455
1.41M
    if (mem->ApproximateMemoryUsage() > options_.write_buffer_size) {
456
0
      compactions++;
457
0
      *save_manifest = true;
458
0
      status = WriteLevel0Table(mem, edit, nullptr);
459
0
      mem->Unref();
460
0
      mem = nullptr;
461
0
      if (!status.ok()) {
462
        // Reflect errors immediately so that conditions like full
463
        // file-systems cause the DB::Open() to fail.
464
0
        break;
465
0
      }
466
0
    }
467
1.41M
  }
468
469
108k
  delete file;
470
471
  // See if we should keep reusing the last log file.
472
108k
  if (status.ok() && options_.reuse_logs && last_log && compactions == 0) {
473
0
    assert(logfile_ == nullptr);
474
0
    assert(log_ == nullptr);
475
0
    assert(mem_ == nullptr);
476
0
    uint64_t lfile_size;
477
0
    if (env_->GetFileSize(fname, &lfile_size).ok() &&
478
0
        env_->NewAppendableFile(fname, &logfile_).ok()) {
479
0
      Log(options_.info_log, "Reusing old log %s \n", fname.c_str());
480
0
      log_ = new log::Writer(logfile_, lfile_size);
481
0
      logfile_number_ = log_number;
482
0
      if (mem != nullptr) {
483
0
        mem_ = mem;
484
0
        mem = nullptr;
485
0
      } else {
486
        // mem can be nullptr if lognum exists but was empty.
487
0
        mem_ = new MemTable(internal_comparator_);
488
0
        mem_->Ref();
489
0
      }
490
0
    }
491
0
  }
492
493
108k
  if (mem != nullptr) {
494
    // mem did not get reused; compact it.
495
41.6k
    if (status.ok()) {
496
41.6k
      *save_manifest = true;
497
41.6k
      status = WriteLevel0Table(mem, edit, nullptr);
498
41.6k
    }
499
41.6k
    mem->Unref();
500
41.6k
  }
501
502
108k
  return status;
503
108k
}
504
505
Status DBImpl::WriteLevel0Table(MemTable* mem, VersionEdit* edit,
506
73.3k
                                Version* base) {
507
73.3k
  mutex_.AssertHeld();
508
73.3k
  const uint64_t start_micros = env_->NowMicros();
509
73.3k
  FileMetaData meta;
510
73.3k
  meta.number = versions_->NewFileNumber();
511
73.3k
  pending_outputs_.insert(meta.number);
512
73.3k
  Iterator* iter = mem->NewIterator();
513
73.3k
  Log(options_.info_log, "Level-0 table #%llu: started",
514
73.3k
      (unsigned long long)meta.number);
515
516
73.3k
  Status s;
517
73.3k
  {
518
73.3k
    mutex_.Unlock();
519
73.3k
    s = BuildTable(dbname_, env_, options_, table_cache_, iter, &meta);
520
73.3k
    mutex_.Lock();
521
73.3k
  }
522
523
73.3k
  Log(options_.info_log, "Level-0 table #%llu: %lld bytes %s",
524
73.3k
      (unsigned long long)meta.number, (unsigned long long)meta.file_size,
525
73.3k
      s.ToString().c_str());
526
73.3k
  delete iter;
527
73.3k
  pending_outputs_.erase(meta.number);
528
529
  // Note that if file_size is zero, the file has been deleted and
530
  // should not be added to the manifest.
531
73.3k
  int level = 0;
532
73.3k
  if (s.ok() && meta.file_size > 0) {
533
56.5k
    const Slice min_user_key = meta.smallest.user_key();
534
56.5k
    const Slice max_user_key = meta.largest.user_key();
535
56.5k
    if (base != nullptr) {
536
14.8k
      level = base->PickLevelForMemTableOutput(min_user_key, max_user_key);
537
14.8k
    }
538
56.5k
    edit->AddFile(level, meta.number, meta.file_size, meta.smallest,
539
56.5k
                  meta.largest);
540
56.5k
  }
541
542
73.3k
  CompactionStats stats;
543
73.3k
  stats.micros = env_->NowMicros() - start_micros;
544
73.3k
  stats.bytes_written = meta.file_size;
545
73.3k
  stats_[level].Add(stats);
546
73.3k
  return s;
547
73.3k
}
548
549
31.6k
void DBImpl::CompactMemTable() {
550
31.6k
  mutex_.AssertHeld();
551
31.6k
  assert(imm_ != nullptr);
552
553
  // Save the contents of the memtable as a new Table
554
31.6k
  VersionEdit edit;
555
31.6k
  Version* base = versions_->current();
556
31.6k
  base->Ref();
557
31.6k
  Status s = WriteLevel0Table(imm_, &edit, base);
558
31.6k
  base->Unref();
559
560
31.6k
  if (s.ok() && shutting_down_.load(std::memory_order_acquire)) {
561
0
    s = Status::IOError("Deleting DB during memtable compaction");
562
0
  }
563
564
  // Replace immutable memtable with the generated Table
565
31.6k
  if (s.ok()) {
566
31.6k
    edit.SetPrevLogNumber(0);
567
31.6k
    edit.SetLogNumber(logfile_number_);  // Earlier logs no longer needed
568
31.6k
    s = versions_->LogAndApply(&edit, &mutex_);
569
31.6k
  }
570
571
31.6k
  if (s.ok()) {
572
    // Commit to the new state
573
31.6k
    imm_->Unref();
574
31.6k
    imm_ = nullptr;
575
31.6k
    has_imm_.store(false, std::memory_order_release);
576
31.6k
    RemoveObsoleteFiles();
577
31.6k
  } else {
578
0
    RecordBackgroundError(s);
579
0
  }
580
31.6k
}
581
582
31.6k
void DBImpl::CompactRange(const Slice* begin, const Slice* end) {
583
31.6k
  int max_level_with_files = 1;
584
31.6k
  {
585
31.6k
    MutexLock l(&mutex_);
586
31.6k
    Version* base = versions_->current();
587
221k
    for (int level = 1; level < config::kNumLevels; level++) {
588
189k
      if (base->OverlapInLevel(level, begin, end)) {
589
18.8k
        max_level_with_files = level;
590
18.8k
      }
591
189k
    }
592
31.6k
  }
593
31.6k
  TEST_CompactMemTable();  // TODO(sanjay): Skip if memtable does not overlap
594
75.2k
  for (int level = 0; level < max_level_with_files; level++) {
595
43.5k
    TEST_CompactRange(level, begin, end);
596
43.5k
  }
597
31.6k
}
598
599
void DBImpl::TEST_CompactRange(int level, const Slice* begin,
600
43.5k
                               const Slice* end) {
601
43.5k
  assert(level >= 0);
602
43.5k
  assert(level + 1 < config::kNumLevels);
603
604
43.5k
  InternalKey begin_storage, end_storage;
605
606
43.5k
  ManualCompaction manual;
607
43.5k
  manual.level = level;
608
43.5k
  manual.done = false;
609
43.5k
  if (begin == nullptr) {
610
0
    manual.begin = nullptr;
611
43.5k
  } else {
612
43.5k
    begin_storage = InternalKey(*begin, kMaxSequenceNumber, kValueTypeForSeek);
613
43.5k
    manual.begin = &begin_storage;
614
43.5k
  }
615
43.5k
  if (end == nullptr) {
616
0
    manual.end = nullptr;
617
43.5k
  } else {
618
43.5k
    end_storage = InternalKey(*end, 0, static_cast<ValueType>(0));
619
43.5k
    manual.end = &end_storage;
620
43.5k
  }
621
622
43.5k
  MutexLock l(&mutex_);
623
160k
  while (!manual.done && !shutting_down_.load(std::memory_order_acquire) &&
624
117k
         bg_error_.ok()) {
625
117k
    if (manual_compaction_ == nullptr) {  // Idle
626
58.3k
      manual_compaction_ = &manual;
627
58.3k
      MaybeScheduleCompaction();
628
59.0k
    } else {  // Running either my compaction or another compaction.
629
59.0k
      background_work_finished_signal_.Wait();
630
59.0k
    }
631
117k
  }
632
  // Finish current background compaction in the case where
633
  // `background_work_finished_signal_` was signalled due to an error.
634
43.7k
  while (background_compaction_scheduled_) {
635
183
    background_work_finished_signal_.Wait();
636
183
  }
637
43.5k
  if (manual_compaction_ == &manual) {
638
    // Cancel my manual compaction since we aborted early for some reason.
639
0
    manual_compaction_ = nullptr;
640
0
  }
641
43.5k
}
642
643
31.6k
Status DBImpl::TEST_CompactMemTable() {
644
  // nullptr batch means just wait for earlier writes to be done
645
31.6k
  Status s = Write(WriteOptions(), nullptr);
646
31.6k
  if (s.ok()) {
647
    // Wait until the compaction completes
648
31.6k
    MutexLock l(&mutex_);
649
63.4k
    while (imm_ != nullptr && bg_error_.ok()) {
650
31.8k
      background_work_finished_signal_.Wait();
651
31.8k
    }
652
31.6k
    if (imm_ != nullptr) {
653
0
      s = bg_error_;
654
0
    }
655
31.6k
  }
656
31.6k
  return s;
657
31.6k
}
658
659
13.3k
void DBImpl::RecordBackgroundError(const Status& s) {
660
13.3k
  mutex_.AssertHeld();
661
13.3k
  if (bg_error_.ok()) {
662
6.67k
    bg_error_ = s;
663
6.67k
    background_work_finished_signal_.SignalAll();
664
6.67k
  }
665
13.3k
}
666
667
326k
void DBImpl::MaybeScheduleCompaction() {
668
326k
  mutex_.AssertHeld();
669
326k
  if (background_compaction_scheduled_) {
670
    // Already scheduled
671
323k
  } else if (shutting_down_.load(std::memory_order_acquire)) {
672
    // DB is being deleted; no more background compactions
673
292k
  } else if (!bg_error_.ok()) {
674
    // Already got an error; no more changes
675
292k
  } else if (imm_ == nullptr && manual_compaction_ == nullptr &&
676
203k
             !versions_->NeedsCompaction()) {
677
    // No work to be done
678
169k
  } else {
679
123k
    background_compaction_scheduled_ = true;
680
123k
    env_->Schedule(&DBImpl::BGWork, this);
681
123k
  }
682
326k
}
683
684
123k
void DBImpl::BGWork(void* db) {
685
123k
  reinterpret_cast<DBImpl*>(db)->BackgroundCall();
686
123k
}
687
688
123k
void DBImpl::BackgroundCall() {
689
123k
  MutexLock l(&mutex_);
690
123k
  assert(background_compaction_scheduled_);
691
123k
  if (shutting_down_.load(std::memory_order_acquire)) {
692
    // No more background work when shutting down.
693
110k
  } else if (!bg_error_.ok()) {
694
    // No more background work after a background error.
695
110k
  } else {
696
110k
    BackgroundCompaction();
697
110k
  }
698
699
123k
  background_compaction_scheduled_ = false;
700
701
  // Previous compaction may have produced too many files in a level,
702
  // so reschedule another compaction if needed.
703
123k
  MaybeScheduleCompaction();
704
123k
  background_work_finished_signal_.SignalAll();
705
123k
}
706
707
110k
void DBImpl::BackgroundCompaction() {
708
110k
  mutex_.AssertHeld();
709
710
110k
  if (imm_ != nullptr) {
711
31.5k
    CompactMemTable();
712
31.5k
    return;
713
31.5k
  }
714
715
78.5k
  Compaction* c;
716
78.5k
  bool is_manual = (manual_compaction_ != nullptr);
717
78.5k
  InternalKey manual_end;
718
78.5k
  if (is_manual) {
719
58.3k
    ManualCompaction* m = manual_compaction_;
720
58.3k
    c = versions_->CompactRange(m->level, m->begin, m->end);
721
58.3k
    m->done = (c == nullptr);
722
58.3k
    if (c != nullptr) {
723
14.8k
      manual_end = c->input(0, c->num_input_files(0) - 1)->largest;
724
14.8k
    }
725
58.3k
    Log(options_.info_log,
726
58.3k
        "Manual compaction at level-%d from %s .. %s; will stop at %s\n",
727
58.3k
        m->level, (m->begin ? m->begin->DebugString().c_str() : "(begin)"),
728
58.3k
        (m->end ? m->end->DebugString().c_str() : "(end)"),
729
58.3k
        (m->done ? "(end)" : manual_end.DebugString().c_str()));
730
58.3k
  } else {
731
20.1k
    c = versions_->PickCompaction();
732
20.1k
  }
733
734
78.5k
  Status status;
735
78.5k
  if (c == nullptr) {
736
    // Nothing to do
737
43.5k
  } else if (!is_manual && c->IsTrivialMove()) {
738
    // Move file to next level
739
7.96k
    assert(c->num_input_files(0) == 1);
740
7.96k
    FileMetaData* f = c->input(0, 0);
741
7.96k
    c->edit()->RemoveFile(c->level(), f->number);
742
7.96k
    c->edit()->AddFile(c->level() + 1, f->number, f->file_size, f->smallest,
743
7.96k
                       f->largest);
744
7.96k
    status = versions_->LogAndApply(c->edit(), &mutex_);
745
7.96k
    if (!status.ok()) {
746
0
      RecordBackgroundError(status);
747
0
    }
748
7.96k
    VersionSet::LevelSummaryStorage tmp;
749
7.96k
    Log(options_.info_log, "Moved #%lld to level-%d %lld bytes %s: %s\n",
750
7.96k
        static_cast<unsigned long long>(f->number), c->level() + 1,
751
7.96k
        static_cast<unsigned long long>(f->file_size),
752
7.96k
        status.ToString().c_str(), versions_->LevelSummary(&tmp));
753
26.9k
  } else {
754
26.9k
    CompactionState* compact = new CompactionState(c);
755
26.9k
    status = DoCompactionWork(compact);
756
26.9k
    if (!status.ok()) {
757
6.67k
      RecordBackgroundError(status);
758
6.67k
    }
759
26.9k
    CleanupCompaction(compact);
760
26.9k
    c->ReleaseInputs();
761
26.9k
    RemoveObsoleteFiles();
762
26.9k
  }
763
78.5k
  delete c;
764
765
78.5k
  if (status.ok()) {
766
    // Done
767
71.8k
  } else if (shutting_down_.load(std::memory_order_acquire)) {
768
    // Ignore compaction errors found during shutting down
769
6.67k
  } else {
770
0
    Log(options_.info_log, "Compaction error: %s", status.ToString().c_str());
771
0
  }
772
773
78.5k
  if (is_manual) {
774
58.3k
    ManualCompaction* m = manual_compaction_;
775
58.3k
    if (!status.ok()) {
776
0
      m->done = true;
777
0
    }
778
58.3k
    if (!m->done) {
779
      // We only compacted part of the requested range.  Update *m
780
      // to the range that is left to be compacted.
781
14.8k
      m->tmp_storage = manual_end;
782
14.8k
      m->begin = &m->tmp_storage;
783
14.8k
    }
784
58.3k
    manual_compaction_ = nullptr;
785
58.3k
  }
786
78.5k
}
787
788
26.9k
void DBImpl::CleanupCompaction(CompactionState* compact) {
789
26.9k
  mutex_.AssertHeld();
790
26.9k
  if (compact->builder != nullptr) {
791
    // May happen if we get a shutdown call in the middle of compaction
792
5.98k
    compact->builder->Abandon();
793
5.98k
    delete compact->builder;
794
20.9k
  } else {
795
20.9k
    assert(compact->outfile == nullptr);
796
20.9k
  }
797
26.9k
  delete compact->outfile;
798
48.7k
  for (size_t i = 0; i < compact->outputs.size(); i++) {
799
21.7k
    const CompactionState::Output& out = compact->outputs[i];
800
21.7k
    pending_outputs_.erase(out.number);
801
21.7k
  }
802
26.9k
  delete compact;
803
26.9k
}
804
805
21.7k
Status DBImpl::OpenCompactionOutputFile(CompactionState* compact) {
806
21.7k
  assert(compact != nullptr);
807
21.7k
  assert(compact->builder == nullptr);
808
21.7k
  uint64_t file_number;
809
21.7k
  {
810
21.7k
    mutex_.Lock();
811
21.7k
    file_number = versions_->NewFileNumber();
812
21.7k
    pending_outputs_.insert(file_number);
813
21.7k
    CompactionState::Output out;
814
21.7k
    out.number = file_number;
815
21.7k
    out.smallest.Clear();
816
21.7k
    out.largest.Clear();
817
21.7k
    compact->outputs.push_back(out);
818
21.7k
    mutex_.Unlock();
819
21.7k
  }
820
821
  // Make the output file
822
21.7k
  std::string fname = TableFileName(dbname_, file_number);
823
21.7k
  Status s = env_->NewWritableFile(fname, &compact->outfile);
824
21.7k
  if (s.ok()) {
825
21.7k
    compact->builder = new TableBuilder(options_, compact->outfile);
826
21.7k
  }
827
21.7k
  return s;
828
21.7k
}
829
830
Status DBImpl::FinishCompactionOutputFile(CompactionState* compact,
831
15.7k
                                          Iterator* input) {
832
15.7k
  assert(compact != nullptr);
833
15.7k
  assert(compact->outfile != nullptr);
834
15.7k
  assert(compact->builder != nullptr);
835
836
15.7k
  const uint64_t output_number = compact->current_output()->number;
837
15.7k
  assert(output_number != 0);
838
839
  // Check for iterator errors
840
15.7k
  Status s = input->status();
841
15.7k
  const uint64_t current_entries = compact->builder->NumEntries();
842
15.7k
  if (s.ok()) {
843
15.7k
    s = compact->builder->Finish();
844
15.7k
  } else {
845
0
    compact->builder->Abandon();
846
0
  }
847
15.7k
  const uint64_t current_bytes = compact->builder->FileSize();
848
15.7k
  compact->current_output()->file_size = current_bytes;
849
15.7k
  compact->total_bytes += current_bytes;
850
15.7k
  delete compact->builder;
851
15.7k
  compact->builder = nullptr;
852
853
  // Finish and check for file errors
854
15.7k
  if (s.ok()) {
855
15.7k
    s = compact->outfile->Sync();
856
15.7k
  }
857
15.7k
  if (s.ok()) {
858
15.7k
    s = compact->outfile->Close();
859
15.7k
  }
860
15.7k
  delete compact->outfile;
861
15.7k
  compact->outfile = nullptr;
862
863
15.7k
  if (s.ok() && current_entries > 0) {
864
    // Verify that the table is usable
865
15.7k
    Iterator* iter =
866
15.7k
        table_cache_->NewIterator(ReadOptions(), output_number, current_bytes);
867
15.7k
    s = iter->status();
868
15.7k
    delete iter;
869
15.7k
    if (s.ok()) {
870
15.7k
      Log(options_.info_log, "Generated table #%llu@%d: %lld keys, %lld bytes",
871
15.7k
          (unsigned long long)output_number, compact->compaction->level(),
872
15.7k
          (unsigned long long)current_entries,
873
15.7k
          (unsigned long long)current_bytes);
874
15.7k
    }
875
15.7k
  }
876
15.7k
  return s;
877
15.7k
}
878
879
20.3k
Status DBImpl::InstallCompactionResults(CompactionState* compact) {
880
20.3k
  mutex_.AssertHeld();
881
20.3k
  Log(options_.info_log, "Compacted %d@%d + %d@%d files => %lld bytes",
882
20.3k
      compact->compaction->num_input_files(0), compact->compaction->level(),
883
20.3k
      compact->compaction->num_input_files(1), compact->compaction->level() + 1,
884
20.3k
      static_cast<long long>(compact->total_bytes));
885
886
  // Add compaction outputs
887
20.3k
  compact->compaction->AddInputDeletions(compact->compaction->edit());
888
20.3k
  const int level = compact->compaction->level();
889
36.0k
  for (size_t i = 0; i < compact->outputs.size(); i++) {
890
15.7k
    const CompactionState::Output& out = compact->outputs[i];
891
15.7k
    compact->compaction->edit()->AddFile(level + 1, out.number, out.file_size,
892
15.7k
                                         out.smallest, out.largest);
893
15.7k
  }
894
20.3k
  return versions_->LogAndApply(compact->compaction->edit(), &mutex_);
895
20.3k
}
896
897
26.9k
Status DBImpl::DoCompactionWork(CompactionState* compact) {
898
26.9k
  const uint64_t start_micros = env_->NowMicros();
899
26.9k
  int64_t imm_micros = 0;  // Micros spent doing imm_ compactions
900
901
26.9k
  Log(options_.info_log, "Compacting %d@%d + %d@%d files",
902
26.9k
      compact->compaction->num_input_files(0), compact->compaction->level(),
903
26.9k
      compact->compaction->num_input_files(1),
904
26.9k
      compact->compaction->level() + 1);
905
906
26.9k
  assert(versions_->NumLevelFiles(compact->compaction->level()) > 0);
907
26.9k
  assert(compact->builder == nullptr);
908
26.9k
  assert(compact->outfile == nullptr);
909
26.9k
  if (snapshots_.empty()) {
910
26.9k
    compact->smallest_snapshot = versions_->LastSequence();
911
26.9k
  } else {
912
54
    compact->smallest_snapshot = snapshots_.oldest()->sequence_number();
913
54
  }
914
915
26.9k
  Iterator* input = versions_->MakeInputIterator(compact->compaction);
916
917
  // Release mutex while we're actually doing the compaction work
918
26.9k
  mutex_.Unlock();
919
920
26.9k
  input->SeekToFirst();
921
26.9k
  Status status;
922
26.9k
  ParsedInternalKey ikey;
923
26.9k
  std::string current_user_key;
924
26.9k
  bool has_current_user_key = false;
925
26.9k
  SequenceNumber last_sequence_for_key = kMaxSequenceNumber;
926
1.28M
  while (input->Valid() && !shutting_down_.load(std::memory_order_acquire)) {
927
    // Prioritize immutable compaction work
928
1.25M
    if (has_imm_.load(std::memory_order_relaxed)) {
929
58
      const uint64_t imm_start = env_->NowMicros();
930
58
      mutex_.Lock();
931
58
      if (imm_ != nullptr) {
932
58
        CompactMemTable();
933
        // Wake up MakeRoomForWrite() if necessary.
934
58
        background_work_finished_signal_.SignalAll();
935
58
      }
936
58
      mutex_.Unlock();
937
58
      imm_micros += (env_->NowMicros() - imm_start);
938
58
    }
939
940
1.25M
    Slice key = input->key();
941
1.25M
    if (compact->compaction->ShouldStopBefore(key) &&
942
0
        compact->builder != nullptr) {
943
0
      status = FinishCompactionOutputFile(compact, input);
944
0
      if (!status.ok()) {
945
0
        break;
946
0
      }
947
0
    }
948
949
    // Handle key/value, add to state, etc.
950
1.25M
    bool drop = false;
951
1.25M
    if (!ParseInternalKey(key, &ikey)) {
952
      // Do not hide error keys
953
0
      current_user_key.clear();
954
0
      has_current_user_key = false;
955
0
      last_sequence_for_key = kMaxSequenceNumber;
956
1.25M
    } else {
957
1.25M
      if (!has_current_user_key ||
958
1.22M
          user_comparator()->Compare(ikey.user_key, Slice(current_user_key)) !=
959
1.22M
              0) {
960
        // First occurrence of this user key
961
268k
        current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
962
268k
        has_current_user_key = true;
963
268k
        last_sequence_for_key = kMaxSequenceNumber;
964
268k
      }
965
966
1.25M
      if (last_sequence_for_key <= compact->smallest_snapshot) {
967
        // Hidden by an newer entry for same user key
968
987k
        drop = true;  // (A)
969
987k
      } else if (ikey.type == kTypeDeletion &&
970
46.2k
                 ikey.sequence <= compact->smallest_snapshot &&
971
46.2k
                 compact->compaction->IsBaseLevelForKey(ikey.user_key)) {
972
        // For this user key:
973
        // (1) there is no data in higher levels
974
        // (2) data in lower levels will have larger sequence numbers
975
        // (3) data in layers that are being compacted here and have
976
        //     smaller sequence numbers will be dropped in the next
977
        //     few iterations of this loop (by rule (A) above).
978
        // Therefore this deletion marker is obsolete and can be dropped.
979
28.0k
        drop = true;
980
28.0k
      }
981
982
1.25M
      last_sequence_for_key = ikey.sequence;
983
1.25M
    }
984
#if 0
985
    Log(options_.info_log,
986
        "  Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
987
        "%d smallest_snapshot: %d",
988
        ikey.user_key.ToString().c_str(),
989
        (int)ikey.sequence, ikey.type, kTypeValue, drop,
990
        compact->compaction->IsBaseLevelForKey(ikey.user_key),
991
        (int)last_sequence_for_key, (int)compact->smallest_snapshot);
992
#endif
993
994
1.25M
    if (!drop) {
995
      // Open output file if necessary
996
240k
      if (compact->builder == nullptr) {
997
21.7k
        status = OpenCompactionOutputFile(compact);
998
21.7k
        if (!status.ok()) {
999
0
          break;
1000
0
        }
1001
21.7k
      }
1002
240k
      if (compact->builder->NumEntries() == 0) {
1003
21.7k
        compact->current_output()->smallest.DecodeFrom(key);
1004
21.7k
      }
1005
240k
      compact->current_output()->largest.DecodeFrom(key);
1006
240k
      compact->builder->Add(key, input->value());
1007
1008
      // Close output file if it is big enough
1009
240k
      if (compact->builder->FileSize() >=
1010
240k
          compact->compaction->MaxOutputFileSize()) {
1011
0
        status = FinishCompactionOutputFile(compact, input);
1012
0
        if (!status.ok()) {
1013
0
          break;
1014
0
        }
1015
0
      }
1016
240k
    }
1017
1018
1.25M
    input->Next();
1019
1.25M
  }
1020
1021
26.9k
  if (status.ok() && shutting_down_.load(std::memory_order_acquire)) {
1022
6.67k
    status = Status::IOError("Deleting DB during compaction");
1023
6.67k
  }
1024
26.9k
  if (status.ok() && compact->builder != nullptr) {
1025
15.7k
    status = FinishCompactionOutputFile(compact, input);
1026
15.7k
  }
1027
26.9k
  if (status.ok()) {
1028
20.3k
    status = input->status();
1029
20.3k
  }
1030
26.9k
  delete input;
1031
26.9k
  input = nullptr;
1032
1033
26.9k
  CompactionStats stats;
1034
26.9k
  stats.micros = env_->NowMicros() - start_micros - imm_micros;
1035
80.9k
  for (int which = 0; which < 2; which++) {
1036
157k
    for (int i = 0; i < compact->compaction->num_input_files(which); i++) {
1037
103k
      stats.bytes_read += compact->compaction->input(which, i)->file_size;
1038
103k
    }
1039
53.9k
  }
1040
48.7k
  for (size_t i = 0; i < compact->outputs.size(); i++) {
1041
21.7k
    stats.bytes_written += compact->outputs[i].file_size;
1042
21.7k
  }
1043
1044
26.9k
  mutex_.Lock();
1045
26.9k
  stats_[compact->compaction->level() + 1].Add(stats);
1046
1047
26.9k
  if (status.ok()) {
1048
20.3k
    status = InstallCompactionResults(compact);
1049
20.3k
  }
1050
26.9k
  if (!status.ok()) {
1051
6.67k
    RecordBackgroundError(status);
1052
6.67k
  }
1053
26.9k
  VersionSet::LevelSummaryStorage tmp;
1054
26.9k
  Log(options_.info_log, "compacted to: %s", versions_->LevelSummary(&tmp));
1055
26.9k
  return status;
1056
26.9k
}
1057
1058
namespace {
1059
1060
struct IterState {
1061
  port::Mutex* const mu;
1062
  Version* const version GUARDED_BY(mu);
1063
  MemTable* const mem GUARDED_BY(mu);
1064
  MemTable* const imm GUARDED_BY(mu);
1065
1066
  IterState(port::Mutex* mutex, MemTable* mem, MemTable* imm, Version* version)
1067
143k
      : mu(mutex), version(version), mem(mem), imm(imm) {}
1068
};
1069
1070
143k
static void CleanupIteratorState(void* arg1, void* arg2) {
1071
143k
  IterState* state = reinterpret_cast<IterState*>(arg1);
1072
143k
  state->mu->Lock();
1073
143k
  state->mem->Unref();
1074
143k
  if (state->imm != nullptr) state->imm->Unref();
1075
143k
  state->version->Unref();
1076
143k
  state->mu->Unlock();
1077
143k
  delete state;
1078
143k
}
1079
1080
}  // anonymous namespace
1081
1082
Iterator* DBImpl::NewInternalIterator(const ReadOptions& options,
1083
                                      SequenceNumber* latest_snapshot,
1084
143k
                                      uint32_t* seed) {
1085
143k
  mutex_.Lock();
1086
143k
  *latest_snapshot = versions_->LastSequence();
1087
1088
  // Collect together all needed child iterators
1089
143k
  std::vector<Iterator*> list;
1090
143k
  list.push_back(mem_->NewIterator());
1091
143k
  mem_->Ref();
1092
143k
  if (imm_ != nullptr) {
1093
0
    list.push_back(imm_->NewIterator());
1094
0
    imm_->Ref();
1095
0
  }
1096
143k
  versions_->current()->AddIterators(options, &list);
1097
143k
  Iterator* internal_iter =
1098
143k
      NewMergingIterator(&internal_comparator_, &list[0], list.size());
1099
143k
  versions_->current()->Ref();
1100
1101
143k
  IterState* cleanup = new IterState(&mutex_, mem_, imm_, versions_->current());
1102
143k
  internal_iter->RegisterCleanup(CleanupIteratorState, cleanup, nullptr);
1103
1104
143k
  *seed = ++seed_;
1105
143k
  mutex_.Unlock();
1106
143k
  return internal_iter;
1107
143k
}
1108
1109
0
Iterator* DBImpl::TEST_NewInternalIterator() {
1110
0
  SequenceNumber ignored;
1111
0
  uint32_t ignored_seed;
1112
0
  return NewInternalIterator(ReadOptions(), &ignored, &ignored_seed);
1113
0
}
1114
1115
0
int64_t DBImpl::TEST_MaxNextLevelOverlappingBytes() {
1116
0
  MutexLock l(&mutex_);
1117
0
  return versions_->MaxNextLevelOverlappingBytes();
1118
0
}
1119
1120
Status DBImpl::Get(const ReadOptions& options, const Slice& key,
1121
47.7k
                   std::string* value) {
1122
47.7k
  Status s;
1123
47.7k
  MutexLock l(&mutex_);
1124
47.7k
  SequenceNumber snapshot;
1125
47.7k
  if (options.snapshot != nullptr) {
1126
0
    snapshot =
1127
0
        static_cast<const SnapshotImpl*>(options.snapshot)->sequence_number();
1128
47.7k
  } else {
1129
47.7k
    snapshot = versions_->LastSequence();
1130
47.7k
  }
1131
1132
47.7k
  MemTable* mem = mem_;
1133
47.7k
  MemTable* imm = imm_;
1134
47.7k
  Version* current = versions_->current();
1135
47.7k
  mem->Ref();
1136
47.7k
  if (imm != nullptr) imm->Ref();
1137
47.7k
  current->Ref();
1138
1139
47.7k
  bool have_stat_update = false;
1140
47.7k
  Version::GetStats stats;
1141
1142
  // Unlock while reading from files and memtables
1143
47.7k
  {
1144
47.7k
    mutex_.Unlock();
1145
    // First look in the memtable, then in the immutable memtable (if any).
1146
47.7k
    LookupKey lkey(key, snapshot);
1147
47.7k
    if (mem->Get(lkey, value, &s)) {
1148
      // Done
1149
41.1k
    } else if (imm != nullptr && imm->Get(lkey, value, &s)) {
1150
      // Done
1151
41.1k
    } else {
1152
41.1k
      s = current->Get(options, lkey, value, &stats);
1153
41.1k
      have_stat_update = true;
1154
41.1k
    }
1155
47.7k
    mutex_.Lock();
1156
47.7k
  }
1157
1158
47.7k
  if (have_stat_update && current->UpdateStats(stats)) {
1159
45
    MaybeScheduleCompaction();
1160
45
  }
1161
47.7k
  mem->Unref();
1162
47.7k
  if (imm != nullptr) imm->Unref();
1163
47.7k
  current->Unref();
1164
47.7k
  return s;
1165
47.7k
}
1166
1167
143k
Iterator* DBImpl::NewIterator(const ReadOptions& options) {
1168
143k
  SequenceNumber latest_snapshot;
1169
143k
  uint32_t seed;
1170
143k
  Iterator* iter = NewInternalIterator(options, &latest_snapshot, &seed);
1171
143k
  return NewDBIterator(this, user_comparator(), iter,
1172
143k
                       (options.snapshot != nullptr
1173
143k
                            ? static_cast<const SnapshotImpl*>(options.snapshot)
1174
80.4k
                                  ->sequence_number()
1175
143k
                            : latest_snapshot),
1176
143k
                       seed);
1177
143k
}
1178
1179
6.76k
void DBImpl::RecordReadSample(Slice key) {
1180
6.76k
  MutexLock l(&mutex_);
1181
6.76k
  if (versions_->current()->RecordReadSample(key)) {
1182
2
    MaybeScheduleCompaction();
1183
2
  }
1184
6.76k
}
1185
1186
80.4k
const Snapshot* DBImpl::GetSnapshot() {
1187
80.4k
  MutexLock l(&mutex_);
1188
80.4k
  return snapshots_.New(versions_->LastSequence());
1189
80.4k
}
1190
1191
80.4k
void DBImpl::ReleaseSnapshot(const Snapshot* snapshot) {
1192
80.4k
  MutexLock l(&mutex_);
1193
80.4k
  snapshots_.Delete(static_cast<const SnapshotImpl*>(snapshot));
1194
80.4k
}
1195
1196
// Convenience methods
1197
46.8k
Status DBImpl::Put(const WriteOptions& o, const Slice& key, const Slice& val) {
1198
46.8k
  return DB::Put(o, key, val);
1199
46.8k
}
1200
1201
1.89M
Status DBImpl::Delete(const WriteOptions& options, const Slice& key) {
1202
1.89M
  return DB::Delete(options, key);
1203
1.89M
}
1204
1205
1.96M
Status DBImpl::Write(const WriteOptions& options, WriteBatch* updates) {
1206
1.96M
  Writer w(&mutex_);
1207
1.96M
  w.batch = updates;
1208
1.96M
  w.sync = options.sync;
1209
1.96M
  w.done = false;
1210
1211
1.96M
  MutexLock l(&mutex_);
1212
1.96M
  writers_.push_back(&w);
1213
1.96M
  while (!w.done && &w != writers_.front()) {
1214
0
    w.cv.Wait();
1215
0
  }
1216
1.96M
  if (w.done) {
1217
0
    return w.status;
1218
0
  }
1219
1220
  // May temporarily unlock and wait.
1221
1.96M
  Status status = MakeRoomForWrite(updates == nullptr);
1222
1.96M
  uint64_t last_sequence = versions_->LastSequence();
1223
1.96M
  Writer* last_writer = &w;
1224
1.96M
  if (status.ok() && updates != nullptr) {  // nullptr batch is for compactions
1225
1.93M
    WriteBatch* write_batch = BuildBatchGroup(&last_writer);
1226
1.93M
    WriteBatchInternal::SetSequence(write_batch, last_sequence + 1);
1227
1.93M
    last_sequence += WriteBatchInternal::Count(write_batch);
1228
1229
    // Add to log and apply to memtable.  We can release the lock
1230
    // during this phase since &w is currently responsible for logging
1231
    // and protects against concurrent loggers and concurrent writes
1232
    // into mem_.
1233
1.93M
    {
1234
1.93M
      mutex_.Unlock();
1235
1.93M
      status = log_->AddRecord(WriteBatchInternal::Contents(write_batch));
1236
1.93M
      bool sync_error = false;
1237
1.93M
      if (status.ok() && options.sync) {
1238
0
        status = logfile_->Sync();
1239
0
        if (!status.ok()) {
1240
0
          sync_error = true;
1241
0
        }
1242
0
      }
1243
1.93M
      if (status.ok()) {
1244
1.93M
        status = WriteBatchInternal::InsertInto(write_batch, mem_);
1245
1.93M
      }
1246
1.93M
      mutex_.Lock();
1247
1.93M
      if (sync_error) {
1248
        // The state of the log file is indeterminate: the log record we
1249
        // just added may or may not show up when the DB is re-opened.
1250
        // So we force the DB into a mode where all future writes fail.
1251
0
        RecordBackgroundError(status);
1252
0
      }
1253
1.93M
    }
1254
1.93M
    if (write_batch == tmp_batch_) tmp_batch_->Clear();
1255
1256
1.93M
    versions_->SetLastSequence(last_sequence);
1257
1.93M
  }
1258
1259
1.96M
  while (true) {
1260
1.96M
    Writer* ready = writers_.front();
1261
1.96M
    writers_.pop_front();
1262
1.96M
    if (ready != &w) {
1263
0
      ready->status = status;
1264
0
      ready->done = true;
1265
0
      ready->cv.Signal();
1266
0
    }
1267
1.96M
    if (ready == last_writer) break;
1268
1.96M
  }
1269
1270
  // Notify new head of write queue
1271
1.96M
  if (!writers_.empty()) {
1272
0
    writers_.front()->cv.Signal();
1273
0
  }
1274
1275
1.96M
  return status;
1276
1.96M
}
1277
1278
// REQUIRES: Writer list must be non-empty
1279
// REQUIRES: First writer must have a non-null batch
1280
1.93M
WriteBatch* DBImpl::BuildBatchGroup(Writer** last_writer) {
1281
1.93M
  mutex_.AssertHeld();
1282
1.93M
  assert(!writers_.empty());
1283
1.93M
  Writer* first = writers_.front();
1284
1.93M
  WriteBatch* result = first->batch;
1285
1.93M
  assert(result != nullptr);
1286
1287
1.93M
  size_t size = WriteBatchInternal::ByteSize(first->batch);
1288
1289
  // Allow the group to grow up to a maximum size, but if the
1290
  // original write is small, limit the growth so we do not slow
1291
  // down the small write too much.
1292
1.93M
  size_t max_size = 1 << 20;
1293
1.93M
  if (size <= (128 << 10)) {
1294
1.93M
    max_size = size + (128 << 10);
1295
1.93M
  }
1296
1297
1.93M
  *last_writer = first;
1298
1.93M
  std::deque<Writer*>::iterator iter = writers_.begin();
1299
1.93M
  ++iter;  // Advance past "first"
1300
1.93M
  for (; iter != writers_.end(); ++iter) {
1301
0
    Writer* w = *iter;
1302
0
    if (w->sync && !first->sync) {
1303
      // Do not include a sync write into a batch handled by a non-sync write.
1304
0
      break;
1305
0
    }
1306
1307
0
    if (w->batch != nullptr) {
1308
0
      size += WriteBatchInternal::ByteSize(w->batch);
1309
0
      if (size > max_size) {
1310
        // Do not make batch too big
1311
0
        break;
1312
0
      }
1313
1314
      // Append to *result
1315
0
      if (result == first->batch) {
1316
        // Switch to temporary batch instead of disturbing caller's batch
1317
0
        result = tmp_batch_;
1318
0
        assert(WriteBatchInternal::Count(result) == 0);
1319
0
        WriteBatchInternal::Append(result, first->batch);
1320
0
      }
1321
0
      WriteBatchInternal::Append(result, w->batch);
1322
0
    }
1323
0
    *last_writer = w;
1324
0
  }
1325
1.93M
  return result;
1326
1.93M
}
1327
1328
// REQUIRES: mutex_ is held
1329
// REQUIRES: this thread is currently at the front of the writer queue
1330
1.96M
Status DBImpl::MakeRoomForWrite(bool force) {
1331
1.96M
  mutex_.AssertHeld();
1332
1.96M
  assert(!writers_.empty());
1333
1.96M
  bool allow_delay = !force;
1334
1.96M
  Status s;
1335
2.00M
  while (true) {
1336
2.00M
    if (!bg_error_.ok()) {
1337
      // Yield previous error
1338
0
      s = bg_error_;
1339
0
      break;
1340
2.00M
    } else if (allow_delay && versions_->NumLevelFiles(0) >=
1341
1.93M
                                  config::kL0_SlowdownWritesTrigger) {
1342
      // We are getting close to hitting a hard limit on the number of
1343
      // L0 files.  Rather than delaying a single write by several
1344
      // seconds when we hit the hard limit, start delaying each
1345
      // individual write by 1ms to reduce latency variance.  Also,
1346
      // this delay hands over some CPU to the compaction thread in
1347
      // case it is sharing the same core as the writer.
1348
4.25k
      mutex_.Unlock();
1349
4.25k
      env_->SleepForMicroseconds(1000);
1350
4.25k
      allow_delay = false;  // Do not delay a single write more than once
1351
4.25k
      mutex_.Lock();
1352
2.00M
    } else if (!force &&
1353
1.96M
               (mem_->ApproximateMemoryUsage() <= options_.write_buffer_size)) {
1354
      // There is room in current memtable
1355
1.96M
      break;
1356
1.96M
    } else if (imm_ != nullptr) {
1357
      // We have filled up the current memtable, but the previous
1358
      // one is still being compacted, so we wait.
1359
0
      Log(options_.info_log, "Current memtable full; waiting...\n");
1360
0
      background_work_finished_signal_.Wait();
1361
31.6k
    } else if (versions_->NumLevelFiles(0) >= config::kL0_StopWritesTrigger) {
1362
      // There are too many level-0 files.
1363
3
      Log(options_.info_log, "Too many L0 files; waiting...\n");
1364
3
      background_work_finished_signal_.Wait();
1365
31.6k
    } else {
1366
      // Attempt to switch to a new memtable and trigger compaction of old
1367
31.6k
      assert(versions_->PrevLogNumber() == 0);
1368
31.6k
      uint64_t new_log_number = versions_->NewFileNumber();
1369
31.6k
      WritableFile* lfile = nullptr;
1370
31.6k
      s = env_->NewWritableFile(LogFileName(dbname_, new_log_number), &lfile);
1371
31.6k
      if (!s.ok()) {
1372
        // Avoid chewing through file number space in a tight loop.
1373
0
        versions_->ReuseFileNumber(new_log_number);
1374
0
        break;
1375
0
      }
1376
1377
31.6k
      delete log_;
1378
1379
31.6k
      s = logfile_->Close();
1380
31.6k
      if (!s.ok()) {
1381
        // We may have lost some data written to the previous log file.
1382
        // Switch to the new log file anyway, but record as a background
1383
        // error so we do not attempt any more writes.
1384
        //
1385
        // We could perhaps attempt to save the memtable corresponding
1386
        // to log file and suppress the error if that works, but that
1387
        // would add more complexity in a critical code path.
1388
0
        RecordBackgroundError(s);
1389
0
      }
1390
31.6k
      delete logfile_;
1391
1392
31.6k
      logfile_ = lfile;
1393
31.6k
      logfile_number_ = new_log_number;
1394
31.6k
      log_ = new log::Writer(lfile);
1395
31.6k
      imm_ = mem_;
1396
31.6k
      has_imm_.store(true, std::memory_order_release);
1397
31.6k
      mem_ = new MemTable(internal_comparator_);
1398
31.6k
      mem_->Ref();
1399
31.6k
      force = false;  // Do not force another compaction if have room
1400
31.6k
      MaybeScheduleCompaction();
1401
31.6k
    }
1402
2.00M
  }
1403
1.96M
  return s;
1404
1.96M
}
1405
1406
11.2k
bool DBImpl::GetProperty(const Slice& property, std::string* value) {
1407
11.2k
  value->clear();
1408
1409
11.2k
  MutexLock l(&mutex_);
1410
11.2k
  Slice in = property;
1411
11.2k
  Slice prefix("leveldb.");
1412
11.2k
  if (!in.starts_with(prefix)) return false;
1413
1.95k
  in.remove_prefix(prefix.size());
1414
1415
1.95k
  if (in.starts_with("num-files-at-level")) {
1416
622
    in.remove_prefix(strlen("num-files-at-level"));
1417
622
    uint64_t level;
1418
622
    bool ok = ConsumeDecimalNumber(&in, &level) && in.empty();
1419
622
    if (!ok || level >= config::kNumLevels) {
1420
529
      return false;
1421
529
    } else {
1422
93
      char buf[100];
1423
93
      std::snprintf(buf, sizeof(buf), "%d",
1424
93
                    versions_->NumLevelFiles(static_cast<int>(level)));
1425
93
      *value = buf;
1426
93
      return true;
1427
93
    }
1428
1.33k
  } else if (in == "stats") {
1429
0
    char buf[200];
1430
0
    std::snprintf(buf, sizeof(buf),
1431
0
                  "                               Compactions\n"
1432
0
                  "Level  Files Size(MB) Time(sec) Read(MB) Write(MB)\n"
1433
0
                  "--------------------------------------------------\n");
1434
0
    value->append(buf);
1435
0
    for (int level = 0; level < config::kNumLevels; level++) {
1436
0
      int files = versions_->NumLevelFiles(level);
1437
0
      if (stats_[level].micros > 0 || files > 0) {
1438
0
        std::snprintf(buf, sizeof(buf), "%3d %8d %8.0f %9.0f %8.0f %9.0f\n",
1439
0
                      level, files, versions_->NumLevelBytes(level) / 1048576.0,
1440
0
                      stats_[level].micros / 1e6,
1441
0
                      stats_[level].bytes_read / 1048576.0,
1442
0
                      stats_[level].bytes_written / 1048576.0);
1443
0
        value->append(buf);
1444
0
      }
1445
0
    }
1446
0
    return true;
1447
1.33k
  } else if (in == "sstables") {
1448
323
    *value = versions_->current()->DebugString();
1449
323
    return true;
1450
1.01k
  } else if (in == "approximate-memory-usage") {
1451
18
    size_t total_usage = options_.block_cache->TotalCharge();
1452
18
    if (mem_) {
1453
18
      total_usage += mem_->ApproximateMemoryUsage();
1454
18
    }
1455
18
    if (imm_) {
1456
0
      total_usage += imm_->ApproximateMemoryUsage();
1457
0
    }
1458
18
    char buf[50];
1459
18
    std::snprintf(buf, sizeof(buf), "%llu",
1460
18
                  static_cast<unsigned long long>(total_usage));
1461
18
    value->append(buf);
1462
18
    return true;
1463
18
  }
1464
1465
993
  return false;
1466
1.95k
}
1467
1468
0
void DBImpl::GetApproximateSizes(const Range* range, int n, uint64_t* sizes) {
1469
  // TODO(opt): better implementation
1470
0
  MutexLock l(&mutex_);
1471
0
  Version* v = versions_->current();
1472
0
  v->Ref();
1473
1474
0
  for (int i = 0; i < n; i++) {
1475
    // Convert user_key into a corresponding internal key.
1476
0
    InternalKey k1(range[i].start, kMaxSequenceNumber, kValueTypeForSeek);
1477
0
    InternalKey k2(range[i].limit, kMaxSequenceNumber, kValueTypeForSeek);
1478
0
    uint64_t start = versions_->ApproximateOffsetOf(v, k1);
1479
0
    uint64_t limit = versions_->ApproximateOffsetOf(v, k2);
1480
0
    sizes[i] = (limit >= start ? limit - start : 0);
1481
0
  }
1482
1483
0
  v->Unref();
1484
0
}
1485
1486
// Default implementations of convenience methods that subclasses of DB
1487
// can call if they wish
1488
46.8k
Status DB::Put(const WriteOptions& opt, const Slice& key, const Slice& value) {
1489
46.8k
  WriteBatch batch;
1490
46.8k
  batch.Put(key, value);
1491
46.8k
  return Write(opt, &batch);
1492
46.8k
}
1493
1494
1.89M
Status DB::Delete(const WriteOptions& opt, const Slice& key) {
1495
1.89M
  WriteBatch batch;
1496
1.89M
  batch.Delete(key);
1497
1.89M
  return Write(opt, &batch);
1498
1.89M
}
1499
1500
113k
DB::~DB() = default;
1501
1502
113k
Status DB::Open(const Options& options, const std::string& dbname, DB** dbptr) {
1503
113k
  *dbptr = nullptr;
1504
1505
113k
  DBImpl* impl = new DBImpl(options, dbname);
1506
113k
  impl->mutex_.Lock();
1507
113k
  VersionEdit edit;
1508
  // Recover handles create_if_missing, error_if_exists
1509
113k
  bool save_manifest = false;
1510
113k
  Status s = impl->Recover(&edit, &save_manifest);
1511
113k
  if (s.ok() && impl->mem_ == nullptr) {
1512
    // Create new log and a corresponding memtable.
1513
113k
    uint64_t new_log_number = impl->versions_->NewFileNumber();
1514
113k
    WritableFile* lfile;
1515
113k
    s = options.env->NewWritableFile(LogFileName(dbname, new_log_number),
1516
113k
                                     &lfile);
1517
113k
    if (s.ok()) {
1518
113k
      edit.SetLogNumber(new_log_number);
1519
113k
      impl->logfile_ = lfile;
1520
113k
      impl->logfile_number_ = new_log_number;
1521
113k
      impl->log_ = new log::Writer(lfile);
1522
113k
      impl->mem_ = new MemTable(impl->internal_comparator_);
1523
113k
      impl->mem_->Ref();
1524
113k
    }
1525
113k
  }
1526
113k
  if (s.ok() && save_manifest) {
1527
113k
    edit.SetPrevLogNumber(0);  // No older logs needed after recovery.
1528
113k
    edit.SetLogNumber(impl->logfile_number_);
1529
113k
    s = impl->versions_->LogAndApply(&edit, &impl->mutex_);
1530
113k
  }
1531
113k
  if (s.ok()) {
1532
113k
    impl->RemoveObsoleteFiles();
1533
113k
    impl->MaybeScheduleCompaction();
1534
113k
  }
1535
113k
  impl->mutex_.Unlock();
1536
113k
  if (s.ok()) {
1537
113k
    assert(impl->mem_ != nullptr);
1538
113k
    *dbptr = impl;
1539
113k
  } else {
1540
0
    delete impl;
1541
0
  }
1542
113k
  return s;
1543
113k
}
1544
1545
193k
Snapshot::~Snapshot() = default;
1546
1547
0
Status DestroyDB(const std::string& dbname, const Options& options) {
1548
0
  Env* env = options.env;
1549
0
  std::vector<std::string> filenames;
1550
0
  Status result = env->GetChildren(dbname, &filenames);
1551
0
  if (!result.ok()) {
1552
    // Ignore error in case directory does not exist
1553
0
    return Status::OK();
1554
0
  }
1555
1556
0
  FileLock* lock;
1557
0
  const std::string lockname = LockFileName(dbname);
1558
0
  result = env->LockFile(lockname, &lock);
1559
0
  if (result.ok()) {
1560
0
    uint64_t number;
1561
0
    FileType type;
1562
0
    for (size_t i = 0; i < filenames.size(); i++) {
1563
0
      if (ParseFileName(filenames[i], &number, &type) &&
1564
0
          type != kDBLockFile) {  // Lock file will be deleted at end
1565
0
        Status del = env->RemoveFile(dbname + "/" + filenames[i]);
1566
0
        if (result.ok() && !del.ok()) {
1567
0
          result = del;
1568
0
        }
1569
0
      }
1570
0
    }
1571
0
    env->UnlockFile(lock);  // Ignore error since state is already gone
1572
0
    env->RemoveFile(lockname);
1573
0
    env->RemoveDir(dbname);  // Ignore error in case dir contains other files
1574
0
  }
1575
0
  return result;
1576
0
}
1577
1578
}  // namespace leveldb