hashtablez_sampler.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. #ifndef Y_ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
  39. #define Y_ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
  40. #include <atomic>
  41. #include <functional>
  42. #include <memory>
  43. #include <vector>
  44. #include "y_absl/base/config.h"
  45. #include "y_absl/base/internal/per_thread_tls.h"
  46. #include "y_absl/base/optimization.h"
  47. #include "y_absl/profiling/internal/sample_recorder.h"
  48. #include "y_absl/synchronization/mutex.h"
  49. #include "y_absl/utility/utility.h"
  50. namespace y_absl {
  51. Y_ABSL_NAMESPACE_BEGIN
  52. namespace container_internal {
  53. // Stores information about a sampled hashtable. All mutations to this *must*
  54. // be made through `Record*` functions below. All reads from this *must* only
  55. // occur in the callback to `HashtablezSampler::Iterate`.
  56. struct HashtablezInfo : public profiling_internal::Sample<HashtablezInfo> {
  57. // Constructs the object but does not fill in any fields.
  58. HashtablezInfo();
  59. ~HashtablezInfo();
  60. HashtablezInfo(const HashtablezInfo&) = delete;
  61. HashtablezInfo& operator=(const HashtablezInfo&) = delete;
  62. // Puts the object into a clean state, fills in the logically `const` members,
  63. // blocking for any readers that are currently sampling the object.
  64. void PrepareForSampling(int64_t stride, size_t inline_element_size_value)
  65. Y_ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu);
  66. // These fields are mutated by the various Record* APIs and need to be
  67. // thread-safe.
  68. std::atomic<size_t> capacity;
  69. std::atomic<size_t> size;
  70. std::atomic<size_t> num_erases;
  71. std::atomic<size_t> num_rehashes;
  72. std::atomic<size_t> max_probe_length;
  73. std::atomic<size_t> total_probe_length;
  74. std::atomic<size_t> hashes_bitwise_or;
  75. std::atomic<size_t> hashes_bitwise_and;
  76. std::atomic<size_t> hashes_bitwise_xor;
  77. std::atomic<size_t> max_reserve;
  78. // All of the fields below are set by `PrepareForSampling`, they must not be
  79. // mutated in `Record*` functions. They are logically `const` in that sense.
  80. // These are guarded by init_mu, but that is not externalized to clients,
  81. // which can read them only during `SampleRecorder::Iterate` which will hold
  82. // the lock.
  83. static constexpr int kMaxStackDepth = 64;
  84. y_absl::Time create_time;
  85. int32_t depth;
  86. void* stack[kMaxStackDepth];
  87. size_t inline_element_size; // How big is the slot?
  88. };
  89. void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length);
  90. void RecordReservationSlow(HashtablezInfo* info, size_t target_capacity);
  91. void RecordClearedReservationSlow(HashtablezInfo* info);
  92. void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
  93. size_t capacity);
  94. void RecordInsertSlow(HashtablezInfo* info, size_t hash,
  95. size_t distance_from_desired);
  96. void RecordEraseSlow(HashtablezInfo* info);
  97. struct SamplingState {
  98. int64_t next_sample;
  99. // When we make a sampling decision, we record that distance so we can weight
  100. // each sample.
  101. int64_t sample_stride;
  102. };
  103. HashtablezInfo* SampleSlow(SamplingState& next_sample,
  104. size_t inline_element_size);
  105. void UnsampleSlow(HashtablezInfo* info);
  106. #if defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  107. #error Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
  108. #endif // defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  109. #if defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  110. class HashtablezInfoHandle {
  111. public:
  112. explicit HashtablezInfoHandle() : info_(nullptr) {}
  113. explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
  114. // We do not have a destructor. Caller is responsible for calling Unregister
  115. // before destroying the handle.
  116. void Unregister() {
  117. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  118. UnsampleSlow(info_);
  119. }
  120. inline bool IsSampled() const { return Y_ABSL_PREDICT_FALSE(info_ != nullptr); }
  121. inline void RecordStorageChanged(size_t size, size_t capacity) {
  122. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  123. RecordStorageChangedSlow(info_, size, capacity);
  124. }
  125. inline void RecordRehash(size_t total_probe_length) {
  126. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  127. RecordRehashSlow(info_, total_probe_length);
  128. }
  129. inline void RecordReservation(size_t target_capacity) {
  130. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  131. RecordReservationSlow(info_, target_capacity);
  132. }
  133. inline void RecordClearedReservation() {
  134. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  135. RecordClearedReservationSlow(info_);
  136. }
  137. inline void RecordInsert(size_t hash, size_t distance_from_desired) {
  138. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  139. RecordInsertSlow(info_, hash, distance_from_desired);
  140. }
  141. inline void RecordErase() {
  142. if (Y_ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  143. RecordEraseSlow(info_);
  144. }
  145. friend inline void swap(HashtablezInfoHandle& lhs,
  146. HashtablezInfoHandle& rhs) {
  147. std::swap(lhs.info_, rhs.info_);
  148. }
  149. private:
  150. friend class HashtablezInfoHandlePeer;
  151. HashtablezInfo* info_;
  152. };
  153. #else
  154. // Ensure that when Hashtablez is turned off at compile time, HashtablezInfo can
  155. // be removed by the linker, in order to reduce the binary size.
  156. class HashtablezInfoHandle {
  157. public:
  158. explicit HashtablezInfoHandle() = default;
  159. explicit HashtablezInfoHandle(std::nullptr_t) {}
  160. inline void Unregister() {}
  161. inline bool IsSampled() const { return false; }
  162. inline void RecordStorageChanged(size_t /*size*/, size_t /*capacity*/) {}
  163. inline void RecordRehash(size_t /*total_probe_length*/) {}
  164. inline void RecordReservation(size_t /*target_capacity*/) {}
  165. inline void RecordClearedReservation() {}
  166. inline void RecordInsert(size_t /*hash*/, size_t /*distance_from_desired*/) {}
  167. inline void RecordErase() {}
  168. friend inline void swap(HashtablezInfoHandle& /*lhs*/,
  169. HashtablezInfoHandle& /*rhs*/) {}
  170. };
  171. #endif // defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  172. #if defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  173. extern Y_ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample;
  174. #endif // defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  175. // Returns an RAII sampling handle that manages registration and unregistation
  176. // with the global sampler.
  177. inline HashtablezInfoHandle Sample(
  178. size_t inline_element_size Y_ABSL_ATTRIBUTE_UNUSED) {
  179. #if defined(Y_ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  180. if (Y_ABSL_PREDICT_TRUE(--global_next_sample.next_sample > 0)) {
  181. return HashtablezInfoHandle(nullptr);
  182. }
  183. return HashtablezInfoHandle(
  184. SampleSlow(global_next_sample, inline_element_size));
  185. #else
  186. return HashtablezInfoHandle(nullptr);
  187. #endif // !Y_ABSL_PER_THREAD_TLS
  188. }
  189. using HashtablezSampler =
  190. ::y_absl::profiling_internal::SampleRecorder<HashtablezInfo>;
  191. // Returns a global Sampler.
  192. HashtablezSampler& GlobalHashtablezSampler();
  193. using HashtablezConfigListener = void (*)();
  194. void SetHashtablezConfigListener(HashtablezConfigListener l);
  195. // Enables or disables sampling for Swiss tables.
  196. bool IsHashtablezEnabled();
  197. void SetHashtablezEnabled(bool enabled);
  198. void SetHashtablezEnabledInternal(bool enabled);
  199. // Sets the rate at which Swiss tables will be sampled.
  200. int32_t GetHashtablezSampleParameter();
  201. void SetHashtablezSampleParameter(int32_t rate);
  202. void SetHashtablezSampleParameterInternal(int32_t rate);
  203. // Sets a soft max for the number of samples that will be kept.
  204. size_t GetHashtablezMaxSamples();
  205. void SetHashtablezMaxSamples(size_t max);
  206. void SetHashtablezMaxSamplesInternal(size_t max);
  207. // Configuration override.
  208. // This allows process-wide sampling without depending on order of
  209. // initialization of static storage duration objects.
  210. // The definition of this constant is weak, which allows us to inject a
  211. // different value for it at link time.
  212. extern "C" bool Y_ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)();
  213. } // namespace container_internal
  214. Y_ABSL_NAMESPACE_END
  215. } // namespace y_absl
  216. #endif // Y_ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_