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/internal/exponential_biased.h"
25 #include "absl/container/internal/have_sse.h"
26 #include "absl/debugging/stacktrace.h"
27 #include "absl/memory/memory.h"
28 #include "absl/synchronization/mutex.h"
29
30 namespace absl {
31 ABSL_NAMESPACE_BEGIN
32 namespace container_internal {
33 constexpr int HashtablezInfo::kMaxStackDepth;
34
35 namespace {
36 ABSL_CONST_INIT std::atomic<bool> g_hashtablez_enabled{
37 false
38 };
39 ABSL_CONST_INIT std::atomic<int32_t> g_hashtablez_sample_parameter{1 << 10};
40 ABSL_CONST_INIT std::atomic<int32_t> g_hashtablez_max_samples{1 << 20};
41
42 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
43 ABSL_PER_THREAD_TLS_KEYWORD absl::base_internal::ExponentialBiased
44 g_exponential_biased_generator;
45 #endif
46
47 } // namespace
48
49 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
50 ABSL_PER_THREAD_TLS_KEYWORD int64_t global_next_sample = 0;
51 #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
52
Global()53 HashtablezSampler& HashtablezSampler::Global() {
54 static auto* sampler = new HashtablezSampler();
55 return *sampler;
56 }
57
SetDisposeCallback(DisposeCallback f)58 HashtablezSampler::DisposeCallback HashtablezSampler::SetDisposeCallback(
59 DisposeCallback f) {
60 return dispose_.exchange(f, std::memory_order_relaxed);
61 }
62
HashtablezInfo()63 HashtablezInfo::HashtablezInfo() { PrepareForSampling(); }
64 HashtablezInfo::~HashtablezInfo() = default;
65
PrepareForSampling()66 void HashtablezInfo::PrepareForSampling() {
67 capacity.store(0, std::memory_order_relaxed);
68 size.store(0, std::memory_order_relaxed);
69 num_erases.store(0, std::memory_order_relaxed);
70 max_probe_length.store(0, std::memory_order_relaxed);
71 total_probe_length.store(0, std::memory_order_relaxed);
72 hashes_bitwise_or.store(0, std::memory_order_relaxed);
73 hashes_bitwise_and.store(~size_t{}, std::memory_order_relaxed);
74
75 create_time = absl::Now();
76 // The inliner makes hardcoded skip_count difficult (especially when combined
77 // with LTO). We use the ability to exclude stacks by regex when encoding
78 // instead.
79 depth = absl::GetStackTrace(stack, HashtablezInfo::kMaxStackDepth,
80 /* skip_count= */ 0);
81 dead = nullptr;
82 }
83
HashtablezSampler()84 HashtablezSampler::HashtablezSampler()
85 : dropped_samples_(0), size_estimate_(0), all_(nullptr), dispose_(nullptr) {
86 absl::MutexLock l(&graveyard_.init_mu);
87 graveyard_.dead = &graveyard_;
88 }
89
~HashtablezSampler()90 HashtablezSampler::~HashtablezSampler() {
91 HashtablezInfo* s = all_.load(std::memory_order_acquire);
92 while (s != nullptr) {
93 HashtablezInfo* next = s->next;
94 delete s;
95 s = next;
96 }
97 }
98
PushNew(HashtablezInfo * sample)99 void HashtablezSampler::PushNew(HashtablezInfo* sample) {
100 sample->next = all_.load(std::memory_order_relaxed);
101 while (!all_.compare_exchange_weak(sample->next, sample,
102 std::memory_order_release,
103 std::memory_order_relaxed)) {
104 }
105 }
106
PushDead(HashtablezInfo * sample)107 void HashtablezSampler::PushDead(HashtablezInfo* sample) {
108 if (auto* dispose = dispose_.load(std::memory_order_relaxed)) {
109 dispose(*sample);
110 }
111
112 absl::MutexLock graveyard_lock(&graveyard_.init_mu);
113 absl::MutexLock sample_lock(&sample->init_mu);
114 sample->dead = graveyard_.dead;
115 graveyard_.dead = sample;
116 }
117
PopDead()118 HashtablezInfo* HashtablezSampler::PopDead() {
119 absl::MutexLock graveyard_lock(&graveyard_.init_mu);
120
121 // The list is circular, so eventually it collapses down to
122 // graveyard_.dead == &graveyard_
123 // when it is empty.
124 HashtablezInfo* sample = graveyard_.dead;
125 if (sample == &graveyard_) return nullptr;
126
127 absl::MutexLock sample_lock(&sample->init_mu);
128 graveyard_.dead = sample->dead;
129 sample->PrepareForSampling();
130 return sample;
131 }
132
Register()133 HashtablezInfo* HashtablezSampler::Register() {
134 int64_t size = size_estimate_.fetch_add(1, std::memory_order_relaxed);
135 if (size > g_hashtablez_max_samples.load(std::memory_order_relaxed)) {
136 size_estimate_.fetch_sub(1, std::memory_order_relaxed);
137 dropped_samples_.fetch_add(1, std::memory_order_relaxed);
138 return nullptr;
139 }
140
141 HashtablezInfo* sample = PopDead();
142 if (sample == nullptr) {
143 // Resurrection failed. Hire a new warlock.
144 sample = new HashtablezInfo();
145 PushNew(sample);
146 }
147
148 return sample;
149 }
150
Unregister(HashtablezInfo * sample)151 void HashtablezSampler::Unregister(HashtablezInfo* sample) {
152 PushDead(sample);
153 size_estimate_.fetch_sub(1, std::memory_order_relaxed);
154 }
155
Iterate(const std::function<void (const HashtablezInfo & stack)> & f)156 int64_t HashtablezSampler::Iterate(
157 const std::function<void(const HashtablezInfo& stack)>& f) {
158 HashtablezInfo* s = all_.load(std::memory_order_acquire);
159 while (s != nullptr) {
160 absl::MutexLock l(&s->init_mu);
161 if (s->dead == nullptr) {
162 f(*s);
163 }
164 s = s->next;
165 }
166
167 return dropped_samples_.load(std::memory_order_relaxed);
168 }
169
ShouldForceSampling()170 static bool ShouldForceSampling() {
171 enum ForceState {
172 kDontForce,
173 kForce,
174 kUninitialized
175 };
176 ABSL_CONST_INIT static std::atomic<ForceState> global_state{
177 kUninitialized};
178 ForceState state = global_state.load(std::memory_order_relaxed);
179 if (ABSL_PREDICT_TRUE(state == kDontForce)) return false;
180
181 if (state == kUninitialized) {
182 state = AbslContainerInternalSampleEverything() ? kForce : kDontForce;
183 global_state.store(state, std::memory_order_relaxed);
184 }
185 return state == kForce;
186 }
187
SampleSlow(int64_t * next_sample)188 HashtablezInfo* SampleSlow(int64_t* next_sample) {
189 if (ABSL_PREDICT_FALSE(ShouldForceSampling())) {
190 *next_sample = 1;
191 return HashtablezSampler::Global().Register();
192 }
193
194 #if !defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
195 *next_sample = std::numeric_limits<int64_t>::max();
196 return nullptr;
197 #else
198 bool first = *next_sample < 0;
199 *next_sample = g_exponential_biased_generator.GetStride(
200 g_hashtablez_sample_parameter.load(std::memory_order_relaxed));
201 // Small values of interval are equivalent to just sampling next time.
202 ABSL_ASSERT(*next_sample >= 1);
203
204 // g_hashtablez_enabled can be dynamically flipped, we need to set a threshold
205 // low enough that we will start sampling in a reasonable time, so we just use
206 // the default sampling rate.
207 if (!g_hashtablez_enabled.load(std::memory_order_relaxed)) return nullptr;
208
209 // We will only be negative on our first count, so we should just retry in
210 // that case.
211 if (first) {
212 if (ABSL_PREDICT_TRUE(--*next_sample > 0)) return nullptr;
213 return SampleSlow(next_sample);
214 }
215
216 return HashtablezSampler::Global().Register();
217 #endif
218 }
219
UnsampleSlow(HashtablezInfo * info)220 void UnsampleSlow(HashtablezInfo* info) {
221 HashtablezSampler::Global().Unregister(info);
222 }
223
RecordInsertSlow(HashtablezInfo * info,size_t hash,size_t distance_from_desired)224 void RecordInsertSlow(HashtablezInfo* info, size_t hash,
225 size_t distance_from_desired) {
226 // SwissTables probe in groups of 16, so scale this to count items probes and
227 // not offset from desired.
228 size_t probe_length = distance_from_desired;
229 #if SWISSTABLE_HAVE_SSE2
230 probe_length /= 16;
231 #else
232 probe_length /= 8;
233 #endif
234
235 info->hashes_bitwise_and.fetch_and(hash, std::memory_order_relaxed);
236 info->hashes_bitwise_or.fetch_or(hash, std::memory_order_relaxed);
237 info->max_probe_length.store(
238 std::max(info->max_probe_length.load(std::memory_order_relaxed),
239 probe_length),
240 std::memory_order_relaxed);
241 info->total_probe_length.fetch_add(probe_length, std::memory_order_relaxed);
242 info->size.fetch_add(1, std::memory_order_relaxed);
243 }
244
SetHashtablezEnabled(bool enabled)245 void SetHashtablezEnabled(bool enabled) {
246 g_hashtablez_enabled.store(enabled, std::memory_order_release);
247 }
248
SetHashtablezSampleParameter(int32_t rate)249 void SetHashtablezSampleParameter(int32_t rate) {
250 if (rate > 0) {
251 g_hashtablez_sample_parameter.store(rate, std::memory_order_release);
252 } else {
253 ABSL_RAW_LOG(ERROR, "Invalid hashtablez sample rate: %lld",
254 static_cast<long long>(rate)); // NOLINT(runtime/int)
255 }
256 }
257
SetHashtablezMaxSamples(int32_t max)258 void SetHashtablezMaxSamples(int32_t max) {
259 if (max > 0) {
260 g_hashtablez_max_samples.store(max, std::memory_order_release);
261 } else {
262 ABSL_RAW_LOG(ERROR, "Invalid hashtablez max samples: %lld",
263 static_cast<long long>(max)); // NOLINT(runtime/int)
264 }
265 }
266
267 } // namespace container_internal
268 ABSL_NAMESPACE_END
269 } // namespace absl
270