hashtablez_sampler.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
  39. #define ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_
  40. #include <atomic>
  41. #include <functional>
  42. #include <memory>
  43. #include <vector>
  44. #include "absl/base/internal/per_thread_tls.h"
  45. #include "absl/base/optimization.h"
  46. #include "absl/container/internal/have_sse.h"
  47. #include "absl/profiling/internal/sample_recorder.h"
  48. #include "absl/synchronization/mutex.h"
  49. #include "absl/utility/utility.h"
  50. namespace absl {
  51. 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() ABSL_EXCLUSIVE_LOCKS_REQUIRED(init_mu);
  65. // These fields are mutated by the various Record* APIs and need to be
  66. // thread-safe.
  67. std::atomic<size_t> capacity;
  68. std::atomic<size_t> size;
  69. std::atomic<size_t> num_erases;
  70. std::atomic<size_t> num_rehashes;
  71. std::atomic<size_t> max_probe_length;
  72. std::atomic<size_t> total_probe_length;
  73. std::atomic<size_t> hashes_bitwise_or;
  74. std::atomic<size_t> hashes_bitwise_and;
  75. std::atomic<size_t> hashes_bitwise_xor;
  76. std::atomic<size_t> max_reserve;
  77. // All of the fields below are set by `PrepareForSampling`, they must not be
  78. // mutated in `Record*` functions. They are logically `const` in that sense.
  79. // These are guarded by init_mu, but that is not externalized to clients, who
  80. // can only read them during `HashtablezSampler::Iterate` which will hold the
  81. // lock.
  82. static constexpr int kMaxStackDepth = 64;
  83. absl::Time create_time;
  84. int32_t depth;
  85. void* stack[kMaxStackDepth];
  86. size_t inline_element_size;
  87. };
  88. inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
  89. #if ABSL_INTERNAL_RAW_HASH_SET_HAVE_SSE2
  90. total_probe_length /= 16;
  91. #else
  92. total_probe_length /= 8;
  93. #endif
  94. info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
  95. info->num_erases.store(0, std::memory_order_relaxed);
  96. // There is only one concurrent writer, so `load` then `store` is sufficient
  97. // instead of using `fetch_add`.
  98. info->num_rehashes.store(
  99. 1 + info->num_rehashes.load(std::memory_order_relaxed),
  100. std::memory_order_relaxed);
  101. }
  102. inline void RecordReservationSlow(HashtablezInfo* info,
  103. size_t target_capacity) {
  104. info->max_reserve.store(
  105. (std::max)(info->max_reserve.load(std::memory_order_relaxed),
  106. target_capacity),
  107. std::memory_order_relaxed);
  108. }
  109. inline void RecordClearedReservationSlow(HashtablezInfo* info) {
  110. info->max_reserve.store(0, std::memory_order_relaxed);
  111. }
  112. inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
  113. size_t capacity) {
  114. info->size.store(size, std::memory_order_relaxed);
  115. info->capacity.store(capacity, std::memory_order_relaxed);
  116. if (size == 0) {
  117. // This is a clear, reset the total/num_erases too.
  118. info->total_probe_length.store(0, std::memory_order_relaxed);
  119. info->num_erases.store(0, std::memory_order_relaxed);
  120. }
  121. }
  122. void RecordInsertSlow(HashtablezInfo* info, size_t hash,
  123. size_t distance_from_desired);
  124. inline void RecordEraseSlow(HashtablezInfo* info) {
  125. info->size.fetch_sub(1, std::memory_order_relaxed);
  126. // There is only one concurrent writer, so `load` then `store` is sufficient
  127. // instead of using `fetch_add`.
  128. info->num_erases.store(
  129. 1 + info->num_erases.load(std::memory_order_relaxed),
  130. std::memory_order_relaxed);
  131. }
  132. HashtablezInfo* SampleSlow(int64_t* next_sample, size_t inline_element_size);
  133. void UnsampleSlow(HashtablezInfo* info);
  134. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  135. #error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
  136. #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  137. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  138. class HashtablezInfoHandle {
  139. public:
  140. explicit HashtablezInfoHandle() : info_(nullptr) {}
  141. explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
  142. ~HashtablezInfoHandle() {
  143. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  144. UnsampleSlow(info_);
  145. }
  146. HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
  147. HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
  148. HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
  149. : info_(absl::exchange(o.info_, nullptr)) {}
  150. HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
  151. if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
  152. UnsampleSlow(info_);
  153. }
  154. info_ = absl::exchange(o.info_, nullptr);
  155. return *this;
  156. }
  157. inline void RecordStorageChanged(size_t size, size_t capacity) {
  158. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  159. RecordStorageChangedSlow(info_, size, capacity);
  160. }
  161. inline void RecordRehash(size_t total_probe_length) {
  162. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  163. RecordRehashSlow(info_, total_probe_length);
  164. }
  165. inline void RecordReservation(size_t target_capacity) {
  166. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  167. RecordReservationSlow(info_, target_capacity);
  168. }
  169. inline void RecordClearedReservation() {
  170. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  171. RecordClearedReservationSlow(info_);
  172. }
  173. inline void RecordInsert(size_t hash, size_t distance_from_desired) {
  174. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  175. RecordInsertSlow(info_, hash, distance_from_desired);
  176. }
  177. inline void RecordErase() {
  178. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  179. RecordEraseSlow(info_);
  180. }
  181. friend inline void swap(HashtablezInfoHandle& lhs,
  182. HashtablezInfoHandle& rhs) {
  183. std::swap(lhs.info_, rhs.info_);
  184. }
  185. private:
  186. friend class HashtablezInfoHandlePeer;
  187. HashtablezInfo* info_;
  188. };
  189. #else
  190. // Ensure that when Hashtablez is turned off at compile time, HashtablezInfo can
  191. // be removed by the linker, in order to reduce the binary size.
  192. class HashtablezInfoHandle {
  193. public:
  194. explicit HashtablezInfoHandle() = default;
  195. explicit HashtablezInfoHandle(std::nullptr_t) {}
  196. inline void RecordStorageChanged(size_t /*size*/, size_t /*capacity*/) {}
  197. inline void RecordRehash(size_t /*total_probe_length*/) {}
  198. inline void RecordReservation(size_t /*target_capacity*/) {}
  199. inline void RecordClearedReservation() {}
  200. inline void RecordInsert(size_t /*hash*/, size_t /*distance_from_desired*/) {}
  201. inline void RecordErase() {}
  202. friend inline void swap(HashtablezInfoHandle& /*lhs*/,
  203. HashtablezInfoHandle& /*rhs*/) {}
  204. };
  205. #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  206. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  207. extern ABSL_PER_THREAD_TLS_KEYWORD int64_t global_next_sample;
  208. #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  209. // Returns an RAII sampling handle that manages registration and unregistation
  210. // with the global sampler.
  211. inline HashtablezInfoHandle Sample(
  212. size_t inline_element_size ABSL_ATTRIBUTE_UNUSED) {
  213. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  214. if (ABSL_PREDICT_TRUE(--global_next_sample > 0)) {
  215. return HashtablezInfoHandle(nullptr);
  216. }
  217. return HashtablezInfoHandle(
  218. SampleSlow(&global_next_sample, inline_element_size));
  219. #else
  220. return HashtablezInfoHandle(nullptr);
  221. #endif // !ABSL_PER_THREAD_TLS
  222. }
  223. using HashtablezSampler =
  224. ::absl::profiling_internal::SampleRecorder<HashtablezInfo>;
  225. // Returns a global Sampler.
  226. HashtablezSampler& GlobalHashtablezSampler();
  227. // Enables or disables sampling for Swiss tables.
  228. void SetHashtablezEnabled(bool enabled);
  229. // Sets the rate at which Swiss tables will be sampled.
  230. void SetHashtablezSampleParameter(int32_t rate);
  231. // Sets a soft max for the number of samples that will be kept.
  232. void SetHashtablezMaxSamples(int32_t max);
  233. // Configuration override.
  234. // This allows process-wide sampling without depending on order of
  235. // initialization of static storage duration objects.
  236. // The definition of this constant is weak, which allows us to inject a
  237. // different value for it at link time.
  238. extern "C" bool ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)();
  239. } // namespace container_internal
  240. ABSL_NAMESPACE_END
  241. } // namespace absl
  242. #endif // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_