blob: 394348da58f53fc86d1f896dd241920856f76ea9 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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
53namespace absl {
Austin Schuhb4691e92020-12-31 12:37:18 -080054ABSL_NAMESPACE_BEGIN
Austin Schuh36244a12019-09-21 17:52:38 -070055namespace 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`.
60struct 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;
Austin Schuhb4691e92020-12-31 12:37:18 -080076 std::atomic<size_t> num_rehashes;
Austin Schuh36244a12019-09-21 17:52:38 -070077 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
82 // `HashtablezSampler` maintains intrusive linked lists for all samples. See
83 // comments on `HashtablezSampler::all_` for details on these. `init_mu`
84 // guards the ability to restore the sample to a pristine state. This
85 // prevents races with sampling and resurrecting an object.
86 absl::Mutex init_mu;
87 HashtablezInfo* next;
88 HashtablezInfo* dead ABSL_GUARDED_BY(init_mu);
89
90 // All of the fields below are set by `PrepareForSampling`, they must not be
91 // mutated in `Record*` functions. They are logically `const` in that sense.
92 // These are guarded by init_mu, but that is not externalized to clients, who
93 // can only read them during `HashtablezSampler::Iterate` which will hold the
94 // lock.
95 static constexpr int kMaxStackDepth = 64;
96 absl::Time create_time;
97 int32_t depth;
98 void* stack[kMaxStackDepth];
99};
100
101inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
Austin Schuhb4691e92020-12-31 12:37:18 -0800102#if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
Austin Schuh36244a12019-09-21 17:52:38 -0700103 total_probe_length /= 16;
104#else
105 total_probe_length /= 8;
106#endif
107 info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
108 info->num_erases.store(0, std::memory_order_relaxed);
Austin Schuhb4691e92020-12-31 12:37:18 -0800109 // There is only one concurrent writer, so `load` then `store` is sufficient
110 // instead of using `fetch_add`.
111 info->num_rehashes.store(
112 1 + info->num_rehashes.load(std::memory_order_relaxed),
113 std::memory_order_relaxed);
Austin Schuh36244a12019-09-21 17:52:38 -0700114}
115
116inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
117 size_t capacity) {
118 info->size.store(size, std::memory_order_relaxed);
119 info->capacity.store(capacity, std::memory_order_relaxed);
120 if (size == 0) {
121 // This is a clear, reset the total/num_erases too.
Austin Schuhb4691e92020-12-31 12:37:18 -0800122 info->total_probe_length.store(0, std::memory_order_relaxed);
123 info->num_erases.store(0, std::memory_order_relaxed);
Austin Schuh36244a12019-09-21 17:52:38 -0700124 }
125}
126
127void RecordInsertSlow(HashtablezInfo* info, size_t hash,
128 size_t distance_from_desired);
129
130inline void RecordEraseSlow(HashtablezInfo* info) {
131 info->size.fetch_sub(1, std::memory_order_relaxed);
Austin Schuhb4691e92020-12-31 12:37:18 -0800132 // There is only one concurrent writer, so `load` then `store` is sufficient
133 // instead of using `fetch_add`.
134 info->num_erases.store(
135 1 + info->num_erases.load(std::memory_order_relaxed),
136 std::memory_order_relaxed);
Austin Schuh36244a12019-09-21 17:52:38 -0700137}
138
139HashtablezInfo* SampleSlow(int64_t* next_sample);
140void UnsampleSlow(HashtablezInfo* info);
141
Austin Schuhb4691e92020-12-31 12:37:18 -0800142#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
143#error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
144#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
145
146#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
Austin Schuh36244a12019-09-21 17:52:38 -0700147class HashtablezInfoHandle {
148 public:
149 explicit HashtablezInfoHandle() : info_(nullptr) {}
150 explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
151 ~HashtablezInfoHandle() {
152 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
153 UnsampleSlow(info_);
154 }
155
156 HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
157 HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
158
159 HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
160 : info_(absl::exchange(o.info_, nullptr)) {}
161 HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
162 if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
163 UnsampleSlow(info_);
164 }
165 info_ = absl::exchange(o.info_, nullptr);
166 return *this;
167 }
168
169 inline void RecordStorageChanged(size_t size, size_t capacity) {
170 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
171 RecordStorageChangedSlow(info_, size, capacity);
172 }
173
174 inline void RecordRehash(size_t total_probe_length) {
175 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
176 RecordRehashSlow(info_, total_probe_length);
177 }
178
179 inline void RecordInsert(size_t hash, size_t distance_from_desired) {
180 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
181 RecordInsertSlow(info_, hash, distance_from_desired);
182 }
183
184 inline void RecordErase() {
185 if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
186 RecordEraseSlow(info_);
187 }
188
189 friend inline void swap(HashtablezInfoHandle& lhs,
190 HashtablezInfoHandle& rhs) {
191 std::swap(lhs.info_, rhs.info_);
192 }
193
194 private:
195 friend class HashtablezInfoHandlePeer;
196 HashtablezInfo* info_;
197};
Austin Schuhb4691e92020-12-31 12:37:18 -0800198#else
199// Ensure that when Hashtablez is turned off at compile time, HashtablezInfo can
200// be removed by the linker, in order to reduce the binary size.
201class HashtablezInfoHandle {
202 public:
203 explicit HashtablezInfoHandle() = default;
204 explicit HashtablezInfoHandle(std::nullptr_t) {}
Austin Schuh36244a12019-09-21 17:52:38 -0700205
Austin Schuhb4691e92020-12-31 12:37:18 -0800206 inline void RecordStorageChanged(size_t /*size*/, size_t /*capacity*/) {}
207 inline void RecordRehash(size_t /*total_probe_length*/) {}
208 inline void RecordInsert(size_t /*hash*/, size_t /*distance_from_desired*/) {}
209 inline void RecordErase() {}
210
211 friend inline void swap(HashtablezInfoHandle& /*lhs*/,
212 HashtablezInfoHandle& /*rhs*/) {}
213};
214#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
215
216#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
Austin Schuh36244a12019-09-21 17:52:38 -0700217extern ABSL_PER_THREAD_TLS_KEYWORD int64_t global_next_sample;
Austin Schuhb4691e92020-12-31 12:37:18 -0800218#endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
Austin Schuh36244a12019-09-21 17:52:38 -0700219
220// Returns an RAII sampling handle that manages registration and unregistation
221// with the global sampler.
222inline HashtablezInfoHandle Sample() {
Austin Schuhb4691e92020-12-31 12:37:18 -0800223#if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
Austin Schuh36244a12019-09-21 17:52:38 -0700224 if (ABSL_PREDICT_TRUE(--global_next_sample > 0)) {
225 return HashtablezInfoHandle(nullptr);
226 }
227 return HashtablezInfoHandle(SampleSlow(&global_next_sample));
Austin Schuhb4691e92020-12-31 12:37:18 -0800228#else
229 return HashtablezInfoHandle(nullptr);
230#endif // !ABSL_PER_THREAD_TLS
Austin Schuh36244a12019-09-21 17:52:38 -0700231}
232
233// Holds samples and their associated stack traces with a soft limit of
234// `SetHashtablezMaxSamples()`.
235//
236// Thread safe.
237class HashtablezSampler {
238 public:
239 // Returns a global Sampler.
240 static HashtablezSampler& Global();
241
242 HashtablezSampler();
243 ~HashtablezSampler();
244
245 // Registers for sampling. Returns an opaque registration info.
246 HashtablezInfo* Register();
247
248 // Unregisters the sample.
249 void Unregister(HashtablezInfo* sample);
250
251 // The dispose callback will be called on all samples the moment they are
252 // being unregistered. Only affects samples that are unregistered after the
253 // callback has been set.
254 // Returns the previous callback.
255 using DisposeCallback = void (*)(const HashtablezInfo&);
256 DisposeCallback SetDisposeCallback(DisposeCallback f);
257
258 // Iterates over all the registered `StackInfo`s. Returning the number of
259 // samples that have been dropped.
260 int64_t Iterate(const std::function<void(const HashtablezInfo& stack)>& f);
261
262 private:
263 void PushNew(HashtablezInfo* sample);
264 void PushDead(HashtablezInfo* sample);
265 HashtablezInfo* PopDead();
266
267 std::atomic<size_t> dropped_samples_;
268 std::atomic<size_t> size_estimate_;
269
270 // Intrusive lock free linked lists for tracking samples.
271 //
272 // `all_` records all samples (they are never removed from this list) and is
273 // terminated with a `nullptr`.
274 //
275 // `graveyard_.dead` is a circular linked list. When it is empty,
276 // `graveyard_.dead == &graveyard`. The list is circular so that
277 // every item on it (even the last) has a non-null dead pointer. This allows
278 // `Iterate` to determine if a given sample is live or dead using only
279 // information on the sample itself.
280 //
281 // For example, nodes [A, B, C, D, E] with [A, C, E] alive and [B, D] dead
282 // looks like this (G is the Graveyard):
283 //
284 // +---+ +---+ +---+ +---+ +---+
285 // all -->| A |--->| B |--->| C |--->| D |--->| E |
286 // | | | | | | | | | |
287 // +---+ | | +->| |-+ | | +->| |-+ | |
288 // | G | +---+ | +---+ | +---+ | +---+ | +---+
289 // | | | | | |
290 // | | --------+ +--------+ |
291 // +---+ |
292 // ^ |
293 // +--------------------------------------+
294 //
295 std::atomic<HashtablezInfo*> all_;
296 HashtablezInfo graveyard_;
297
298 std::atomic<DisposeCallback> dispose_;
299};
300
301// Enables or disables sampling for Swiss tables.
302void SetHashtablezEnabled(bool enabled);
303
304// Sets the rate at which Swiss tables will be sampled.
305void SetHashtablezSampleParameter(int32_t rate);
306
307// Sets a soft max for the number of samples that will be kept.
308void SetHashtablezMaxSamples(int32_t max);
309
310// Configuration override.
311// This allows process-wide sampling without depending on order of
312// initialization of static storage duration objects.
313// The definition of this constant is weak, which allows us to inject a
314// different value for it at link time.
Austin Schuhb4691e92020-12-31 12:37:18 -0800315extern "C" bool AbslContainerInternalSampleEverything();
Austin Schuh36244a12019-09-21 17:52:38 -0700316
317} // namespace container_internal
Austin Schuhb4691e92020-12-31 12:37:18 -0800318ABSL_NAMESPACE_END
Austin Schuh36244a12019-09-21 17:52:38 -0700319} // namespace absl
320
321#endif // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_