MySQL 9.1.0
Source Code Documentation
ut0ut.h
Go to the documentation of this file.
1/*****************************************************************************
2
3Copyright (c) 1994, 2024, Oracle and/or its affiliates.
4
5This program is free software; you can redistribute it and/or modify it under
6the terms of the GNU General Public License, version 2.0, as published by the
7Free Software Foundation.
8
9This program is designed to work with certain software (including
10but not limited to OpenSSL) that is licensed under separate terms,
11as designated in a particular file or component or in included license
12documentation. The authors of MySQL hereby grant you an additional
13permission to link the program and your derivative works with the
14separately licensed software that they have either included with
15the program or referenced in the documentation.
16
17This program is distributed in the hope that it will be useful, but WITHOUT
18ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20for more details.
21
22You should have received a copy of the GNU General Public License along with
23this program; if not, write to the Free Software Foundation, Inc.,
2451 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26*****************************************************************************/
27
28/** @file include/ut0ut.h
29 Various utilities
30
31 Created 1/20/1994 Heikki Tuuri
32 ***********************************************************************/
33
34/**************************************************/ /**
35 @page PAGE_INNODB_UTILS Innodb utils
36
37 Useful data structures:
38 - @ref Link_buf - to track concurrent operations
39 - @ref Sharded_rw_lock - sharded rw-lock (very fast s-lock, slow x-lock)
40
41 *******************************************************/
42
43#ifndef ut0ut_h
44#define ut0ut_h
45
46/* Do not include univ.i because univ.i includes this. */
47
48#include <string.h>
49#include <algorithm>
50#include <chrono>
51#include <cmath>
52#include <iomanip>
53#include <iterator>
54#include <ostream>
55#include <sstream>
56#include <thread>
57#include <type_traits>
58
59#ifdef UNIV_DEBUG
60#include <limits>
61#include <random>
62#endif /* UNIV_DEBUG */
63
64#include "db0err.h"
65
66#ifndef UNIV_HOTBACKUP
67#include "os0atomic.h"
68#endif /* !UNIV_HOTBACKUP */
69
70#include <time.h>
71
72#include <ctype.h>
73
74#include <stdarg.h>
75#include "ut/ut.h"
76#include "ut0dbg.h"
77
78#ifndef UNIV_NO_ERR_MSGS
80#include "mysqld_error.h"
81#include "sql/derror.h"
82#endif /* !UNIV_NO_ERR_MSGS */
83
84/** Index name prefix in fast index creation, as a string constant */
85#define TEMP_INDEX_PREFIX_STR "\377"
86
87#ifndef UNIV_HOTBACKUP
88#if defined(HAVE_PAUSE_INSTRUCTION)
89/* According to the gcc info page, asm volatile means that the
90instruction has important side-effects and must not be removed.
91Also asm volatile may trigger a memory barrier (spilling all registers
92to memory). */
93#define UT_RELAX_CPU() __asm__ __volatile__("pause")
94
95#elif defined(HAVE_FAKE_PAUSE_INSTRUCTION)
96#define UT_RELAX_CPU() __asm__ __volatile__("rep; nop")
97#elif defined _WIN32
98/* In the Win32 API, the x86 PAUSE instruction is executed by calling
99the YieldProcessor macro defined in WinNT.h. It is a CPU architecture-
100independent way by using YieldProcessor. */
101#define UT_RELAX_CPU() YieldProcessor()
102#elif defined(__aarch64__)
103/* A "yield" instruction in aarch64 is essentially a nop, and does not cause
104enough delay to help backoff. "isb" is a barrier that, especially inside a
105loop, creates a small delay without consuming ALU resources.
106Experiments shown that adding the isb instruction improves stability and reduces
107result jitter. Adding more delay to the UT_RELAX_CPU than a single isb reduces
108performance. */
109#define UT_RELAX_CPU() __asm__ __volatile__("isb" ::: "memory")
110#else
111#define UT_RELAX_CPU() __asm__ __volatile__("" ::: "memory")
112#endif
113
114#if defined(HAVE_HMT_PRIORITY_INSTRUCTION)
115#define UT_LOW_PRIORITY_CPU() __asm__ __volatile__("or 1,1,1")
116#define UT_RESUME_PRIORITY_CPU() __asm__ __volatile__("or 2,2,2")
117#else
118#define UT_LOW_PRIORITY_CPU() ((void)0)
119#define UT_RESUME_PRIORITY_CPU() ((void)0)
120#endif
121
122#else /* !UNIV_HOTBACKUP */
123#define UT_RELAX_CPU() /* No op */
124#endif /* !UNIV_HOTBACKUP */
125
126#ifndef UNIV_HOTBACKUP
127
128/** Calculate the minimum of two pairs.
129@param[out] min_hi MSB of the minimum pair
130@param[out] min_lo LSB of the minimum pair
131@param[in] a_hi MSB of the first pair
132@param[in] a_lo LSB of the first pair
133@param[in] b_hi MSB of the second pair
134@param[in] b_lo LSB of the second pair */
135static inline void ut_pair_min(ulint *min_hi, ulint *min_lo, ulint a_hi,
136 ulint a_lo, ulint b_hi, ulint b_lo);
137#endif /* !UNIV_HOTBACKUP */
138
139/** Compares two ulints.
140@param[in] a ulint
141@param[in] b ulint
142@return 1 if a > b, 0 if a == b, -1 if a < b */
143static inline int ut_ulint_cmp(ulint a, ulint b);
144
145/** Compare two pairs of integers.
146@param[in] a_h more significant part of first pair
147@param[in] a_l less significant part of first pair
148@param[in] b_h more significant part of second pair
149@param[in] b_l less significant part of second pair
150@return comparison result of (a_h,a_l) and (b_h,b_l)
151@retval -1 if (a_h,a_l) is less than (b_h,b_l)
152@retval 0 if (a_h,a_l) is equal to (b_h,b_l)
153@retval 1 if (a_h,a_l) is greater than (b_h,b_l) */
154[[nodiscard]] static inline int ut_pair_cmp(ulint a_h, ulint a_l, ulint b_h,
155 ulint b_l);
156
157/** Calculates fast the remainder of n/m when m is a power of two.
158 @param n in: numerator
159 @param m in: denominator, must be a power of two
160 @return the remainder of n/m */
161#define ut_2pow_remainder(n, m) ((n) & ((m)-1))
162/** Calculates the biggest multiple of m that is not bigger than n
163 when m is a power of two. In other words, rounds n down to m * k.
164 @param n in: number to round down
165 @param m in: alignment, must be a power of two
166 @return n rounded down to the biggest possible integer multiple of m */
167#define ut_2pow_round(n, m) ((n) & ~((m)-1))
168/** Align a number down to a multiple of a power of two.
169@param n in: number to round down
170@param m in: alignment, must be a power of two
171@return n rounded down to the biggest possible integer multiple of m */
172#define ut_calc_align_down(n, m) ut_2pow_round(n, m)
173/** Calculates the smallest multiple of m that is not smaller than n
174 when m is a power of two. In other words, rounds n up to m * k.
175 @param n in: number to round up
176 @param m in: alignment, must be a power of two
177 @return n rounded up to the smallest possible integer multiple of m */
178#define ut_calc_align(n, m) (((n) + ((m)-1)) & ~((m)-1))
179/** Calculates fast the 2-logarithm of a number, rounded upward to an
180 integer.
181 @return logarithm in the base 2, rounded upward */
182constexpr ulint ut_2_log(ulint n); /*!< in: number */
183
184/** Calculates 2 to power n.
185@param[in] n power of 2
186@return 2 to power n */
187static inline uint32_t ut_2_exp(uint32_t n);
188
189/** Calculates fast the number rounded up to the nearest power of 2.
190@param[in] n number != 0
191@return first power of 2 which is >= n */
193
194/** Determine how many bytes (groups of 8 bits) are needed to
195store the given number of bits.
196@param b in: bits
197@return number of bytes (octets) needed to represent b */
198#define UT_BITS_IN_BYTES(b) (((b) + 7UL) / 8UL)
199
200/** Determines if a number is zero or a power of two.
201@param[in] n number
202@return nonzero if n is zero or a power of two; zero otherwise */
203#define ut_is_2pow(n) UNIV_LIKELY(!((n) & ((n)-1)))
204
205/** Functor that compares two C strings. Can be used as a comparator for
206e.g. std::map that uses char* as keys. */
208 bool operator()(const char *a, const char *b) const {
209 return (strcmp(a, b) < 0);
210 }
211};
212
213namespace ut {
214/** The current value of @@innodb_spin_wait_pause_multiplier. Determines
215how many PAUSE instructions to emit for each requested unit of delay
216when calling `ut_delay(delay)`. The default value of 50 causes `delay*50` PAUSES
217which was equivalent to `delay` microseconds on 100 MHz Pentium + Visual C++.
218Useful on processors which have "non-standard" duration of a single PAUSE
219instruction - one can compensate for longer PAUSES by setting the
220spin_wait_pause_multiplier to a smaller value on such machine */
221extern ulong spin_wait_pause_multiplier;
222} // namespace ut
223
224/** Runs an idle loop on CPU. The argument gives the desired delay
225 in microseconds on 100 MHz Pentium + Visual C++.
226 The actual duration depends on a product of `delay` and the current value of
227 @@innodb_spin_wait_pause_multiplier.
228 @param[in] delay delay in microseconds on 100 MHz Pentium, assuming
229 spin_wait_pause_multiplier is 50 (default).
230 @return dummy value */
231ulint ut_delay(ulint delay);
232
233/* Forward declaration of transaction handle */
234struct trx_t;
235
236/** Get a fixed-length string, quoted as an SQL identifier.
237If the string contains a slash '/', the string will be
238output as two identifiers separated by a period (.),
239as in SQL database_name.identifier.
240 @param [in] trx transaction (NULL=no quotes).
241 @param [in] name table name.
242 @retval String quoted as an SQL identifier.
243*/
244std::string ut_get_name(const trx_t *trx, const char *name);
245
246/** Outputs a fixed-length string, quoted as an SQL identifier.
247 If the string contains a slash '/', the string will be
248 output as two identifiers separated by a period (.),
249 as in SQL database_name.identifier. */
250void ut_print_name(FILE *f, /*!< in: output stream */
251 const trx_t *trx, /*!< in: transaction */
252 const char *name); /*!< in: table name to print */
253
254/** Format a table name, quoted as an SQL identifier.
255If the name contains a slash '/', the result will contain two
256identifiers separated by a period (.), as in SQL
257database_name.table_name.
258@see table_name_t
259@param[in] name table or index name
260@param[out] formatted formatted result, will be NUL-terminated
261@param[in] formatted_size size of the buffer in bytes
262@return pointer to 'formatted' */
263char *ut_format_name(const char *name, char *formatted, ulint formatted_size);
264
265/** Catenate files.
266@param[in] dest Output file
267@param[in] src Input file to be appended to output */
268void ut_copy_file(FILE *dest, FILE *src);
269
270/** Convert byte value to string with unit
271@param[in] data_bytes byte value
272@param[out] data_str formatted string */
273void ut_format_byte_value(uint64_t data_bytes, std::string &data_str);
274
275#ifdef _WIN32
276/** A substitute for vsnprintf(3), formatted output conversion into
277 a limited buffer. Note: this function DOES NOT return the number of
278 characters that would have been printed if the buffer was unlimited because
279 VC's _vsnprintf() returns -1 in this case and we would need to call
280 _vscprintf() in addition to estimate that but we would need another copy
281 of "ap" for that and VC does not provide va_copy(). */
282void ut_vsnprintf(char *str, /*!< out: string */
283 size_t size, /*!< in: str size */
284 const char *fmt, /*!< in: format */
285 va_list ap); /*!< in: format values */
286#else
287/** A wrapper for vsnprintf(3), formatted output conversion into
288 a limited buffer. Note: this function DOES NOT return the number of
289 characters that would have been printed if the buffer was unlimited because
290 VC's _vsnprintf() returns -1 in this case and we would need to call
291 _vscprintf() in addition to estimate that but we would need another copy
292 of "ap" for that and VC does not provide va_copy(). */
293#define ut_vsnprintf(buf, size, fmt, ap) ((void)vsnprintf(buf, size, fmt, ap))
294#endif /* _WIN32 */
295
296/** Convert an error number to a human readable text message. The
297 returned string is static and should not be freed or modified.
298 @return string, describing the error */
299const char *ut_strerr(dberr_t num); /*!< in: error number */
300
301namespace ib {
302
303/** For measuring time elapsed. Since std::chrono::high_resolution_clock
304may be influenced by a change in system time, it might not be steady.
305So we use std::chrono::steady_clock for elapsed time. */
306class Timer {
307 public:
308 using SC = std::chrono::steady_clock;
309
310 public:
311 /** Constructor. Starts/resets the timer to the current time. */
312 Timer() noexcept { reset(); }
313
314 /** Reset the timer to the current time. */
315 void reset() { m_start = SC::now(); }
316
317 /** @return the time elapsed in milliseconds. */
318 template <typename T = std::chrono::milliseconds>
319 int64_t elapsed() const noexcept {
320 return std::chrono::duration_cast<T>(SC::now() - m_start).count();
321 }
322
323 /** Print time elapsed since last reset (in milliseconds) to the stream.
324 @param[in,out] out Stream to write to.
325 @param[in] timer Timer to write to the stream.
326 @return stream instance that was passed in. */
327 template <typename T, typename Traits>
328 friend std::basic_ostream<T, Traits> &operator<<(
329 std::basic_ostream<T, Traits> &out, const Timer &timer) noexcept {
330 return out << timer.elapsed();
331 }
332
333 private:
334 /** High resolution timer instance used for timimg. */
335 SC::time_point m_start;
336};
337
338} // namespace ib
339
340#ifdef UNIV_HOTBACKUP
341/** Sprintfs a timestamp to a buffer with no spaces and with ':' characters
342replaced by '_'.
343@param[in] buf buffer where to sprintf */
344void meb_sprintf_timestamp_without_extra_chars(char *buf);
345#endif /* UNIV_HOTBACKUP */
346
348 uint64_t wait_loops;
349
350 explicit Wait_stats(uint64_t wait_loops = 0) : wait_loops(wait_loops) {}
351
353 wait_loops += rhs.wait_loops;
354 return (*this);
355 }
356
357 Wait_stats operator+(const Wait_stats &rhs) const {
358 return (Wait_stats{wait_loops + rhs.wait_loops});
359 }
360
361 bool any_waits() const { return (wait_loops != 0); }
362};
363
364namespace ib {
365
366/** Allows to monitor an event processing times, allowing to throttle the
367processing to one per throttle_delay_sec. */
369 using seconds = std::chrono::duration<uint64_t>;
370 using clock = std::chrono::steady_clock;
371 using time_point = std::chrono::time_point<clock, seconds>;
372
373 public:
374 explicit Throttler(seconds delay = seconds{10})
376
377 /** Checks if the item should be processed or ignored to not process them more
378 frequently than one per throttle_delay_sec. */
379 bool apply() {
380 const time_point current_time_in_sec =
381 std::chrono::time_point_cast<seconds>(clock::now());
382 auto last_apply_time = m_last_applied_time.load();
383 if (last_apply_time + m_throttle_delay < current_time_in_sec) {
384 if (m_last_applied_time.compare_exchange_strong(last_apply_time,
385 current_time_in_sec)) {
386 return true;
387 }
388 /* Any race condition with other threads would mean someone just changed
389 the `m_last_apply_time` and will print the message. We don't want
390 to retry the operation again. */
391 }
392 return false;
393 }
394
395 private:
396 /* Time when the last item was not throttled. Stored as number of seconds
397 since epoch. */
398 std::atomic<time_point> m_last_applied_time;
399 static_assert(decltype(m_last_applied_time)::is_always_lock_free);
400
401 /** Throttle all items within that amount seconds from the last non throttled
402 one. */
404};
405
406} // namespace ib
407
408namespace ut {
409
410template <typename T, typename U>
411constexpr bool can_type_fit_value(const U value) {
412 return ((value > U(0)) == (T(value) > T(0))) && U(T(value)) == value;
413}
414template <typename T, typename U>
415T clamp(U x) {
416 return can_type_fit_value<T>(x) ? T(x)
417 : x < 0 ? std::numeric_limits<T>::min()
418 : std::numeric_limits<T>::max();
419}
420
421} // namespace ut
422
423#include "ut0ut.ic"
424
425#endif /* !ut0ut_h */
Allows to monitor an event processing times, allowing to throttle the processing to one per throttle_...
Definition: ut0ut.h:368
std::atomic< time_point > m_last_applied_time
Definition: ut0ut.h:398
Throttler(seconds delay=seconds{10})
Definition: ut0ut.h:374
std::chrono::steady_clock clock
Definition: ut0ut.h:370
std::chrono::duration< uint64_t > seconds
Definition: ut0ut.h:369
const seconds m_throttle_delay
Throttle all items within that amount seconds from the last non throttled one.
Definition: ut0ut.h:399
std::chrono::time_point< clock, seconds > time_point
Definition: ut0ut.h:371
bool apply()
Checks if the item should be processed or ignored to not process them more frequently than one per th...
Definition: ut0ut.h:379
For measuring time elapsed.
Definition: ut0ut.h:306
std::chrono::steady_clock SC
Definition: ut0ut.h:308
void reset()
Reset the timer to the current time.
Definition: ut0ut.h:315
SC::time_point m_start
High resolution timer instance used for timimg.
Definition: ut0ut.h:335
int64_t elapsed() const noexcept
Definition: ut0ut.h:319
friend std::basic_ostream< T, Traits > & operator<<(std::basic_ostream< T, Traits > &out, const Timer &timer) noexcept
Print time elapsed since last reset (in milliseconds) to the stream.
Definition: ut0ut.h:328
Timer() noexcept
Constructor.
Definition: ut0ut.h:312
#define U
Definition: ctype-tis620.cc:74
Global error codes for the database.
dberr_t
Definition: db0err.h:39
std::string str(const mysqlrouter::ConfigGenerator::Options::Endpoint &ep)
Definition: config_generator.cc:1105
Definition: buf0block_hint.cc:30
const std::string FILE("FILE")
Definition: ha_prototypes.h:342
size_t size(const char *const c)
Definition: base64.h:46
This file contains a set of libraries providing overloads for regular dynamic allocation routines whi...
Definition: aligned_alloc.h:48
ulong spin_wait_pause_multiplier
The current value of @innodb_spin_wait_pause_multiplier.
Definition: ut0ut.cc:65
constexpr bool can_type_fit_value(const U value)
Definition: ut0ut.h:411
T clamp(U x)
Definition: ut0ut.h:415
Macros for using atomics.
case opt name
Definition: sslopt-case.h:29
Definition: ut0ut.h:347
Wait_stats & operator+=(const Wait_stats &rhs)
Definition: ut0ut.h:352
Wait_stats(uint64_t wait_loops=0)
Definition: ut0ut.h:350
uint64_t wait_loops
Definition: ut0ut.h:348
Wait_stats operator+(const Wait_stats &rhs) const
Definition: ut0ut.h:357
bool any_waits() const
Definition: ut0ut.h:361
Definition: trx0trx.h:675
Functor that compares two C strings.
Definition: ut0ut.h:207
bool operator()(const char *a, const char *b) const
Definition: ut0ut.h:208
Include file for Sun RPC to compile out of the box.
Definition: dtoa.cc:595
unsigned long int ulint
Definition: univ.i:406
Debug utilities for Innobase.
void ut_copy_file(FILE *dest, FILE *src)
Catenate files.
Definition: ut0ut.cc:219
static int ut_pair_cmp(ulint a_h, ulint a_l, ulint b_h, ulint b_l)
Compare two pairs of integers.
const char * ut_strerr(dberr_t num)
Convert an error number to a human readable text message.
Definition: ut0ut.cc:290
ulint ut_2_power_up(ulint n)
Calculates fast the number rounded up to the nearest power of 2.
Definition: ut0ut.cc:123
#define ut_vsnprintf(buf, size, fmt, ap)
A wrapper for vsnprintf(3), formatted output conversion into a limited buffer.
Definition: ut0ut.h:293
static uint32_t ut_2_exp(uint32_t n)
Calculates 2 to power n.
char * ut_format_name(const char *name, char *formatted, ulint formatted_size)
Format a table name, quoted as an SQL identifier.
Definition: ut0ut.cc:189
void ut_format_byte_value(uint64_t data_bytes, std::string &data_str)
Convert byte value to string with unit.
Definition: ut0ut.cc:237
static int ut_ulint_cmp(ulint a, ulint b)
Compares two ulints.
std::string ut_get_name(const trx_t *trx, const char *name)
Get a fixed-length string, quoted as an SQL identifier.
Definition: ut0ut.cc:147
constexpr ulint ut_2_log(ulint n)
Calculates fast the 2-logarithm of a number, rounded upward to an integer.
Definition: ut0ut.ic:98
void ut_print_name(FILE *f, const trx_t *trx, const char *name)
Outputs a fixed-length string, quoted as an SQL identifier.
Definition: ut0ut.cc:163
ulint ut_delay(ulint delay)
Runs an idle loop on CPU.
Definition: ut0ut.cc:99
static void ut_pair_min(ulint *min_hi, ulint *min_lo, ulint a_hi, ulint a_lo, ulint b_hi, ulint b_lo)
Calculate the minimum of two pairs.
Various utilities.
Various utilities.
int n
Definition: xcom_base.cc:509