You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

hashtablez_sampler.h 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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/config.h"
  45. #include "absl/base/internal/per_thread_tls.h"
  46. #include "absl/base/optimization.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(int64_t stride, size_t inline_element_size_value)
  65. 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. 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. inline void RecordRehashSlow(HashtablezInfo* info, size_t total_probe_length) {
  90. #ifdef ABSL_INTERNAL_HAVE_SSE2
  91. total_probe_length /= 16;
  92. #else
  93. total_probe_length /= 8;
  94. #endif
  95. info->total_probe_length.store(total_probe_length, std::memory_order_relaxed);
  96. info->num_erases.store(0, std::memory_order_relaxed);
  97. // There is only one concurrent writer, so `load` then `store` is sufficient
  98. // instead of using `fetch_add`.
  99. info->num_rehashes.store(
  100. 1 + info->num_rehashes.load(std::memory_order_relaxed),
  101. std::memory_order_relaxed);
  102. }
  103. inline void RecordReservationSlow(HashtablezInfo* info,
  104. size_t target_capacity) {
  105. info->max_reserve.store(
  106. (std::max)(info->max_reserve.load(std::memory_order_relaxed),
  107. target_capacity),
  108. std::memory_order_relaxed);
  109. }
  110. inline void RecordClearedReservationSlow(HashtablezInfo* info) {
  111. info->max_reserve.store(0, std::memory_order_relaxed);
  112. }
  113. inline void RecordStorageChangedSlow(HashtablezInfo* info, size_t size,
  114. size_t capacity) {
  115. info->size.store(size, std::memory_order_relaxed);
  116. info->capacity.store(capacity, std::memory_order_relaxed);
  117. if (size == 0) {
  118. // This is a clear, reset the total/num_erases too.
  119. info->total_probe_length.store(0, std::memory_order_relaxed);
  120. info->num_erases.store(0, std::memory_order_relaxed);
  121. }
  122. }
  123. void RecordInsertSlow(HashtablezInfo* info, size_t hash,
  124. size_t distance_from_desired);
  125. inline void RecordEraseSlow(HashtablezInfo* info) {
  126. info->size.fetch_sub(1, std::memory_order_relaxed);
  127. // There is only one concurrent writer, so `load` then `store` is sufficient
  128. // instead of using `fetch_add`.
  129. info->num_erases.store(
  130. 1 + info->num_erases.load(std::memory_order_relaxed),
  131. std::memory_order_relaxed);
  132. }
  133. struct SamplingState {
  134. int64_t next_sample;
  135. // When we make a sampling decision, we record that distance so we can weight
  136. // each sample.
  137. int64_t sample_stride;
  138. };
  139. HashtablezInfo* SampleSlow(SamplingState& next_sample,
  140. size_t inline_element_size);
  141. void UnsampleSlow(HashtablezInfo* info);
  142. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  143. #error ABSL_INTERNAL_HASHTABLEZ_SAMPLE cannot be directly set
  144. #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  145. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  146. class HashtablezInfoHandle {
  147. public:
  148. explicit HashtablezInfoHandle() : info_(nullptr) {}
  149. explicit HashtablezInfoHandle(HashtablezInfo* info) : info_(info) {}
  150. ~HashtablezInfoHandle() {
  151. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  152. UnsampleSlow(info_);
  153. }
  154. HashtablezInfoHandle(const HashtablezInfoHandle&) = delete;
  155. HashtablezInfoHandle& operator=(const HashtablezInfoHandle&) = delete;
  156. HashtablezInfoHandle(HashtablezInfoHandle&& o) noexcept
  157. : info_(absl::exchange(o.info_, nullptr)) {}
  158. HashtablezInfoHandle& operator=(HashtablezInfoHandle&& o) noexcept {
  159. if (ABSL_PREDICT_FALSE(info_ != nullptr)) {
  160. UnsampleSlow(info_);
  161. }
  162. info_ = absl::exchange(o.info_, nullptr);
  163. return *this;
  164. }
  165. inline void RecordStorageChanged(size_t size, size_t capacity) {
  166. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  167. RecordStorageChangedSlow(info_, size, capacity);
  168. }
  169. inline void RecordRehash(size_t total_probe_length) {
  170. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  171. RecordRehashSlow(info_, total_probe_length);
  172. }
  173. inline void RecordReservation(size_t target_capacity) {
  174. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  175. RecordReservationSlow(info_, target_capacity);
  176. }
  177. inline void RecordClearedReservation() {
  178. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  179. RecordClearedReservationSlow(info_);
  180. }
  181. inline void RecordInsert(size_t hash, size_t distance_from_desired) {
  182. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  183. RecordInsertSlow(info_, hash, distance_from_desired);
  184. }
  185. inline void RecordErase() {
  186. if (ABSL_PREDICT_TRUE(info_ == nullptr)) return;
  187. RecordEraseSlow(info_);
  188. }
  189. friend inline void swap(HashtablezInfoHandle& lhs,
  190. HashtablezInfoHandle& rhs) {
  191. std::swap(lhs.info_, rhs.info_);
  192. }
  193. private:
  194. friend class HashtablezInfoHandlePeer;
  195. HashtablezInfo* info_;
  196. };
  197. #else
  198. // Ensure that when Hashtablez is turned off at compile time, HashtablezInfo can
  199. // be removed by the linker, in order to reduce the binary size.
  200. class HashtablezInfoHandle {
  201. public:
  202. explicit HashtablezInfoHandle() = default;
  203. explicit HashtablezInfoHandle(std::nullptr_t) {}
  204. inline void RecordStorageChanged(size_t /*size*/, size_t /*capacity*/) {}
  205. inline void RecordRehash(size_t /*total_probe_length*/) {}
  206. inline void RecordReservation(size_t /*target_capacity*/) {}
  207. inline void RecordClearedReservation() {}
  208. inline void RecordInsert(size_t /*hash*/, size_t /*distance_from_desired*/) {}
  209. inline void RecordErase() {}
  210. friend inline void swap(HashtablezInfoHandle& /*lhs*/,
  211. HashtablezInfoHandle& /*rhs*/) {}
  212. };
  213. #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  214. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  215. extern ABSL_PER_THREAD_TLS_KEYWORD SamplingState global_next_sample;
  216. #endif // defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  217. // Returns an RAII sampling handle that manages registration and unregistation
  218. // with the global sampler.
  219. inline HashtablezInfoHandle Sample(
  220. size_t inline_element_size ABSL_ATTRIBUTE_UNUSED) {
  221. #if defined(ABSL_INTERNAL_HASHTABLEZ_SAMPLE)
  222. if (ABSL_PREDICT_TRUE(--global_next_sample.next_sample > 0)) {
  223. return HashtablezInfoHandle(nullptr);
  224. }
  225. return HashtablezInfoHandle(
  226. SampleSlow(global_next_sample, inline_element_size));
  227. #else
  228. return HashtablezInfoHandle(nullptr);
  229. #endif // !ABSL_PER_THREAD_TLS
  230. }
  231. using HashtablezSampler =
  232. ::absl::profiling_internal::SampleRecorder<HashtablezInfo>;
  233. // Returns a global Sampler.
  234. HashtablezSampler& GlobalHashtablezSampler();
  235. using HashtablezConfigListener = void (*)();
  236. void SetHashtablezConfigListener(HashtablezConfigListener l);
  237. // Enables or disables sampling for Swiss tables.
  238. bool IsHashtablezEnabled();
  239. void SetHashtablezEnabled(bool enabled);
  240. void SetHashtablezEnabledInternal(bool enabled);
  241. // Sets the rate at which Swiss tables will be sampled.
  242. int32_t GetHashtablezSampleParameter();
  243. void SetHashtablezSampleParameter(int32_t rate);
  244. void SetHashtablezSampleParameterInternal(int32_t rate);
  245. // Sets a soft max for the number of samples that will be kept.
  246. int32_t GetHashtablezMaxSamples();
  247. void SetHashtablezMaxSamples(int32_t max);
  248. void SetHashtablezMaxSamplesInternal(int32_t max);
  249. // Configuration override.
  250. // This allows process-wide sampling without depending on order of
  251. // initialization of static storage duration objects.
  252. // The definition of this constant is weak, which allows us to inject a
  253. // different value for it at link time.
  254. extern "C" bool ABSL_INTERNAL_C_SYMBOL(AbslContainerInternalSampleEverything)();
  255. } // namespace container_internal
  256. ABSL_NAMESPACE_END
  257. } // namespace absl
  258. #endif // ABSL_CONTAINER_INTERNAL_HASHTABLEZ_SAMPLER_H_