1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/container/internal/hashtablez_sampler.h"
16
17 #include <atomic>
18 #include <cassert>
19 #include <cmath>
20 #include <functional>
21 #include <limits>
22
23 #include "absl/base/attributes.h"
24 #include "absl/base/config.h"
25 #include "absl/debugging/stacktrace.h"
26 #include "absl/memory/memory.h"
27 #include "absl/profiling/internal/exponential_biased.h"
28 #include "absl/profiling/internal/sample_recorder.h"
29 #include "absl/synchronization/mutex.h"
30 #include "absl/utility/utility.h"
31
32 namespace absl {
33 ABSL_NAMESPACE_BEGIN
34 namespace container_internal {
35
36 #ifdef ABSL_INTERNAL_NEED_REDUNDANT_CONSTEXPR_DECL
37 constexpr int HashtablezInfo::kMaxStackDepth;
38 #endif
39
40 namespace {
41 ABSL_CONST_INIT std::atomic<bool> g_hashtablez_enabled{
42 false
43 };
44 ABSL_CONST_INIT std::atomic<int32_t> g_hashtablez_sample_parameter{1 << 10};
45 std::atomic<HashtablezConfigListener> g_hashtablez_config_listener{nullptr};
46
47 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
48 ABSL_PER_THREAD_TLS_KEYWORD absl::profiling_internal::ExponentialBiased
49 g_exponential_biased_generator;
50 #endif
51
TriggerHashtablezConfigListener()52 void TriggerHashtablezConfigListener() {
53 auto* listener = g_hashtablez_config_listener.load(std::memory_order_acquire);
54 if (listener != nullptr) listener();
55 }
56
57 } // namespace
58
59 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
60 ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample = {0, 0};
61 #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
62
GlobalHashtablezSampler()63 HashtablezSampler& GlobalHashtablezSampler() {
64 static auto* sampler = new HashtablezSampler();
65 return *sampler;
66 }
67
68 HashtablezInfo::HashtablezInfo() = default;
69 HashtablezInfo::~HashtablezInfo() = default;
70
PrepareForSampling(int64_t stride,size_t inline_element_size_value)71 void HashtablezInfo::PrepareForSampling(int64_t stride,
72 size_t inline_element_size_value) {
73 capacity.store(0, std::memory_order_relaxed);
74 size.store(0, std::memory_order_relaxed);
75 num_erases.store(0, std::memory_order_relaxed);
76 num_rehashes.store(0, std::memory_order_relaxed);
77 max_probe_length.store(0, std::memory_order_relaxed);
78 total_probe_length.store(0, std::memory_order_relaxed);
79 hashes_bitwise_or.store(0, std::memory_order_relaxed);
80 hashes_bitwise_and.store(~size_t{}, std::memory_order_relaxed);
81 hashes_bitwise_xor.store(0, std::memory_order_relaxed);
82 max_reserve.store(0, std::memory_order_relaxed);
83
84 create_time = absl::Now();
85 weight = stride;
86 // The inliner makes hardcoded skip_count difficult (especially when combined
87 // with LTO). We use the ability to exclude stacks by regex when encoding
88 // instead.
89 depth = absl::GetStackTrace(stack, HashtablezInfo::kMaxStackDepth,
90 /* skip_count= */ 0);
91 inline_element_size = inline_element_size_value;
92 }
93
ShouldForceSampling()94 static bool ShouldForceSampling() {
95 enum ForceState {
96 kDontForce,
97 kForce,
98 kUninitialized
99 };
100 ABSL_CONST_INIT static std::atomic<ForceState> global_state{
101 kUninitialized};
102 ForceState state = global_state.load(std::memory_order_relaxed);
103 if (ABSL_PREDICT_TRUE(state == kDontForce)) return false;
104
105 if (state == kUninitialized) {
106 state = ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)()
107 ? kForce
108 : kDontForce;
109 global_state.store(state, std::memory_order_relaxed);
110 }
111 return state == kForce;
112 }
113
SampleSlow(SamplingState & next_sample,size_t inline_element_size)114 HashtablezInfo* SampleSlow(SamplingState& next_sample,
115 size_t inline_element_size) {
116 if (ABSL_PREDICT_FALSE(ShouldForceSampling())) {
117 next_sample.next_sample = 1;
118 const int64_t old_stride = exchange(next_sample.sample_stride, 1);
119 HashtablezInfo* result =
120 GlobalHashtablezSampler().Register(old_stride, inline_element_size);
121 return result;
122 }
123
124 #if !defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
125 next_sample = {
126 std::numeric_limits<int64_t>::max(),
127 std::numeric_limits<int64_t>::max(),
128 };
129 return nullptr;
130 #else
131 bool first = next_sample.next_sample < 0;
132
133 const int64_t next_stride = g_exponential_biased_generator.GetStride(
134 g_hashtablez_sample_parameter.load(std::memory_order_relaxed));
135
136 next_sample.next_sample = next_stride;
137 const int64_t old_stride = exchange(next_sample.sample_stride, next_stride);
138 // Small values of interval are equivalent to just sampling next time.
139 ABSL_ASSERT(next_stride >= 1);
140
141 // g_hashtablez_enabled can be dynamically flipped, we need to set a threshold
142 // low enough that we will start sampling in a reasonable time, so we just use
143 // the default sampling rate.
144 if (!g_hashtablez_enabled.load(std::memory_order_relaxed)) return nullptr;
145
146 // We will only be negative on our first count, so we should just retry in
147 // that case.
148 if (first) {
149 if (ABSL_PREDICT_TRUE(--next_sample.next_sample > 0)) return nullptr;
150 return SampleSlow(next_sample, inline_element_size);
151 }
152
153 return GlobalHashtablezSampler().Register(old_stride, inline_element_size);
154 #endif
155 }
156
UnsampleSlow(HashtablezInfo * info)157 void UnsampleSlow(HashtablezInfo* info) {
158 GlobalHashtablezSampler().Unregister(info);
159 }
160
RecordInsertSlow(HashtablezInfo * info,size_t hash,size_t distance_from_desired)161 void RecordInsertSlow(HashtablezInfo* info, size_t hash,
162 size_t distance_from_desired) {
163 // SwissTables probe in groups of 16, so scale this to count items probes and
164 // not offset from desired.
165 size_t probe_length = distance_from_desired;
166 #ifdef ABSL_INTERNAL_HAVE_SSE2
167 probe_length /= 16;
168 #else
169 probe_length /= 8;
170 #endif
171
172 info->hashes_bitwise_and.fetch_and(hash, std::memory_order_relaxed);
173 info->hashes_bitwise_or.fetch_or(hash, std::memory_order_relaxed);
174 info->hashes_bitwise_xor.fetch_xor(hash, std::memory_order_relaxed);
175 info->max_probe_length.store(
176 std::max(info->max_probe_length.load(std::memory_order_relaxed),
177 probe_length),
178 std::memory_order_relaxed);
179 info->total_probe_length.fetch_add(probe_length, std::memory_order_relaxed);
180 info->size.fetch_add(1, std::memory_order_relaxed);
181 }
182
SetHashtablezConfigListener(HashtablezConfigListener l)183 void SetHashtablezConfigListener(HashtablezConfigListener l) {
184 g_hashtablez_config_listener.store(l, std::memory_order_release);
185 }
186
IsHashtablezEnabled()187 bool IsHashtablezEnabled() {
188 return g_hashtablez_enabled.load(std::memory_order_acquire);
189 }
190
SetHashtablezEnabled(bool enabled)191 void SetHashtablezEnabled(bool enabled) {
192 SetHashtablezEnabledInternal(enabled);
193 TriggerHashtablezConfigListener();
194 }
195
SetHashtablezEnabledInternal(bool enabled)196 void SetHashtablezEnabledInternal(bool enabled) {
197 g_hashtablez_enabled.store(enabled, std::memory_order_release);
198 }
199
GetHashtablezSampleParameter()200 int32_t GetHashtablezSampleParameter() {
201 return g_hashtablez_sample_parameter.load(std::memory_order_acquire);
202 }
203
SetHashtablezSampleParameter(int32_t rate)204 void SetHashtablezSampleParameter(int32_t rate) {
205 SetHashtablezSampleParameterInternal(rate);
206 TriggerHashtablezConfigListener();
207 }
208
SetHashtablezSampleParameterInternal(int32_t rate)209 void SetHashtablezSampleParameterInternal(int32_t rate) {
210 if (rate > 0) {
211 g_hashtablez_sample_parameter.store(rate, std::memory_order_release);
212 } else {
213 ABSL_RAW_LOG(ERROR, "Invalid hashtablez sample rate: %lld",
214 static_cast<long long>(rate)); // NOLINT(runtime/int)
215 }
216 }
217
GetHashtablezMaxSamples()218 size_t GetHashtablezMaxSamples() {
219 return GlobalHashtablezSampler().GetMaxSamples();
220 }
221
SetHashtablezMaxSamples(size_t max)222 void SetHashtablezMaxSamples(size_t max) {
223 SetHashtablezMaxSamplesInternal(max);
224 TriggerHashtablezConfigListener();
225 }
226
SetHashtablezMaxSamplesInternal(size_t max)227 void SetHashtablezMaxSamplesInternal(size_t max) {
228 if (max > 0) {
229 GlobalHashtablezSampler().SetMaxSamples(max);
230 } else {
231 ABSL_RAW_LOG(ERROR, "Invalid hashtablez max samples: 0");
232 }
233 }
234
235 } // namespace container_internal
236 ABSL_NAMESPACE_END
237 } // namespace absl
238