db_iter.cc 45.0 KB
Newer Older
1
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
S
Siying Dong 已提交
2 3 4
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
5
//
J
jorlow@chromium.org 已提交
6 7 8 9 10
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/db_iter.h"
S
Stanislau Hlebik 已提交
11
#include <string>
12
#include <iostream>
S
Stanislau Hlebik 已提交
13
#include <limits>
J
jorlow@chromium.org 已提交
14 15

#include "db/dbformat.h"
16
#include "db/merge_context.h"
17
#include "db/merge_helper.h"
18
#include "db/pinned_iterators_manager.h"
19
#include "file/filename.h"
20
#include "logging/logging.h"
21
#include "memory/arena.h"
22
#include "monitoring/perf_context_imp.h"
23 24 25
#include "rocksdb/env.h"
#include "rocksdb/iterator.h"
#include "rocksdb/merge_operator.h"
26
#include "rocksdb/options.h"
S
sdong 已提交
27
#include "table/internal_iterator.h"
28
#include "table/iterator_wrapper.h"
29
#include "trace_replay/trace_replay.h"
J
jorlow@chromium.org 已提交
30
#include "util/mutexlock.h"
31
#include "util/string_util.h"
32
#include "util/user_comparator_wrapper.h"
J
jorlow@chromium.org 已提交
33

34
namespace rocksdb {
J
jorlow@chromium.org 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48

#if 0
static void DumpInternalIter(Iterator* iter) {
  for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {
    ParsedInternalKey k;
    if (!ParseInternalKey(iter->key(), &k)) {
      fprintf(stderr, "Corrupt '%s'\n", EscapeString(iter->key()).c_str());
    } else {
      fprintf(stderr, "@ '%s'\n", k.DebugString().c_str());
    }
  }
}
#endif

49
DBIter::DBIter(Env* _env, const ReadOptions& read_options,
50 51 52 53 54 55 56 57
               const ImmutableCFOptions& cf_options,
               const MutableCFOptions& mutable_cf_options,
               const Comparator* cmp, InternalIterator* iter, SequenceNumber s,
               bool arena_mode, uint64_t max_sequential_skip_in_iterations,
               ReadCallback* read_callback, DBImpl* db_impl,
               ColumnFamilyData* cfd, bool allow_blob)
    : prefix_extractor_(mutable_cf_options.prefix_extractor.get()),
      env_(_env),
58 59 60 61 62 63 64 65 66 67 68 69 70 71
      logger_(cf_options.info_log),
      user_comparator_(cmp),
      merge_operator_(cf_options.merge_operator),
      iter_(iter),
      read_callback_(read_callback),
      sequence_(s),
      statistics_(cf_options.statistics),
      num_internal_keys_skipped_(0),
      iterate_lower_bound_(read_options.iterate_lower_bound),
      iterate_upper_bound_(read_options.iterate_upper_bound),
      direction_(kForward),
      valid_(false),
      current_entry_is_merged_(false),
      is_key_seqnum_zero_(false),
72 73 74
      prefix_same_as_start_(mutable_cf_options.prefix_extractor
                                ? read_options.prefix_same_as_start
                                : false),
75
      pin_thru_lifetime_(read_options.pin_data),
S
sdong 已提交
76 77 78
      expect_total_order_inner_iter_(prefix_extractor_ == nullptr ||
                                     read_options.total_order_seek ||
                                     read_options.auto_prefix_mode),
79 80 81 82 83 84 85 86 87 88 89 90 91 92
      allow_blob_(allow_blob),
      is_blob_(false),
      arena_mode_(arena_mode),
      range_del_agg_(&cf_options.internal_comparator, s),
      db_impl_(db_impl),
      cfd_(cfd),
      start_seqnum_(read_options.iter_start_seqnum) {
  RecordTick(statistics_, NO_ITERATOR_CREATED);
  max_skip_ = max_sequential_skip_in_iterations;
  max_skippable_internal_keys_ = read_options.max_skippable_internal_keys;
  if (pin_thru_lifetime_) {
    pinned_iters_mgr_.StartPinning();
  }
  if (iter_.iter()) {
93
    iter_.iter()->SetPinnedItersMgr(&pinned_iters_mgr_);
J
jorlow@chromium.org 已提交
94
  }
95
}
96

97 98 99
Status DBIter::GetProperty(std::string prop_name, std::string* prop) {
  if (prop == nullptr) {
    return Status::InvalidArgument("prop is nullptr");
100
  }
101 102 103 104
  if (prop_name == "rocksdb.iterator.super-version-number") {
    // First try to pass the value returned from inner iterator.
    return iter_.iter()->GetProperty(prop_name, prop);
  } else if (prop_name == "rocksdb.iterator.is-key-pinned") {
105
    if (valid_) {
106 107 108
      *prop = (pin_thru_lifetime_ && saved_key_.IsKeyPinned()) ? "1" : "0";
    } else {
      *prop = "Iterator is not valid.";
109
    }
110 111 112 113
    return Status::OK();
  } else if (prop_name == "rocksdb.iterator.internal-key") {
    *prop = saved_key_.GetUserKey().ToString();
    return Status::OK();
114
  }
115 116
  return Status::InvalidArgument("Unidentified property.");
}
117

118
bool DBIter::ParseKey(ParsedInternalKey* ikey) {
119
  if (!ParseInternalKey(iter_.key(), ikey)) {
J
jorlow@chromium.org 已提交
120
    status_ = Status::Corruption("corrupted internal key in DBIter");
121
    valid_ = false;
122
    ROCKS_LOG_ERROR(logger_, "corrupted internal key in DBIter: %s",
123
                    iter_.key().ToString(true).c_str());
J
jorlow@chromium.org 已提交
124 125 126 127 128 129
    return false;
  } else {
    return true;
  }
}

J
jorlow@chromium.org 已提交
130 131
void DBIter::Next() {
  assert(valid_);
132
  assert(status_.ok());
J
jorlow@chromium.org 已提交
133

134
  PERF_CPU_TIMER_GUARD(iter_next_cpu_nanos, env_);
135 136
  // Release temporarily pinned blocks from last operation
  ReleaseTempPinnedData();
137 138 139
  local_stats_.skip_count_ += num_internal_keys_skipped_;
  local_stats_.skip_count_--;
  num_internal_keys_skipped_ = 0;
140
  bool ok = true;
S
Stanislau Hlebik 已提交
141
  if (direction_ == kReverse) {
142
    is_key_seqnum_zero_ = false;
143 144 145
    if (!ReverseToForward()) {
      ok = false;
    }
146
  } else if (!current_entry_is_merged_) {
147 148 149 150 151
    // If the current value is not a merge, the iter position is the
    // current key, which is already returned. We can safely issue a
    // Next() without checking the current key.
    // If the current key is a merge, very likely iter already points
    // to the next internal position.
152 153
    assert(iter_.Valid());
    iter_.Next();
154
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
J
jorlow@chromium.org 已提交
155
  }
J
jorlow@chromium.org 已提交
156

157
  local_stats_.next_count_++;
158
  if (ok && iter_.Valid()) {
159 160 161 162 163
    Slice prefix;
    if (prefix_same_as_start_) {
      assert(prefix_extractor_ != nullptr);
      prefix = prefix_.GetUserKey();
    }
164
    FindNextUserEntry(true /* skipping the current user key */,
165
                      prefix_same_as_start_ ? &prefix : nullptr);
166
  } else {
167
    is_key_seqnum_zero_ = false;
168 169
    valid_ = false;
  }
170 171 172 173
  if (statistics_ != nullptr && valid_) {
    local_stats_.next_found_count_++;
    local_stats_.bytes_read_ += (key().size() + value().size());
  }
J
jorlow@chromium.org 已提交
174 175
}

176
// PRE: saved_key_ has the current user key if skipping_saved_key
177 178 179 180 181 182
// POST: saved_key_ should have the next user key if valid_,
//       if the current entry is a result of merge
//           current_entry_is_merged_ => true
//           saved_value_             => the merged value
//
// NOTE: In between, saved_key_ can point to a user key that has
183
//       a delete marker or a sequence number higher than sequence_
184
//       saved_key_ MUST have a proper user_key before calling this function
185
//
186 187 188 189
// The prefix parameter, if not null, indicates that we need to iterator
// within the prefix, and the iterator needs to be made invalid, if no
// more entry for the prefix can be found.
bool DBIter::FindNextUserEntry(bool skipping_saved_key, const Slice* prefix) {
190
  PERF_TIMER_GUARD(find_next_user_entry_time);
191
  return FindNextUserEntryInternal(skipping_saved_key, prefix);
192 193 194
}

// Actual implementation of DBIter::FindNextUserEntry()
195 196
bool DBIter::FindNextUserEntryInternal(bool skipping_saved_key,
                                       const Slice* prefix) {
J
jorlow@chromium.org 已提交
197
  // Loop until we hit an acceptable entry to yield
198
  assert(iter_.Valid());
199
  assert(status_.ok());
J
jorlow@chromium.org 已提交
200
  assert(direction_ == kForward);
201
  current_entry_is_merged_ = false;
202 203 204

  // How many times in a row we have skipped an entry with user key less than
  // or equal to saved_key_. We could skip these entries either because
205
  // sequence numbers were too high or because skipping_saved_key = true.
206
  // What saved_key_ contains throughout this method:
207 208
  //  - if skipping_saved_key        : saved_key_ contains the key that we need
  //  to skip,
209 210 211 212 213
  //                         and we haven't seen any keys greater than that,
  //  - if num_skipped > 0 : saved_key_ contains the key that we have skipped
  //                         num_skipped times, and we haven't seen any keys
  //                         greater than that,
  //  - none of the above  : saved_key_ can contain anything, it doesn't matter.
214
  uint64_t num_skipped = 0;
215 216 217 218 219
  // For write unprepared, the target sequence number in reseek could be larger
  // than the snapshot, and thus needs to be skipped again. This could result in
  // an infinite loop of reseeks. To avoid that, we limit the number of reseeks
  // to one.
  bool reseek_done = false;
220

Y
Yi Wu 已提交
221 222
  is_blob_ = false;

J
jorlow@chromium.org 已提交
223
  do {
224 225 226
    // Will update is_key_seqnum_zero_ as soon as we parsed the current key
    // but we need to save the previous value to be used in the loop.
    bool is_prev_key_seqnum_zero = is_key_seqnum_zero_;
227
    if (!ParseKey(&ikey_)) {
228
      is_key_seqnum_zero_ = false;
229
      return false;
230
    }
231

232 233
    is_key_seqnum_zero_ = (ikey_.sequence == 0);

234 235 236
    assert(iterate_upper_bound_ == nullptr || iter_.MayBeOutOfUpperBound() ||
           user_comparator_.Compare(ikey_.user_key, *iterate_upper_bound_) < 0);
    if (iterate_upper_bound_ != nullptr && iter_.MayBeOutOfUpperBound() &&
237
        user_comparator_.Compare(ikey_.user_key, *iterate_upper_bound_) >= 0) {
238 239
      break;
    }
240

241 242 243 244
    assert(prefix == nullptr || prefix_extractor_ != nullptr);
    if (prefix != nullptr &&
        prefix_extractor_->Transform(ikey_.user_key).compare(*prefix) != 0) {
      assert(prefix_same_as_start_);
245 246 247
      break;
    }

248
    if (TooManyInternalKeysSkipped()) {
249
      return false;
250 251
    }

Y
Yi Wu 已提交
252
    if (IsVisible(ikey_.sequence)) {
253 254 255 256
      // If the previous entry is of seqnum 0, the current entry will not
      // possibly be skipped. This condition can potentially be relaxed to
      // prev_key.seq <= ikey_.sequence. We are cautious because it will be more
      // prone to bugs causing the same user key with the same sequence number.
257
      if (!is_prev_key_seqnum_zero && skipping_saved_key &&
258 259
          user_comparator_.Compare(ikey_.user_key, saved_key_.GetUserKey()) <=
              0) {
260 261 262
        num_skipped++;  // skip this entry
        PERF_COUNTER_ADD(internal_key_skipped_count, 1);
      } else {
263 264 265
        assert(!skipping_saved_key ||
               user_comparator_.Compare(ikey_.user_key,
                                        saved_key_.GetUserKey()) > 0);
266
        num_skipped = 0;
267
        reseek_done = false;
268
        switch (ikey_.type) {
269 270 271 272
          case kTypeDeletion:
          case kTypeSingleDeletion:
            // Arrange to skip all upcoming entries for this key since
            // they are hidden by this deletion.
273 274 275
            // if iterartor specified start_seqnum we
            // 1) return internal key, including the type
            // 2) return ikey only if ikey.seqnum >= start_seqnum_
276
            // note that if deletion seqnum is < start_seqnum_ we
277 278 279
            // just skip it like in normal iterator.
            if (start_seqnum_ > 0 && ikey_.sequence >= start_seqnum_)  {
              saved_key_.SetInternalKey(ikey_);
280 281
              valid_ = true;
              return true;
282 283
            } else {
              saved_key_.SetUserKey(
284 285
                  ikey_.user_key, !pin_thru_lifetime_ ||
                                      !iter_.iter()->IsKeyPinned() /* copy */);
286
              skipping_saved_key = true;
287
              PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
288
            }
289 290
            break;
          case kTypeValue:
Y
Yi Wu 已提交
291
          case kTypeBlobIndex:
292 293 294 295 296 297 298 299
            if (start_seqnum_ > 0) {
              // we are taking incremental snapshot here
              // incremental snapshots aren't supported on DB with range deletes
              assert(!(
                (ikey_.type == kTypeBlobIndex) && (start_seqnum_ > 0)
              ));
              if (ikey_.sequence >= start_seqnum_) {
                saved_key_.SetInternalKey(ikey_);
Y
Yi Wu 已提交
300
                valid_ = true;
301
                return true;
302 303
              } else {
                // this key and all previous versions shouldn't be included,
304
                // skipping_saved_key
305 306 307 308
                saved_key_.SetUserKey(
                    ikey_.user_key,
                    !pin_thru_lifetime_ ||
                        !iter_.iter()->IsKeyPinned() /* copy */);
309
                skipping_saved_key = true;
Y
Yi Wu 已提交
310
              }
311
            } else {
312
              saved_key_.SetUserKey(
313 314
                  ikey_.user_key, !pin_thru_lifetime_ ||
                                      !iter_.iter()->IsKeyPinned() /* copy */);
315
              if (range_del_agg_.ShouldDelete(
316
                      ikey_, RangeDelPositioningMode::kForwardTraversal)) {
317 318
                // Arrange to skip all upcoming entries for this key since
                // they are hidden by this deletion.
319
                skipping_saved_key = true;
320
                num_skipped = 0;
321
                reseek_done = false;
322 323 324 325 326 327 328 329
                PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
              } else if (ikey_.type == kTypeBlobIndex) {
                if (!allow_blob_) {
                  ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
                  status_ = Status::NotSupported(
                      "Encounter unexpected blob index. Please open DB with "
                      "rocksdb::blob_db::BlobDB instead.");
                  valid_ = false;
330
                  return false;
331
                }
332 333 334 335

                is_blob_ = true;
                valid_ = true;
                return true;
336 337
              } else {
                valid_ = true;
338
                return true;
339
              }
340 341 342
            }
            break;
          case kTypeMerge:
343
            saved_key_.SetUserKey(
344
                ikey_.user_key,
345
                !pin_thru_lifetime_ || !iter_.iter()->IsKeyPinned() /* copy */);
346
            if (range_del_agg_.ShouldDelete(
347
                    ikey_, RangeDelPositioningMode::kForwardTraversal)) {
348 349
              // Arrange to skip all upcoming entries for this key since
              // they are hidden by this deletion.
350
              skipping_saved_key = true;
351
              num_skipped = 0;
352
              reseek_done = false;
353 354 355 356 357 358
              PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
            } else {
              // By now, we are sure the current ikey is going to yield a
              // value
              current_entry_is_merged_ = true;
              valid_ = true;
359
              return MergeValuesNewToOld();  // Go to a different state machine
360 361 362 363 364
            }
            break;
          default:
            assert(false);
            break;
365
        }
J
jorlow@chromium.org 已提交
366
      }
367 368 369
    } else {
      PERF_COUNTER_ADD(internal_recent_skipped_count, 1);

370 371 372 373
      // This key was inserted after our snapshot was taken.
      // If this happens too many times in a row for the same user key, we want
      // to seek to the target sequence number.
      int cmp =
374
          user_comparator_.Compare(ikey_.user_key, saved_key_.GetUserKey());
375
      if (cmp == 0 || (skipping_saved_key && cmp <= 0)) {
376 377
        num_skipped++;
      } else {
378
        saved_key_.SetUserKey(
379
            ikey_.user_key,
380
            !iter_.iter()->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
381
        skipping_saved_key = false;
382
        num_skipped = 0;
383
        reseek_done = false;
384
      }
J
jorlow@chromium.org 已提交
385
    }
386 387 388

    // If we have sequentially iterated via numerous equal keys, then it's
    // better to seek so that we can avoid too many key comparisons.
389 390 391 392 393 394 395 396
    //
    // To avoid infinite loops, do not reseek if we have already attempted to
    // reseek previously.
    //
    // TODO(lth): If we reseek to sequence number greater than ikey_.sequence,
    // than it does not make sense to reseek as we would actually land further
    // away from the desired key. There is opportunity for optimization here.
    if (num_skipped > max_skip_ && !reseek_done) {
397
      is_key_seqnum_zero_ = false;
398
      num_skipped = 0;
399
      reseek_done = true;
400
      std::string last_key;
401
      if (skipping_saved_key) {
402 403 404
        // We're looking for the next user-key but all we see are the same
        // user-key with decreasing sequence numbers. Fast forward to
        // sequence number 0 and type deletion (the smallest type).
405 406
        AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetUserKey(),
                                                       0, kTypeDeletion));
407 408
        // Don't set skipping_saved_key = false because we may still see more
        // user-keys equal to saved_key_.
409 410 411 412 413 414 415
      } else {
        // We saw multiple entries with this user key and sequence numbers
        // higher than sequence_. Fast forward to sequence_.
        // Note that this only covers a case when a higher key was overwritten
        // many times since our snapshot was taken, not the case when a lot of
        // different keys were inserted after our snapshot was taken.
        AppendInternalKey(&last_key,
416
                          ParsedInternalKey(saved_key_.GetUserKey(), sequence_,
417 418
                                            kValueTypeForSeek));
      }
419
      iter_.Seek(last_key);
420 421
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
    } else {
422
      iter_.Next();
423
    }
424
  } while (iter_.Valid());
425

J
jorlow@chromium.org 已提交
426
  valid_ = false;
427
  return iter_.status().ok();
J
jorlow@chromium.org 已提交
428 429
}

430 431
// Merge values of the same user key starting from the current iter_ position
// Scan from the newer entries to older entries.
432
// PRE: iter_.key() points to the first merge type entry
433 434 435
//      saved_key_ stores the user key
// POST: saved_value_ has the merged value for the user key
//       iter_ points to the next entry (or invalid)
436
bool DBIter::MergeValuesNewToOld() {
437
  if (!merge_operator_) {
438
    ROCKS_LOG_ERROR(logger_, "Options::merge_operator is null.");
439
    status_ = Status::InvalidArgument("merge_operator_ must be set.");
440
    valid_ = false;
441
    return false;
D
Deon Nicholas 已提交
442
  }
443

444 445
  // Temporarily pin the blocks that hold merge operands
  TempPinData();
446
  merge_context_.Clear();
447
  // Start the merge process by pushing the first operand
448 449
  merge_context_.PushOperand(
      iter_.value(), iter_.iter()->IsValuePinned() /* operand_pinned */);
450
  TEST_SYNC_POINT("DBIter::MergeValuesNewToOld:PushedFirstOperand");
451 452

  ParsedInternalKey ikey;
453
  Status s;
454
  for (iter_.Next(); iter_.Valid(); iter_.Next()) {
455
    TEST_SYNC_POINT("DBIter::MergeValuesNewToOld:SteppedToNextOperand");
456
    if (!ParseKey(&ikey)) {
457
      return false;
458 459
    }

460
    if (!user_comparator_.Equal(ikey.user_key, saved_key_.GetUserKey())) {
461 462
      // hit the next user key, stop right here
      break;
A
Andrew Kryczka 已提交
463
    } else if (kTypeDeletion == ikey.type || kTypeSingleDeletion == ikey.type ||
464
               range_del_agg_.ShouldDelete(
465
                   ikey, RangeDelPositioningMode::kForwardTraversal)) {
466 467
      // hit a delete with the same user key, stop right here
      // iter_ is positioned after delete
468
      iter_.Next();
469
      break;
A
Andres Noetzli 已提交
470
    } else if (kTypeValue == ikey.type) {
471 472
      // hit a put, merge the put value with operands and store the
      // final result in saved_value_. We are done!
473
      const Slice val = iter_.value();
474 475
      s = MergeHelper::TimedFullMerge(
          merge_operator_, ikey.user_key, &val, merge_context_.GetOperands(),
476
          &saved_value_, logger_, statistics_, env_, &pinned_value_, true);
477
      if (!s.ok()) {
Y
Yi Wu 已提交
478
        valid_ = false;
479
        status_ = s;
480
        return false;
481
      }
482
      // iter_ is positioned after put
483 484
      iter_.Next();
      if (!iter_.status().ok()) {
485 486 487 488
        valid_ = false;
        return false;
      }
      return true;
A
Andres Noetzli 已提交
489
    } else if (kTypeMerge == ikey.type) {
490 491
      // hit a merge, add the value as an operand and run associative merge.
      // when complete, add result to operands and continue.
492 493
      merge_context_.PushOperand(
          iter_.value(), iter_.iter()->IsValuePinned() /* operand_pinned */);
494
      PERF_COUNTER_ADD(internal_merge_count, 1);
Y
Yi Wu 已提交
495 496 497 498 499 500 501 502 503 504 505
    } else if (kTypeBlobIndex == ikey.type) {
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
      } else {
        status_ =
            Status::NotSupported("Blob DB does not support merge operator.");
      }
      valid_ = false;
506
      return false;
A
Andres Noetzli 已提交
507 508
    } else {
      assert(false);
509 510 511
    }
  }

512
  if (!iter_.status().ok()) {
513 514 515 516
    valid_ = false;
    return false;
  }

517 518 519 520
  // we either exhausted all internal keys under this user key, or hit
  // a deletion marker.
  // feed null as the existing value to the merge operator, such that
  // client can differentiate this scenario and do things accordingly.
521 522 523
  s = MergeHelper::TimedFullMerge(merge_operator_, saved_key_.GetUserKey(),
                                  nullptr, merge_context_.GetOperands(),
                                  &saved_value_, logger_, statistics_, env_,
524
                                  &pinned_value_, true);
525
  if (!s.ok()) {
Y
Yi Wu 已提交
526
    valid_ = false;
527
    status_ = s;
528
    return false;
529
  }
530 531 532

  assert(status_.ok());
  return true;
533 534
}

J
jorlow@chromium.org 已提交
535 536
void DBIter::Prev() {
  assert(valid_);
537
  assert(status_.ok());
538 539

  PERF_CPU_TIMER_GUARD(iter_prev_cpu_nanos, env_);
540
  ReleaseTempPinnedData();
541
  ResetInternalKeysSkippedCounter();
542
  bool ok = true;
S
Stanislau Hlebik 已提交
543
  if (direction_ == kForward) {
544 545 546 547 548
    if (!ReverseToBackward()) {
      ok = false;
    }
  }
  if (ok) {
549 550 551 552 553 554
    Slice prefix;
    if (prefix_same_as_start_) {
      assert(prefix_extractor_ != nullptr);
      prefix = prefix_.GetUserKey();
    }
    PrevInternal(prefix_same_as_start_ ? &prefix : nullptr);
S
Stanislau Hlebik 已提交
555
  }
556

M
Manuel Ung 已提交
557
  if (statistics_ != nullptr) {
558
    local_stats_.prev_count_++;
M
Manuel Ung 已提交
559
    if (valid_) {
560 561
      local_stats_.prev_found_count_++;
      local_stats_.bytes_read_ += (key().size() + value().size());
M
Manuel Ung 已提交
562 563
    }
  }
S
Stanislau Hlebik 已提交
564
}
J
jorlow@chromium.org 已提交
565

566
bool DBIter::ReverseToForward() {
567
  assert(iter_.status().ok());
568 569 570 571

  // When moving backwards, iter_ is positioned on _previous_ key, which may
  // not exist or may have different prefix than the current key().
  // If that's the case, seek iter_ to current key.
S
sdong 已提交
572
  if (!expect_total_order_inner_iter() || !iter_.Valid()) {
573 574
    IterKey last_key;
    last_key.SetInternalKey(ParsedInternalKey(
575
        saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
576
    iter_.Seek(last_key.GetInternalKey());
577
  }
578

579
  direction_ = kForward;
580
  // Skip keys less than the current key() (a.k.a. saved_key_).
581
  while (iter_.Valid()) {
582 583 584 585
    ParsedInternalKey ikey;
    if (!ParseKey(&ikey)) {
      return false;
    }
586
    if (user_comparator_.Compare(ikey.user_key, saved_key_.GetUserKey()) >= 0) {
587 588
      return true;
    }
589
    iter_.Next();
590 591
  }

592
  if (!iter_.status().ok()) {
593 594
    valid_ = false;
    return false;
595
  }
596 597

  return true;
598 599
}

600 601
// Move iter_ to the key before saved_key_.
bool DBIter::ReverseToBackward() {
602
  assert(iter_.status().ok());
603 604 605 606 607

  // When current_entry_is_merged_ is true, iter_ may be positioned on the next
  // key, which may not exist or may have prefix different from current.
  // If that's the case, seek to saved_key_.
  if (current_entry_is_merged_ &&
S
sdong 已提交
608
      (!expect_total_order_inner_iter() || !iter_.Valid())) {
609
    IterKey last_key;
610 611 612 613 614
    // Using kMaxSequenceNumber and kValueTypeForSeek
    // (not kValueTypeForSeekForPrev) to seek to a key strictly smaller
    // than saved_key_.
    last_key.SetInternalKey(ParsedInternalKey(
        saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
S
sdong 已提交
615
    if (!expect_total_order_inner_iter()) {
616
      iter_.SeekForPrev(last_key.GetInternalKey());
617 618 619 620 621
    } else {
      // Some iterators may not support SeekForPrev(), so we avoid using it
      // when prefix seek mode is disabled. This is somewhat expensive
      // (an extra Prev(), as well as an extra change of direction of iter_),
      // so we may need to reconsider it later.
622 623 624
      iter_.Seek(last_key.GetInternalKey());
      if (!iter_.Valid() && iter_.status().ok()) {
        iter_.SeekToLast();
625
      }
626 627 628 629
    }
  }

  direction_ = kReverse;
630
  return FindUserKeyBeforeSavedKey();
631 632
}

633
void DBIter::PrevInternal(const Slice* prefix) {
634
  while (iter_.Valid()) {
635
    saved_key_.SetUserKey(
636 637
        ExtractUserKey(iter_.key()),
        !iter_.iter()->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
638

639 640
    assert(prefix == nullptr || prefix_extractor_ != nullptr);
    if (prefix != nullptr &&
641
        prefix_extractor_->Transform(saved_key_.GetUserKey())
642 643
                .compare(*prefix) != 0) {
      assert(prefix_same_as_start_);
644 645 646 647 648
      // Current key does not have the same prefix as start
      valid_ = false;
      return;
    }

649 650 651 652
    assert(iterate_lower_bound_ == nullptr || iter_.MayBeOutOfLowerBound() ||
           user_comparator_.Compare(saved_key_.GetUserKey(),
                                    *iterate_lower_bound_) >= 0);
    if (iterate_lower_bound_ != nullptr && iter_.MayBeOutOfLowerBound() &&
653 654
        user_comparator_.Compare(saved_key_.GetUserKey(),
                                 *iterate_lower_bound_) < 0) {
655 656 657 658 659
      // We've iterated earlier than the user-specified lower bound.
      valid_ = false;
      return;
    }

660
    if (!FindValueForCurrentKey()) {  // assigns valid_
S
Stanislau Hlebik 已提交
661
      return;
J
jorlow@chromium.org 已提交
662
    }
663

664 665 666
    // Whether or not we found a value for current key, we need iter_ to end up
    // on a smaller key.
    if (!FindUserKeyBeforeSavedKey()) {
667 668 669
      return;
    }

670 671 672
    if (valid_) {
      // Found the value.
      return;
S
Stanislau Hlebik 已提交
673
    }
674 675 676

    if (TooManyInternalKeysSkipped(false)) {
      return;
S
Stanislau Hlebik 已提交
677 678
    }
  }
679

S
Stanislau Hlebik 已提交
680 681
  // We haven't found any key - iterator is not valid
  valid_ = false;
J
jorlow@chromium.org 已提交
682 683
}

684 685 686 687 688 689 690 691 692 693 694
// Used for backwards iteration.
// Looks at the entries with user key saved_key_ and finds the most up-to-date
// value for it, or executes a merge, or determines that the value was deleted.
// Sets valid_ to true if the value is found and is ready to be presented to
// the user through value().
// Sets valid_ to false if the value was deleted, and we should try another key.
// Returns false if an error occurred, and !status().ok() and !valid_.
//
// PRE: iter_ is positioned on the last entry with user key equal to saved_key_.
// POST: iter_ is positioned on one of the entries equal to saved_key_, or on
//       the entry just before them, or on the entry just after them.
S
Stanislau Hlebik 已提交
695
bool DBIter::FindValueForCurrentKey() {
696
  assert(iter_.Valid());
697
  merge_context_.Clear();
698
  current_entry_is_merged_ = false;
A
Andres Noetzli 已提交
699 700
  // last entry before merge (could be kTypeDeletion, kTypeSingleDeletion or
  // kTypeValue)
S
Stanislau Hlebik 已提交
701 702
  ValueType last_not_merge_type = kTypeDeletion;
  ValueType last_key_entry_type = kTypeDeletion;
J
jorlow@chromium.org 已提交
703

704 705 706
  // Temporarily pin blocks that hold (merge operands / the value)
  ReleaseTempPinnedData();
  TempPinData();
S
Stanislau Hlebik 已提交
707
  size_t num_skipped = 0;
708
  while (iter_.Valid()) {
709 710 711 712 713 714
    ParsedInternalKey ikey;
    if (!ParseKey(&ikey)) {
      return false;
    }

    if (!IsVisible(ikey.sequence) ||
715
        !user_comparator_.Equal(ikey.user_key, saved_key_.GetUserKey())) {
716 717
      break;
    }
718 719 720 721
    if (TooManyInternalKeysSkipped()) {
      return false;
    }

722 723 724
    // This user key has lots of entries.
    // We're going from old to new, and it's taking too long. Let's do a Seek()
    // and go from new to old. This helps when a key was overwritten many times.
725
    if (num_skipped >= max_skip_) {
S
Stanislau Hlebik 已提交
726 727 728 729 730 731
      return FindValueForCurrentKeyUsingSeek();
    }

    last_key_entry_type = ikey.type;
    switch (last_key_entry_type) {
      case kTypeValue:
Y
Yi Wu 已提交
732
      case kTypeBlobIndex:
733
        if (range_del_agg_.ShouldDelete(
734
                ikey, RangeDelPositioningMode::kBackwardTraversal)) {
A
Andrew Kryczka 已提交
735 736 737
          last_key_entry_type = kTypeRangeDeletion;
          PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
        } else {
738 739
          assert(iter_.iter()->IsValuePinned());
          pinned_value_ = iter_.value();
A
Andrew Kryczka 已提交
740
        }
741
        merge_context_.Clear();
A
Andrew Kryczka 已提交
742
        last_not_merge_type = last_key_entry_type;
S
Stanislau Hlebik 已提交
743 744
        break;
      case kTypeDeletion:
A
Andres Noetzli 已提交
745
      case kTypeSingleDeletion:
746
        merge_context_.Clear();
A
Andres Noetzli 已提交
747
        last_not_merge_type = last_key_entry_type;
748
        PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
S
Stanislau Hlebik 已提交
749 750
        break;
      case kTypeMerge:
751
        if (range_del_agg_.ShouldDelete(
752
                ikey, RangeDelPositioningMode::kBackwardTraversal)) {
A
Andrew Kryczka 已提交
753 754 755 756 757 758 759
          merge_context_.Clear();
          last_key_entry_type = kTypeRangeDeletion;
          last_not_merge_type = last_key_entry_type;
          PERF_COUNTER_ADD(internal_delete_skipped_count, 1);
        } else {
          assert(merge_operator_ != nullptr);
          merge_context_.PushOperandBack(
760 761
              iter_.value(),
              iter_.iter()->IsValuePinned() /* operand_pinned */);
762
          PERF_COUNTER_ADD(internal_merge_count, 1);
A
Andrew Kryczka 已提交
763
        }
S
Stanislau Hlebik 已提交
764 765 766 767 768
        break;
      default:
        assert(false);
    }

769
    PERF_COUNTER_ADD(internal_key_skipped_count, 1);
770
    iter_.Prev();
S
Stanislau Hlebik 已提交
771
    ++num_skipped;
772 773
  }

774
  if (!iter_.status().ok()) {
775 776
    valid_ = false;
    return false;
S
Stanislau Hlebik 已提交
777 778
  }

779
  Status s;
Y
Yi Wu 已提交
780
  is_blob_ = false;
S
Stanislau Hlebik 已提交
781 782
  switch (last_key_entry_type) {
    case kTypeDeletion:
A
Andres Noetzli 已提交
783
    case kTypeSingleDeletion:
A
Andrew Kryczka 已提交
784
    case kTypeRangeDeletion:
S
Stanislau Hlebik 已提交
785
      valid_ = false;
786
      return true;
S
Stanislau Hlebik 已提交
787
    case kTypeMerge:
788
      current_entry_is_merged_ = true;
A
Aaron Gao 已提交
789
      if (last_not_merge_type == kTypeDeletion ||
A
Andrew Kryczka 已提交
790 791
          last_not_merge_type == kTypeSingleDeletion ||
          last_not_merge_type == kTypeRangeDeletion) {
792 793 794
        s = MergeHelper::TimedFullMerge(
            merge_operator_, saved_key_.GetUserKey(), nullptr,
            merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
795
            env_, &pinned_value_, true);
Y
Yi Wu 已提交
796 797 798 799 800 801 802 803 804 805 806
      } else if (last_not_merge_type == kTypeBlobIndex) {
        if (!allow_blob_) {
          ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
          status_ = Status::NotSupported(
              "Encounter unexpected blob index. Please open DB with "
              "rocksdb::blob_db::BlobDB instead.");
        } else {
          status_ =
              Status::NotSupported("Blob DB does not support merge operator.");
        }
        valid_ = false;
807
        return false;
808
      } else {
S
Stanislau Hlebik 已提交
809
        assert(last_not_merge_type == kTypeValue);
810
        s = MergeHelper::TimedFullMerge(
811
            merge_operator_, saved_key_.GetUserKey(), &pinned_value_,
812
            merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
813
            env_, &pinned_value_, true);
814
      }
S
Stanislau Hlebik 已提交
815 816
      break;
    case kTypeValue:
817
      // do nothing - we've already has value in pinned_value_
S
Stanislau Hlebik 已提交
818
      break;
Y
Yi Wu 已提交
819 820 821 822 823 824 825
    case kTypeBlobIndex:
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
        valid_ = false;
826
        return false;
Y
Yi Wu 已提交
827 828 829
      }
      is_blob_ = true;
      break;
S
Stanislau Hlebik 已提交
830 831 832
    default:
      assert(false);
      break;
J
jorlow@chromium.org 已提交
833
  }
834
  if (!s.ok()) {
Y
Yi Wu 已提交
835
    valid_ = false;
836
    status_ = s;
837
    return false;
838
  }
839
  valid_ = true;
S
Stanislau Hlebik 已提交
840 841
  return true;
}
J
jorlow@chromium.org 已提交
842

S
Stanislau Hlebik 已提交
843 844
// This function is used in FindValueForCurrentKey.
// We use Seek() function instead of Prev() to find necessary value
845 846
// TODO: This is very similar to FindNextUserEntry() and MergeValuesNewToOld().
//       Would be nice to reuse some code.
S
Stanislau Hlebik 已提交
847
bool DBIter::FindValueForCurrentKeyUsingSeek() {
848 849 850
  // FindValueForCurrentKey will enable pinning before calling
  // FindValueForCurrentKeyUsingSeek()
  assert(pinned_iters_mgr_.PinningEnabled());
S
Stanislau Hlebik 已提交
851
  std::string last_key;
852 853
  AppendInternalKey(&last_key, ParsedInternalKey(saved_key_.GetUserKey(),
                                                 sequence_, kValueTypeForSeek));
854
  iter_.Seek(last_key);
S
Stanislau Hlebik 已提交
855 856
  RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);

857 858
  // In case read_callback presents, the value we seek to may not be visible.
  // Find the next value that's visible.
S
Stanislau Hlebik 已提交
859
  ParsedInternalKey ikey;
860
  is_blob_ = false;
861
  while (true) {
862
    if (!iter_.Valid()) {
863
      valid_ = false;
864
      return iter_.status().ok();
865 866 867 868 869
    }

    if (!ParseKey(&ikey)) {
      return false;
    }
870
    if (!user_comparator_.Equal(ikey.user_key, saved_key_.GetUserKey())) {
871 872 873 874 875 876 877 878 879 880
      // No visible values for this key, even though FindValueForCurrentKey()
      // has seen some. This is possible if we're using a tailing iterator, and
      // the entries were discarded in a compaction.
      valid_ = false;
      return true;
    }

    if (IsVisible(ikey.sequence)) {
      break;
    }
881

882
    iter_.Next();
883
  }
S
Stanislau Hlebik 已提交
884

A
Andrew Kryczka 已提交
885
  if (ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion ||
886
      range_del_agg_.ShouldDelete(
887
          ikey, RangeDelPositioningMode::kBackwardTraversal)) {
J
jorlow@chromium.org 已提交
888
    valid_ = false;
889
    return true;
S
Stanislau Hlebik 已提交
890
  }
Y
Yi Wu 已提交
891 892 893 894 895 896
  if (ikey.type == kTypeBlobIndex && !allow_blob_) {
    ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
    status_ = Status::NotSupported(
        "Encounter unexpected blob index. Please open DB with "
        "rocksdb::blob_db::BlobDB instead.");
    valid_ = false;
897
    return false;
Y
Yi Wu 已提交
898 899
  }
  if (ikey.type == kTypeValue || ikey.type == kTypeBlobIndex) {
900 901
    assert(iter_.iter()->IsValuePinned());
    pinned_value_ = iter_.value();
902
    is_blob_ = (ikey.type == kTypeBlobIndex);
A
Andrew Kryczka 已提交
903 904 905
    valid_ = true;
    return true;
  }
S
Stanislau Hlebik 已提交
906 907 908

  // kTypeMerge. We need to collect all kTypeMerge values and save them
  // in operands
909
  assert(ikey.type == kTypeMerge);
910
  current_entry_is_merged_ = true;
911
  merge_context_.Clear();
912 913
  merge_context_.PushOperand(
      iter_.value(), iter_.iter()->IsValuePinned() /* operand_pinned */);
914
  while (true) {
915
    iter_.Next();
S
Stanislau Hlebik 已提交
916

917 918
    if (!iter_.Valid()) {
      if (!iter_.status().ok()) {
919 920 921 922
        valid_ = false;
        return false;
      }
      break;
S
Stanislau Hlebik 已提交
923
    }
924 925 926
    if (!ParseKey(&ikey)) {
      return false;
    }
927
    if (!user_comparator_.Equal(ikey.user_key, saved_key_.GetUserKey())) {
928 929 930 931 932
      break;
    }

    if (ikey.type == kTypeDeletion || ikey.type == kTypeSingleDeletion ||
        range_del_agg_.ShouldDelete(
933
            ikey, RangeDelPositioningMode::kForwardTraversal)) {
934 935
      break;
    } else if (ikey.type == kTypeValue) {
936
      const Slice val = iter_.value();
937 938 939 940 941 942 943 944 945
      Status s = MergeHelper::TimedFullMerge(
          merge_operator_, saved_key_.GetUserKey(), &val,
          merge_context_.GetOperands(), &saved_value_, logger_, statistics_,
          env_, &pinned_value_, true);
      if (!s.ok()) {
        valid_ = false;
        status_ = s;
        return false;
      }
Y
Yi Wu 已提交
946
      valid_ = true;
947 948
      return true;
    } else if (ikey.type == kTypeMerge) {
949 950
      merge_context_.PushOperand(
          iter_.value(), iter_.iter()->IsValuePinned() /* operand_pinned */);
951 952 953 954 955 956 957 958 959 960 961
      PERF_COUNTER_ADD(internal_merge_count, 1);
    } else if (ikey.type == kTypeBlobIndex) {
      if (!allow_blob_) {
        ROCKS_LOG_ERROR(logger_, "Encounter unexpected blob index.");
        status_ = Status::NotSupported(
            "Encounter unexpected blob index. Please open DB with "
            "rocksdb::blob_db::BlobDB instead.");
      } else {
        status_ =
            Status::NotSupported("Blob DB does not support merge operator.");
      }
Y
Yi Wu 已提交
962
      valid_ = false;
963 964 965
      return false;
    } else {
      assert(false);
966
    }
S
Stanislau Hlebik 已提交
967 968
  }

969 970 971 972 973
  Status s = MergeHelper::TimedFullMerge(
      merge_operator_, saved_key_.GetUserKey(), nullptr,
      merge_context_.GetOperands(), &saved_value_, logger_, statistics_, env_,
      &pinned_value_, true);
  if (!s.ok()) {
Y
Yi Wu 已提交
974
    valid_ = false;
975
    status_ = s;
976
    return false;
977
  }
S
Stanislau Hlebik 已提交
978

979 980 981
  // Make sure we leave iter_ in a good state. If it's valid and we don't care
  // about prefixes, that's already good enough. Otherwise it needs to be
  // seeked to the current key.
S
sdong 已提交
982 983
  if (!expect_total_order_inner_iter() || !iter_.Valid()) {
    if (!expect_total_order_inner_iter()) {
984
      iter_.SeekForPrev(last_key);
985
    } else {
986 987 988
      iter_.Seek(last_key);
      if (!iter_.Valid() && iter_.status().ok()) {
        iter_.SeekToLast();
989 990 991
      }
    }
    RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
S
Stanislau Hlebik 已提交
992
  }
993 994 995

  valid_ = true;
  return true;
S
Stanislau Hlebik 已提交
996 997
}

998 999 1000 1001
// Move backwards until the key smaller than saved_key_.
// Changes valid_ only if return value is false.
bool DBIter::FindUserKeyBeforeSavedKey() {
  assert(status_.ok());
S
Stanislau Hlebik 已提交
1002
  size_t num_skipped = 0;
1003
  while (iter_.Valid()) {
1004 1005 1006
    ParsedInternalKey ikey;
    if (!ParseKey(&ikey)) {
      return false;
1007 1008
    }

1009
    if (user_comparator_.Compare(ikey.user_key, saved_key_.GetUserKey()) < 0) {
1010 1011 1012 1013 1014
      return true;
    }

    if (TooManyInternalKeysSkipped()) {
      return false;
S
Stanislau Hlebik 已提交
1015
    }
1016

S
Siying Dong 已提交
1017
    assert(ikey.sequence != kMaxSequenceNumber);
Y
Yi Wu 已提交
1018
    if (!IsVisible(ikey.sequence)) {
1019 1020 1021 1022
      PERF_COUNTER_ADD(internal_recent_skipped_count, 1);
    } else {
      PERF_COUNTER_ADD(internal_key_skipped_count, 1);
    }
1023

1024
    if (num_skipped >= max_skip_) {
1025 1026 1027 1028 1029 1030
      num_skipped = 0;
      IterKey last_key;
      last_key.SetInternalKey(ParsedInternalKey(
          saved_key_.GetUserKey(), kMaxSequenceNumber, kValueTypeForSeek));
      // It would be more efficient to use SeekForPrev() here, but some
      // iterators may not support it.
1031
      iter_.Seek(last_key.GetInternalKey());
1032
      RecordTick(statistics_, NUMBER_OF_RESEEKS_IN_ITERATION);
1033
      if (!iter_.Valid()) {
1034 1035 1036 1037 1038 1039
        break;
      }
    } else {
      ++num_skipped;
    }

1040
    iter_.Prev();
S
Stanislau Hlebik 已提交
1041
  }
1042

1043
  if (!iter_.status().ok()) {
1044 1045 1046 1047 1048
    valid_ = false;
    return false;
  }

  return true;
S
Stanislau Hlebik 已提交
1049 1050
}

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
bool DBIter::TooManyInternalKeysSkipped(bool increment) {
  if ((max_skippable_internal_keys_ > 0) &&
      (num_internal_keys_skipped_ > max_skippable_internal_keys_)) {
    valid_ = false;
    status_ = Status::Incomplete("Too many internal keys skipped.");
    return true;
  } else if (increment) {
    num_internal_keys_skipped_++;
  }
  return false;
}

Y
Yi Wu 已提交
1063
bool DBIter::IsVisible(SequenceNumber sequence) {
1064
  if (read_callback_ == nullptr) {
1065 1066 1067
    return sequence <= sequence_;
  } else {
    return read_callback_->IsVisible(sequence);
1068
  }
1069
}
1070

1071
void DBIter::SetSavedKeyToSeekTarget(const Slice& target) {
1072
  is_key_seqnum_zero_ = false;
1073
  SequenceNumber seq = sequence_;
1074
  saved_key_.Clear();
1075
  saved_key_.SetInternalKey(target, seq);
1076

Z
zhangjinpeng1987 已提交
1077
  if (iterate_lower_bound_ != nullptr &&
1078 1079
      user_comparator_.Compare(saved_key_.GetUserKey(), *iterate_lower_bound_) <
          0) {
1080
    // Seek key is smaller than the lower bound.
Z
zhangjinpeng1987 已提交
1081
    saved_key_.Clear();
1082
    saved_key_.SetInternalKey(*iterate_lower_bound_, seq);
Z
zhangjinpeng1987 已提交
1083
  }
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
}

void DBIter::SetSavedKeyToSeekForPrevTarget(const Slice& target) {
  is_key_seqnum_zero_ = false;
  saved_key_.Clear();
  // now saved_key is used to store internal key.
  saved_key_.SetInternalKey(target, 0 /* sequence_number */,
                            kValueTypeForSeekForPrev);

  if (iterate_upper_bound_ != nullptr &&
      user_comparator_.Compare(saved_key_.GetUserKey(),
                               *iterate_upper_bound_) >= 0) {
    saved_key_.Clear();
    saved_key_.SetInternalKey(*iterate_upper_bound_, kMaxSequenceNumber);
  }
}

void DBIter::Seek(const Slice& target) {
  PERF_CPU_TIMER_GUARD(iter_seek_cpu_nanos, env_);
  StopWatch sw(env_, statistics_, DB_SEEK);

#ifndef ROCKSDB_LITE
  if (db_impl_ != nullptr && cfd_ != nullptr) {
    db_impl_->TraceIteratorSeek(cfd_->GetID(), target);
  }
#endif  // ROCKSDB_LITE

  status_ = Status::OK();
  ReleaseTempPinnedData();
  ResetInternalKeysSkippedCounter();
Z
zhangjinpeng1987 已提交
1114

1115
  // Seek the inner iterator based on the target key.
1116 1117
  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1118 1119

    SetSavedKeyToSeekTarget(target);
1120
    iter_.Seek(saved_key_.GetInternalKey());
1121

1122
    range_del_agg_.InvalidateRangeDelMapPositions();
1123
    RecordTick(statistics_, NUMBER_DB_SEEK);
1124
  }
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  if (!iter_.Valid()) {
    valid_ = false;
    return;
  }
  direction_ = kForward;

  // Now the inner iterator is placed to the target position. From there,
  // we need to find out the next key that is visible to the user.
  //
  ClearSavedValue();
  if (prefix_same_as_start_) {
    // The case where the iterator needs to be invalidated if it has exausted
    // keys within the same prefix of the seek key.
    assert(prefix_extractor_ != nullptr);
    Slice target_prefix;
    target_prefix = prefix_extractor_->Transform(target);
    FindNextUserEntry(false /* not skipping saved_key */,
                      &target_prefix /* prefix */);
    if (valid_) {
      // Remember the prefix of the seek key for the future Prev() call to
      // check.
      prefix_.SetUserKey(target_prefix);
M
Manuel Ung 已提交
1147
    }
J
jorlow@chromium.org 已提交
1148
  } else {
1149 1150 1151 1152
    FindNextUserEntry(false /* not skipping saved_key */, nullptr);
  }
  if (!valid_) {
    return;
J
jorlow@chromium.org 已提交
1153
  }
1154

1155 1156 1157 1158 1159
  // Updating stats and perf context counters.
  if (statistics_ != nullptr) {
    // Decrement since we don't want to count this key as skipped
    RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
    RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1160
  }
1161
  PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
J
jorlow@chromium.org 已提交
1162
}
J
jorlow@chromium.org 已提交
1163

A
Aaron Gao 已提交
1164
void DBIter::SeekForPrev(const Slice& target) {
1165
  PERF_CPU_TIMER_GUARD(iter_seek_cpu_nanos, env_);
A
Aaron Gao 已提交
1166
  StopWatch sw(env_, statistics_, DB_SEEK);
1167 1168 1169 1170 1171 1172 1173

#ifndef ROCKSDB_LITE
  if (db_impl_ != nullptr && cfd_ != nullptr) {
    db_impl_->TraceIteratorSeekForPrev(cfd_->GetID(), target);
  }
#endif  // ROCKSDB_LITE

1174
  status_ = Status::OK();
A
Aaron Gao 已提交
1175
  ReleaseTempPinnedData();
1176
  ResetInternalKeysSkippedCounter();
Z
zhangjinpeng1987 已提交
1177

1178
  // Seek the inner iterator based on the target key.
A
Aaron Gao 已提交
1179 1180
  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1181
    SetSavedKeyToSeekForPrevTarget(target);
1182
    iter_.SeekForPrev(saved_key_.GetInternalKey());
1183
    range_del_agg_.InvalidateRangeDelMapPositions();
1184
    RecordTick(statistics_, NUMBER_DB_SEEK);
A
Aaron Gao 已提交
1185
  }
1186 1187 1188
  if (!iter_.Valid()) {
    valid_ = false;
    return;
1189
  }
1190
  direction_ = kReverse;
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  // Now the inner iterator is placed to the target position. From there,
  // we need to find out the first key that is visible to the user in the
  // backward direction.
  ClearSavedValue();
  if (prefix_same_as_start_) {
    // The case where the iterator needs to be invalidated if it has exausted
    // keys within the same prefix of the seek key.
    assert(prefix_extractor_ != nullptr);
    Slice target_prefix;
    target_prefix = prefix_extractor_->Transform(target);
    PrevInternal(&target_prefix);
    if (valid_) {
      // Remember the prefix of the seek key for the future Prev() call to
      // check.
      prefix_.SetUserKey(target_prefix);
A
Aaron Gao 已提交
1207 1208
    }
  } else {
1209
    PrevInternal(nullptr);
A
Aaron Gao 已提交
1210
  }
1211 1212 1213 1214 1215 1216

  // Report stats and perf context.
  if (statistics_ != nullptr && valid_) {
    RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
    RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
    PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
A
Aaron Gao 已提交
1217 1218 1219
  }
}

J
jorlow@chromium.org 已提交
1220
void DBIter::SeekToFirst() {
1221 1222 1223 1224
  if (iterate_lower_bound_ != nullptr) {
    Seek(*iterate_lower_bound_);
    return;
  }
1225
  PERF_CPU_TIMER_GUARD(iter_seek_cpu_nanos, env_);
1226 1227
  // Don't use iter_::Seek() if we set a prefix extractor
  // because prefix seek will be used.
S
sdong 已提交
1228
  if (!expect_total_order_inner_iter()) {
1229 1230 1231
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
  status_ = Status::OK();
J
jorlow@chromium.org 已提交
1232
  direction_ = kForward;
1233
  ReleaseTempPinnedData();
1234
  ResetInternalKeysSkippedCounter();
J
jorlow@chromium.org 已提交
1235
  ClearSavedValue();
1236
  is_key_seqnum_zero_ = false;
1237 1238 1239

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1240
    iter_.SeekToFirst();
1241
    range_del_agg_.InvalidateRangeDelMapPositions();
1242 1243
  }

M
Manuel Ung 已提交
1244
  RecordTick(statistics_, NUMBER_DB_SEEK);
1245
  if (iter_.Valid()) {
1246
    saved_key_.SetUserKey(
1247 1248
        ExtractUserKey(iter_.key()),
        !iter_.iter()->IsKeyPinned() || !pin_thru_lifetime_ /* copy */);
1249 1250
    FindNextUserEntry(false /* not skipping saved_key */,
                      nullptr /* no prefix check */);
M
Manuel Ung 已提交
1251 1252 1253 1254
    if (statistics_ != nullptr) {
      if (valid_) {
        RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
        RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1255
        PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1256 1257
      }
    }
J
jorlow@chromium.org 已提交
1258 1259
  } else {
    valid_ = false;
J
jorlow@chromium.org 已提交
1260
  }
1261 1262 1263
  if (valid_ && prefix_same_as_start_) {
    assert(prefix_extractor_ != nullptr);
    prefix_.SetUserKey(prefix_extractor_->Transform(saved_key_.GetUserKey()));
1264
  }
J
jorlow@chromium.org 已提交
1265 1266
}

J
jorlow@chromium.org 已提交
1267
void DBIter::SeekToLast() {
1268 1269 1270
  if (iterate_upper_bound_ != nullptr) {
    // Seek to last key strictly less than ReadOptions.iterate_upper_bound.
    SeekForPrev(*iterate_upper_bound_);
1271
    if (Valid() && user_comparator_.Equal(*iterate_upper_bound_, key())) {
1272
      ReleaseTempPinnedData();
1273
      PrevInternal(nullptr);
1274 1275 1276 1277
    }
    return;
  }

1278
  PERF_CPU_TIMER_GUARD(iter_seek_cpu_nanos, env_);
S
Stanislau Hlebik 已提交
1279
  // Don't use iter_::Seek() if we set a prefix extractor
1280
  // because prefix seek will be used.
S
sdong 已提交
1281
  if (!expect_total_order_inner_iter()) {
S
Stanislau Hlebik 已提交
1282 1283
    max_skip_ = std::numeric_limits<uint64_t>::max();
  }
1284
  status_ = Status::OK();
J
jorlow@chromium.org 已提交
1285
  direction_ = kReverse;
1286
  ReleaseTempPinnedData();
1287
  ResetInternalKeysSkippedCounter();
J
jorlow@chromium.org 已提交
1288
  ClearSavedValue();
1289
  is_key_seqnum_zero_ = false;
1290 1291 1292

  {
    PERF_TIMER_GUARD(seek_internal_seek_time);
1293
    iter_.SeekToLast();
1294
    range_del_agg_.InvalidateRangeDelMapPositions();
1295
  }
1296
  PrevInternal(nullptr);
M
Manuel Ung 已提交
1297 1298 1299 1300 1301
  if (statistics_ != nullptr) {
    RecordTick(statistics_, NUMBER_DB_SEEK);
    if (valid_) {
      RecordTick(statistics_, NUMBER_DB_SEEK_FOUND);
      RecordTick(statistics_, ITER_BYTES_READ, key().size() + value().size());
1302
      PERF_COUNTER_ADD(iter_read_bytes, key().size() + value().size());
M
Manuel Ung 已提交
1303 1304
    }
  }
1305 1306 1307
  if (valid_ && prefix_same_as_start_) {
    assert(prefix_extractor_ != nullptr);
    prefix_.SetUserKey(prefix_extractor_->Transform(saved_key_.GetUserKey()));
1308
  }
J
jorlow@chromium.org 已提交
1309 1310
}

1311 1312
Iterator* NewDBIterator(Env* env, const ReadOptions& read_options,
                        const ImmutableCFOptions& cf_options,
1313
                        const MutableCFOptions& mutable_cf_options,
1314 1315 1316
                        const Comparator* user_key_comparator,
                        InternalIterator* internal_iter,
                        const SequenceNumber& sequence,
Y
Yi Wu 已提交
1317
                        uint64_t max_sequential_skip_in_iterations,
1318 1319 1320 1321 1322 1323
                        ReadCallback* read_callback, DBImpl* db_impl,
                        ColumnFamilyData* cfd, bool allow_blob) {
  DBIter* db_iter = new DBIter(
      env, read_options, cf_options, mutable_cf_options, user_key_comparator,
      internal_iter, sequence, false, max_sequential_skip_in_iterations,
      read_callback, db_impl, cfd, allow_blob);
1324
  return db_iter;
1325 1326
}

1327
}  // namespace rocksdb