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 // -----------------------------------------------------------------------------
16 // File: hashtablez_sampler.h
17 // -----------------------------------------------------------------------------
18 //
19 // This header file defines the API for a low level library to sample hashtables
20 // and collect runtime statistics about them.
21 //
22 // `HashtablezSampler` controls the lifecycle of `HashtablezInfo` objects which
23 // store information about a single sample.
24 //
25 // `Record*` methods store information into samples.
26 // `Sample()` and `Unsample()` make use of a single global sampler with
27 // properties controlled by the flags hashtablez_enabled,
28 // hashtablez_sample_rate, and hashtablez_max_samples.
29 //
30 // WARNING
31 //
32 // Using this sampling API may cause sampled Swiss tables to use the global
33 // allocator (operator `new`) in addition to any custom allocator. If you
34 // are using a table in an unusual circumstance where allocation or calling a
35 // linux syscall is unacceptable, this could interfere.
36 //
37 // This utility is internal-only. Use at your own risk.
38
39 #ifndef ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
40 #define ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
41
42 #include <atomic>
43 #include <functional>
44 #include <memory>
45 #include <vector>
46
47 #include "absl/base/internal/per_thread_tls.h"
48 #include "absl/base/optimization.h"
49 #include "absl/container/internal/have_sse.h"
50 #include "absl/synchronization/mutex.h"
51 #include "absl/utility/utility.h"
52
53 namespace absl {
54 ABSL_NAMESPACE_BEGIN
55 namespace container_internal {
56
57 // Stores information about a sampled hashtable. All mutations to this *must*
58 // be made through `Record*` functions below. All reads from this *must* only
59 // occur in the callback to `HashtablezSampler::Iterate`.
60 struct HashtablezInfo {
61 // Constructs the object but does not fill in any fields.
62 HashtablezInfo();
63 ~HashtablezInfo();
64 HashtablezInfo(const HashtablezInfo&) = delete;
65 HashtablezInfo& operator=(const HashtablezInfo&) = delete;
66
67 // Puts the object into a clean state, fills in the logically `const` members,
68 // blocking for any readers that are currently sampling the object.
69 void PrepareForSampling() ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu);
70
71 // These fields are mutated by the various Record* APIs and need to be
72 // thread-safe.
73 std::atomic<size_t> capacity;
74 std::atomic<size_t> size;
75 std::atomic<size_t> num_erases;
76 std::atomic<size_t> num_rehashes;
77 std::atomic<size_t> max_probe_length;
78 std::atomic<size_t> total_probe_length;
79 std::atomic<size_t> hashes_bitwise_or;
80 std::atomic<size_t> hashes_bitwise_and;
81 std::atomic<size_t> hashes_bitwise_xor;
82
83 // `HashtablezSampler` maintains intrusive linked lists for all samples. See
84 // comments on `HashtablezSampler::all_` for details on these. `init_mu`
85 // guards the ability to restore the sample to a pristine state. This
86 // prevents races with sampling and resurrecting an object.
87 absl::Mutex init_mu;
88 HashtablezInfo* next;
89 HashtablezInfo* dead ABSL_GUARDED_BY(init_mu);
90
91 // All of the fields below are set by `PrepareForSampling`, they must not be
92 // mutated in `Record*` functions. They are logically `const` in that sense.
93 // These are guarded by init_mu, but that is not externalized to clients, who
94 // can only read them during `HashtablezSampler::Iterate` which will hold the
95 // lock.
96 static constexpr int kMaxStackDepth = 64;
97 absl::Time create_time;
98 int32_t depth;
99 void* stack[kMaxStackDepth];
100 };
101
RecordRehashSlow(HashtablezInfo * info,size_t total_probe_length)102 inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
103 #if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
104 total_probe_length /= 16;
105 #else
106 total_probe_length /= 8;
107 #endif
108 info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
109 info->num_erases.store(0, std::memory_order_relaxed);
110 // There is only one concurrent writer, so `load` then `store` is sufficient
111 // instead of using `fetch_add`.
112 info->num_rehashes.store(
113 1 + info->num_rehashes.load(std::memory_order_relaxed),
114 std::memory_order_relaxed);
115 }
116
RecordStorageChangedSlow(HashtablezInfo * info,size_t size,size_t capacity)117 inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
118 size_t capacity) {
119 info->size.store(size, std::memory_order_relaxed);
120 info->capacity.store(capacity, std::memory_order_relaxed);
121 if (size == 0) {
122 // This is a clear, reset the total/num_erases too.
123 info->total_probe_length.store(0, std::memory_order_relaxed);
124 info->num_erases.store(0, std::memory_order_relaxed);
125 }
126 }
127
128 void RecordInsertSlow(HashtablezInfo* info, size_t hash,
129 size_t distance_from_desired);
130
RecordEraseSlow(HashtablezInfo * info)131 inline void RecordEraseSlow(HashtablezInfo* info) {
132 info->size.fetch_sub(1, std::memory_order_relaxed);
133 // There is only one concurrent writer, so `load` then `store` is sufficient
134 // instead of using `fetch_add`.
135 info->num_erases.store(
136 1 + info->num_erases.load(std::memory_order_relaxed),
137 std::memory_order_relaxed);
138 }
139
140 HashtablezInfo* SampleSlow(int64_t* next_sample);
141 void UnsampleSlow(HashtablezInfo* info);
142
143 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
144 #error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
145 #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
146
147 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
148 class HashtablezInfoHandle {
149 public:
HashtablezInfoHandle()150 explicit HashtablezInfoHandle() : info_(nullptr) {}
HashtablezInfoHandle(HashtablezInfo * info)151 explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
~HashtablezInfoHandle()152 ~HashtablezInfoHandle() {
153 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
154 UnsampleSlow(info_);
155 }
156
157 HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
158 HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
159
HashtablezInfoHandle(HashtablezInfoHandle && o)160 HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
161 : info_(absl::exchange(o.info_, nullptr)) {}
162 HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
163 if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
164 UnsampleSlow(info_);
165 }
166 info_ = absl::exchange(o.info_, nullptr);
167 return *this;
168 }
169
RecordStorageChanged(size_t size,size_t capacity)170 inline void RecordStorageChanged(size_t size, size_t capacity) {
171 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
172 RecordStorageChangedSlow(info_, size, capacity);
173 }
174
RecordRehash(size_t total_probe_length)175 inline void RecordRehash(size_t total_probe_length) {
176 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
177 RecordRehashSlow(info_, total_probe_length);
178 }
179
RecordInsert(size_t hash,size_t distance_from_desired)180 inline void RecordInsert(size_t hash, size_t distance_from_desired) {
181 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
182 RecordInsertSlow(info_, hash, distance_from_desired);
183 }
184
RecordErase()185 inline void RecordErase() {
186 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
187 RecordEraseSlow(info_);
188 }
189
swap(HashtablezInfoHandle & lhs,HashtablezInfoHandle & rhs)190 friend inline void swap(HashtablezInfoHandle& lhs,
191 HashtablezInfoHandle& rhs) {
192 std::swap(lhs.info_, rhs.info_);
193 }
194
195 private:
196 friend class HashtablezInfoHandlePeer;
197 HashtablezInfo* info_;
198 };
199 #else
200 // Ensure that when Hashtablez is turned off at compile time, HashtablezInfo can
201 // be removed by the linker, in order to reduce the binary size.
202 class HashtablezInfoHandle {
203 public:
204 explicit HashtablezInfoHandle() = default;
HashtablezInfoHandle(std::nullptr_t)205 explicit HashtablezInfoHandle(std::nullptr_t) {}
206
RecordStorageChanged(size_t,size_t)207 inline void RecordStorageChanged(size_t /*size*/, size_t /*capacity*/) {}
RecordRehash(size_t)208 inline void RecordRehash(size_t /*total_probe_length*/) {}
RecordInsert(size_t,size_t)209 inline void RecordInsert(size_t /*hash*/, size_t /*distance_from_desired*/) {}
RecordErase()210 inline void RecordErase() {}
211
swap(HashtablezInfoHandle &,HashtablezInfoHandle &)212 friend inline void swap(HashtablezInfoHandle& /*lhs*/,
213 HashtablezInfoHandle& /*rhs*/) {}
214 };
215 #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
216
217 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
218 extern ABSL_PER_THREAD_TLS_KEYWORD int64_t global_next_sample;
219 #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
220
221 // Returns an RAII sampling handle that manages registration and unregistation
222 // with the global sampler.
Sample()223 inline HashtablezInfoHandle Sample() {
224 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
225 if (ABSL_PREDICT_TRUE(--global_next_sample > 0)) {
226 return HashtablezInfoHandle(nullptr);
227 }
228 return HashtablezInfoHandle(SampleSlow(&global_next_sample));
229 #else
230 return HashtablezInfoHandle(nullptr);
231 #endif // !ABSL_PER_THREAD_TLS
232 }
233
234 // Holds samples and their associated stack traces with a soft limit of
235 // `SetHashtablezMaxSamples()`.
236 //
237 // Thread safe.
238 class HashtablezSampler {
239 public:
240 // Returns a global Sampler.
241 static HashtablezSampler& Global();
242
243 HashtablezSampler();
244 ~HashtablezSampler();
245
246 // Registers for sampling. Returns an opaque registration info.
247 HashtablezInfo* Register();
248
249 // Unregisters the sample.
250 void Unregister(HashtablezInfo* sample);
251
252 // The dispose callback will be called on all samples the moment they are
253 // being unregistered. Only affects samples that are unregistered after the
254 // callback has been set.
255 // Returns the previous callback.
256 using DisposeCallback = void (*)(const HashtablezInfo&);
257 DisposeCallback SetDisposeCallback(DisposeCallback f);
258
259 // Iterates over all the registered `StackInfo`s. Returning the number of
260 // samples that have been dropped.
261 int64_t Iterate(const std::function<void(const HashtablezInfo& stack)>& f);
262
263 private:
264 void PushNew(HashtablezInfo* sample);
265 void PushDead(HashtablezInfo* sample);
266 HashtablezInfo* PopDead();
267
268 std::atomic<size_t> dropped_samples_;
269 std::atomic<size_t> size_estimate_;
270
271 // Intrusive lock free linked lists for tracking samples.
272 //
273 // `all_` records all samples (they are never removed from this list) and is
274 // terminated with a `nullptr`.
275 //
276 // `graveyard_.dead` is a circular linked list. When it is empty,
277 // `graveyard_.dead == &graveyard`. The list is circular so that
278 // every item on it (even the last) has a non-null dead pointer. This allows
279 // `Iterate` to determine if a given sample is live or dead using only
280 // information on the sample itself.
281 //
282 // For example, nodes [A, B, C, D, E] with [A, C, E] alive and [B, D] dead
283 // looks like this (G is the Graveyard):
284 //
285 // +---+ +---+ +---+ +---+ +---+
286 // all -->| A |--->| B |--->| C |--->| D |--->| E |
287 // | | | | | | | | | |
288 // +---+ | | +->| |-+ | | +->| |-+ | |
289 // | G | +---+ | +---+ | +---+ | +---+ | +---+
290 // | | | | | |
291 // | | --------+ +--------+ |
292 // +---+ |
293 // ^ |
294 // +--------------------------------------+
295 //
296 std::atomic<HashtablezInfo*> all_;
297 HashtablezInfo graveyard_;
298
299 std::atomic<DisposeCallback> dispose_;
300 };
301
302 // Enables or disables sampling for Swiss tables.
303 void SetHashtablezEnabled(bool enabled);
304
305 // Sets the rate at which Swiss tables will be sampled.
306 void SetHashtablezSampleParameter(int32_t rate);
307
308 // Sets a soft max for the number of samples that will be kept.
309 void SetHashtablezMaxSamples(int32_t max);
310
311 // Configuration override.
312 // This allows process-wide sampling without depending on order of
313 // initialization of static storage duration objects.
314 // The definition of this constant is weak, which allows us to inject a
315 // different value for it at link time.
316 extern "C" bool ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)();
317
318 } // namespace container_internal
319 ABSL_NAMESPACE_END
320 } // namespace absl
321
322 #endif // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
323