• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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> max_probe_length;
77   std::atomic<size_t> total_probe_length;
78   std::atomic<size_t> hashes_bitwise_or;
79   std::atomic<size_t> hashes_bitwise_and;
80 
81   // `HashtablezSampler` maintains intrusive linked lists for all samples.  See
82   // comments on `HashtablezSampler::all_` for details on these.  `init_mu`
83   // guards the ability to restore the sample to a pristine state.  This
84   // prevents races with sampling and resurrecting an object.
85   absl::Mutex init_mu;
86   HashtablezInfo* next;
87   HashtablezInfo* dead ABSL_GUARDED_BY(init_mu);
88 
89   // All of the fields below are set by `PrepareForSampling`, they must not be
90   // mutated in `Record*` functions.  They are logically `const` in that sense.
91   // These are guarded by init_mu, but that is not externalized to clients, who
92   // can only read them during `HashtablezSampler::Iterate` which will hold the
93   // lock.
94   static constexpr int kMaxStackDepth = 64;
95   absl::Time create_time;
96   int32_t depth;
97   void* stack[kMaxStackDepth];
98 };
99 
RecordRehashSlow(HashtablezInfo * info,size_t total_probe_length)100 inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
101 #if SWISSTABLE_HAVE_SSE2
102   total_probe_length /= 16;
103 #else
104   total_probe_length /= 8;
105 #endif
106   info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
107   info->num_erases.store(0, std::memory_order_relaxed);
108 }
109 
RecordStorageChangedSlow(HashtablezInfo * info,size_t size,size_t capacity)110 inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
111                                      size_t capacity) {
112   info->size.store(size, std::memory_order_relaxed);
113   info->capacity.store(capacity, std::memory_order_relaxed);
114   if (size == 0) {
115     // This is a clear, reset the total/num_erases too.
116     RecordRehashSlow(info, 0);
117   }
118 }
119 
120 void RecordInsertSlow(HashtablezInfo* info, size_t hash,
121                       size_t distance_from_desired);
122 
RecordEraseSlow(HashtablezInfo * info)123 inline void RecordEraseSlow(HashtablezInfo* info) {
124   info->size.fetch_sub(1, std::memory_order_relaxed);
125   info->num_erases.fetch_add(1, std::memory_order_relaxed);
126 }
127 
128 HashtablezInfo* SampleSlow(int64_t* next_sample);
129 void UnsampleSlow(HashtablezInfo* info);
130 
131 class HashtablezInfoHandle {
132  public:
HashtablezInfoHandle()133   explicit HashtablezInfoHandle() : info_(nullptr) {}
HashtablezInfoHandle(HashtablezInfo * info)134   explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
~HashtablezInfoHandle()135   ~HashtablezInfoHandle() {
136     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
137     UnsampleSlow(info_);
138   }
139 
140   HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
141   HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
142 
HashtablezInfoHandle(HashtablezInfoHandle && o)143   HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
144       : info_(absl::exchange(o.info_, nullptr)) {}
145   HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
146     if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
147       UnsampleSlow(info_);
148     }
149     info_ = absl::exchange(o.info_, nullptr);
150     return *this;
151   }
152 
RecordStorageChanged(size_t size,size_t capacity)153   inline void RecordStorageChanged(size_t size, size_t capacity) {
154     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
155     RecordStorageChangedSlow(info_, size, capacity);
156   }
157 
RecordRehash(size_t total_probe_length)158   inline void RecordRehash(size_t total_probe_length) {
159     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
160     RecordRehashSlow(info_, total_probe_length);
161   }
162 
RecordInsert(size_t hash,size_t distance_from_desired)163   inline void RecordInsert(size_t hash, size_t distance_from_desired) {
164     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
165     RecordInsertSlow(info_, hash, distance_from_desired);
166   }
167 
RecordErase()168   inline void RecordErase() {
169     if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
170     RecordEraseSlow(info_);
171   }
172 
swap(HashtablezInfoHandle & lhs,HashtablezInfoHandle & rhs)173   friend inline void swap(HashtablezInfoHandle& lhs,
174                           HashtablezInfoHandle& rhs) {
175     std::swap(lhs.info_, rhs.info_);
176   }
177 
178  private:
179   friend class HashtablezInfoHandlePeer;
180   HashtablezInfo* info_;
181 };
182 
183 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
184 #error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
185 #endif  // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
186 
187 #if (ABSL_PER_THREAD_TLS == 1) && !defined(ABSL_BUILD_DLL) && \
188     !defined(ABSL_CONSUME_DLL)
189 #define ABSL_INTERNAL_HASHTABLEZ_SAMPLE
190 #endif
191 
192 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
193 extern ABSL_PER_THREAD_TLS_KEYWORD int64_t global_next_sample;
194 #endif  // ABSL_PER_THREAD_TLS
195 
196 // Returns an RAII sampling handle that manages registration and unregistation
197 // with the global sampler.
Sample()198 inline HashtablezInfoHandle Sample() {
199 #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
200   if (ABSL_PREDICT_TRUE(--global_next_sample > 0)) {
201     return HashtablezInfoHandle(nullptr);
202   }
203   return HashtablezInfoHandle(SampleSlow(&global_next_sample));
204 #else
205   return HashtablezInfoHandle(nullptr);
206 #endif  // !ABSL_PER_THREAD_TLS
207 }
208 
209 // Holds samples and their associated stack traces with a soft limit of
210 // `SetHashtablezMaxSamples()`.
211 //
212 // Thread safe.
213 class HashtablezSampler {
214  public:
215   // Returns a global Sampler.
216   static HashtablezSampler& Global();
217 
218   HashtablezSampler();
219   ~HashtablezSampler();
220 
221   // Registers for sampling.  Returns an opaque registration info.
222   HashtablezInfo* Register();
223 
224   // Unregisters the sample.
225   void Unregister(HashtablezInfo* sample);
226 
227   // The dispose callback will be called on all samples the moment they are
228   // being unregistered. Only affects samples that are unregistered after the
229   // callback has been set.
230   // Returns the previous callback.
231   using DisposeCallback = void (*)(const HashtablezInfo&);
232   DisposeCallback SetDisposeCallback(DisposeCallback f);
233 
234   // Iterates over all the registered `StackInfo`s.  Returning the number of
235   // samples that have been dropped.
236   int64_t Iterate(const std::function<void(const HashtablezInfo& stack)>& f);
237 
238  private:
239   void PushNew(HashtablezInfo* sample);
240   void PushDead(HashtablezInfo* sample);
241   HashtablezInfo* PopDead();
242 
243   std::atomic<size_t> dropped_samples_;
244   std::atomic<size_t> size_estimate_;
245 
246   // Intrusive lock free linked lists for tracking samples.
247   //
248   // `all_` records all samples (they are never removed from this list) and is
249   // terminated with a `nullptr`.
250   //
251   // `graveyard_.dead` is a circular linked list.  When it is empty,
252   // `graveyard_.dead == &graveyard`.  The list is circular so that
253   // every item on it (even the last) has a non-null dead pointer.  This allows
254   // `Iterate` to determine if a given sample is live or dead using only
255   // information on the sample itself.
256   //
257   // For example, nodes [A, B, C, D, E] with [A, C, E] alive and [B, D] dead
258   // looks like this (G is the Graveyard):
259   //
260   //           +---+    +---+    +---+    +---+    +---+
261   //    all -->| A |--->| B |--->| C |--->| D |--->| E |
262   //           |   |    |   |    |   |    |   |    |   |
263   //   +---+   |   | +->|   |-+  |   | +->|   |-+  |   |
264   //   | G |   +---+ |  +---+ |  +---+ |  +---+ |  +---+
265   //   |   |         |        |        |        |
266   //   |   | --------+        +--------+        |
267   //   +---+                                    |
268   //     ^                                      |
269   //     +--------------------------------------+
270   //
271   std::atomic<HashtablezInfo*> all_;
272   HashtablezInfo graveyard_;
273 
274   std::atomic<DisposeCallback> dispose_;
275 };
276 
277 // Enables or disables sampling for Swiss tables.
278 void SetHashtablezEnabled(bool enabled);
279 
280 // Sets the rate at which Swiss tables will be sampled.
281 void SetHashtablezSampleParameter(int32_t rate);
282 
283 // Sets a soft max for the number of samples that will be kept.
284 void SetHashtablezMaxSamples(int32_t max);
285 
286 // Configuration override.
287 // This allows process-wide sampling without depending on order of
288 // initialization of static storage duration objects.
289 // The definition of this constant is weak, which allows us to inject a
290 // different value for it at link time.
291 extern "C" bool AbslContainerInternalSampleEverything();
292 
293 }  // namespace container_internal
294 ABSL_NAMESPACE_END
295 }  // namespace absl
296 
297 #endif  // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
298