1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 
6 #include "monitoring/instrumented_mutex.h"
7 #include "monitoring/perf_context_imp.h"
8 #include "monitoring/thread_status_util.h"
9 #include "test_util/sync_point.h"
10 
11 namespace ROCKSDB_NAMESPACE {
12 namespace {
stats_for_report(Env * env,Statistics * stats)13 Statistics* stats_for_report(Env* env, Statistics* stats) {
14   if (env != nullptr && stats != nullptr &&
15       stats->get_stats_level() > kExceptTimeForMutex) {
16     return stats;
17   } else {
18     return nullptr;
19   }
20 }
21 }  // namespace
22 
Lock()23 void InstrumentedMutex::Lock() {
24   PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(
25       db_mutex_lock_nanos, stats_code_ == DB_MUTEX_WAIT_MICROS,
26       stats_for_report(env_, stats_), stats_code_);
27   LockInternal();
28 }
29 
LockInternal()30 void InstrumentedMutex::LockInternal() {
31 #ifndef NDEBUG
32   ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT);
33 #endif
34   mutex_.Lock();
35 }
36 
Wait()37 void InstrumentedCondVar::Wait() {
38   PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(
39       db_condition_wait_nanos, stats_code_ == DB_MUTEX_WAIT_MICROS,
40       stats_for_report(env_, stats_), stats_code_);
41   WaitInternal();
42 }
43 
WaitInternal()44 void InstrumentedCondVar::WaitInternal() {
45 #ifndef NDEBUG
46   ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT);
47 #endif
48   cond_.Wait();
49 }
50 
TimedWait(uint64_t abs_time_us)51 bool InstrumentedCondVar::TimedWait(uint64_t abs_time_us) {
52   PERF_CONDITIONAL_TIMER_FOR_MUTEX_GUARD(
53       db_condition_wait_nanos, stats_code_ == DB_MUTEX_WAIT_MICROS,
54       stats_for_report(env_, stats_), stats_code_);
55   return TimedWaitInternal(abs_time_us);
56 }
57 
TimedWaitInternal(uint64_t abs_time_us)58 bool InstrumentedCondVar::TimedWaitInternal(uint64_t abs_time_us) {
59 #ifndef NDEBUG
60   ThreadStatusUtil::TEST_StateDelay(ThreadStatus::STATE_MUTEX_WAIT);
61 #endif
62 
63   TEST_SYNC_POINT_CALLBACK("InstrumentedCondVar::TimedWaitInternal",
64                            &abs_time_us);
65 
66   return cond_.TimedWait(abs_time_us);
67 }
68 
69 }  // namespace ROCKSDB_NAMESPACE
70