MySQL 9.4.0
Source Code Documentation
ut0ut.h
Go to the documentation of this file.
1/*****************************************************************************
2
3Copyright (c) 1994, 2025, 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#ifndef UNIV_HOTBACKUP
85#if defined(HAVE_PAUSE_INSTRUCTION)
86/* According to the gcc info page, asm volatile means that the
87instruction has important side-effects and must not be removed.
88Also asm volatile may trigger a memory barrier (spilling all registers
89to memory). */
90#define UT_RELAX_CPU() __asm__ __volatile__("pause")
91
92#elif defined(HAVE_FAKE_PAUSE_INSTRUCTION)
93#define UT_RELAX_CPU() __asm__ __volatile__("rep; nop")
94#elif defined _WIN32
95/* In the Win32 API, the x86 PAUSE instruction is executed by calling
96the YieldProcessor macro defined in WinNT.h. It is a CPU architecture-
97independent way by using YieldProcessor. */
98#define UT_RELAX_CPU() YieldProcessor()
99#elif defined(__aarch64__)
100/* A "yield" instruction in aarch64 is essentially a nop, and does not cause
101enough delay to help backoff. "isb" is a barrier that, especially inside a
102loop, creates a small delay without consuming ALU resources.
103Experiments shown that adding the isb instruction improves stability and reduces
104result jitter. Adding more delay to the UT_RELAX_CPU than a single isb reduces
105performance. */
106#define UT_RELAX_CPU() __asm__ __volatile__("isb" ::: "memory")
107#else
108#define UT_RELAX_CPU() __asm__ __volatile__("" ::: "memory")
109#endif
110
111#if defined(HAVE_HMT_PRIORITY_INSTRUCTION)
112#define UT_LOW_PRIORITY_CPU() __asm__ __volatile__("or 1,1,1")
113#define UT_RESUME_PRIORITY_CPU() __asm__ __volatile__("or 2,2,2")
114#else
115#define UT_LOW_PRIORITY_CPU() ((void)0)
116#define UT_RESUME_PRIORITY_CPU() ((void)0)
117#endif
118
119#else /* !UNIV_HOTBACKUP */
120#define UT_RELAX_CPU() /* No op */
121#endif /* !UNIV_HOTBACKUP */
122
123#ifndef UNIV_HOTBACKUP
124
125/** Calculate the minimum of two pairs.
126@param[out] min_hi MSB of the minimum pair
127@param[out] min_lo LSB of the minimum pair
128@param[in] a_hi MSB of the first pair
129@param[in] a_lo LSB of the first pair
130@param[in] b_hi MSB of the second pair
131@param[in] b_lo LSB of the second pair */
132static inline void ut_pair_min(ulint *min_hi, ulint *min_lo, ulint a_hi,
133 ulint a_lo, ulint b_hi, ulint b_lo);
134#endif /* !UNIV_HOTBACKUP */
135
136/** Compares two ulints.
137@param[in] a ulint
138@param[in] b ulint
139@return 1 if a > b, 0 if a == b, -1 if a < b */
140static inline int ut_ulint_cmp(ulint a, ulint b);
141
142/** Compare two pairs of integers.
143@param[in] a_h more significant part of first pair
144@param[in] a_l less significant part of first pair
145@param[in] b_h more significant part of second pair
146@param[in] b_l less significant part of second pair
147@return comparison result of (a_h,a_l) and (b_h,b_l)
148@retval -1 if (a_h,a_l) is less than (b_h,b_l)
149@retval 0 if (a_h,a_l) is equal to (b_h,b_l)
150@retval 1 if (a_h,a_l) is greater than (b_h,b_l) */
151[[nodiscard]] static inline int ut_pair_cmp(ulint a_h, ulint a_l, ulint b_h,
152 ulint b_l);
153
154/** Calculates fast the remainder of n/m when m is a power of two.
155 @param n in: numerator
156 @param m in: denominator, must be a power of two
157 @return the remainder of n/m */
158#define ut_2pow_remainder(n, m) ((n) & ((m)-1))
159/** Calculates the biggest multiple of m that is not bigger than n
160 when m is a power of two. In other words, rounds n down to m * k.
161 @param n in: number to round down
162 @param m in: alignment, must be a power of two
163 @return n rounded down to the biggest possible integer multiple of m */
164#define ut_2pow_round(n, m) ((n) & ~((m)-1))
165/** Align a number down to a multiple of a power of two.
166@param n in: number to round down
167@param m in: alignment, must be a power of two
168@return n rounded down to the biggest possible integer multiple of m */
169#define ut_calc_align_down(n, m) ut_2pow_round(n, m)
170/** Calculates the smallest multiple of m that is not smaller than n
171 when m is a power of two. In other words, rounds n up to m * k.
172 @param n in: number to round up
173 @param m in: alignment, must be a power of two
174 @return n rounded up to the smallest possible integer multiple of m */
175#define ut_calc_align(n, m) (((n) + ((m)-1)) & ~((m)-1))
176/** Calculates fast the 2-logarithm of a number, rounded upward to an
177 integer.
178 @return logarithm in the base 2, rounded upward */
179constexpr ulint ut_2_log(ulint n); /*!< in: number */
180
181/** Calculates 2 to power n.
182@param[in] n power of 2
183@return 2 to power n */
184static inline uint32_t ut_2_exp(uint32_t n);
185
186/** Calculates fast the number rounded up to the nearest power of 2.
187@param[in] n number != 0
188@return first power of 2 which is >= n */
190
191/** Determine how many bytes (groups of 8 bits) are needed to
192store the given number of bits.
193@param b in: bits
194@return number of bytes (octets) needed to represent b */
195#define UT_BITS_IN_BYTES(b) (((b) + 7UL) / 8UL)
196
197/** Determines if a number is zero or a power of two.
198@param[in] n number
199@return nonzero if n is zero or a power of two; zero otherwise */
200#define ut_is_2pow(n) UNIV_LIKELY(!((n) & ((n)-1)))
201
202/** Functor that compares two C strings. Can be used as a comparator for
203e.g. std::map that uses char* as keys. */
205 bool operator()(const char *a, const char *b) const {
206 return (strcmp(a, b) < 0);
207 }
208};
209
210namespace ut {
211/** The current value of @@innodb_spin_wait_pause_multiplier. Determines
212how many PAUSE instructions to emit for each requested unit of delay
213when calling `ut_delay(delay)`. The default value of 50 causes `delay*50` PAUSES
214which was equivalent to `delay` microseconds on 100 MHz Pentium + Visual C++.
215Useful on processors which have "non-standard" duration of a single PAUSE
216instruction - one can compensate for longer PAUSES by setting the
217spin_wait_pause_multiplier to a smaller value on such machine */
218extern ulong spin_wait_pause_multiplier;
219} // namespace ut
220
221/** Runs an idle loop on CPU. The argument gives the desired delay
222 in microseconds on 100 MHz Pentium + Visual C++.
223 The actual duration depends on a product of `delay` and the current value of
224 @@innodb_spin_wait_pause_multiplier.
225 @param[in] delay delay in microseconds on 100 MHz Pentium, assuming
226 spin_wait_pause_multiplier is 50 (default).
227 @return dummy value */
228ulint ut_delay(ulint delay);
229
230/* Forward declaration of transaction handle */
231struct trx_t;
232
233/** Get a fixed-length string, quoted as an SQL identifier.
234If the string contains a slash '/', the string will be
235output as two identifiers separated by a period (.),
236as in SQL database_name.identifier.
237 @param [in] trx transaction (NULL=no quotes).
238 @param [in] name table name.
239 @retval String quoted as an SQL identifier.
240*/
241std::string ut_get_name(const trx_t *trx, const char *name);
242
243/** Outputs a fixed-length string, quoted as an SQL identifier.
244 If the string contains a slash '/', the string will be
245 output as two identifiers separated by a period (.),
246 as in SQL database_name.identifier. */
247void ut_print_name(FILE *f, /*!< in: output stream */
248 const trx_t *trx, /*!< in: transaction */
249 const char *name); /*!< in: table name to print */
250
251/** Format a table name, quoted as an SQL identifier.
252If the name contains a slash '/', the result will contain two
253identifiers separated by a period (.), as in SQL
254database_name.table_name.
255@see table_name_t
256@param[in] name table or index name
257@param[out] formatted formatted result, will be NUL-terminated
258@param[in] formatted_size size of the buffer in bytes
259@return pointer to 'formatted' */
260char *ut_format_name(const char *name, char *formatted, ulint formatted_size);
261
262/** Catenate files.
263@param[in] dest Output file
264@param[in] src Input file to be appended to output */
265void ut_copy_file(FILE *dest, FILE *src);
266
267/** Convert byte value to string with unit
268@param[in] data_bytes byte value
269@param[out] data_str formatted string */
270void ut_format_byte_value(uint64_t data_bytes, std::string &data_str);
271
272#ifdef _WIN32
273/** A substitute for vsnprintf(3), formatted output conversion into
274 a limited buffer. Note: this function DOES NOT return the number of
275 characters that would have been printed if the buffer was unlimited because
276 VC's _vsnprintf() returns -1 in this case and we would need to call
277 _vscprintf() in addition to estimate that but we would need another copy
278 of "ap" for that and VC does not provide va_copy(). */
279void ut_vsnprintf(char *str, /*!< out: string */
280 size_t size, /*!< in: str size */
281 const char *fmt, /*!< in: format */
282 va_list ap); /*!< in: format values */
283#else
284/** A wrapper for vsnprintf(3), formatted output conversion into
285 a limited buffer. Note: this function DOES NOT return the number of
286 characters that would have been printed if the buffer was unlimited because
287 VC's _vsnprintf() returns -1 in this case and we would need to call
288 _vscprintf() in addition to estimate that but we would need another copy
289 of "ap" for that and VC does not provide va_copy(). */
290#define ut_vsnprintf(buf, size, fmt, ap) ((void)vsnprintf(buf, size, fmt, ap))
291#endif /* _WIN32 */
292
293/** Convert an error number to a human readable text message. The
294 returned string is static and should not be freed or modified.
295 @return string, describing the error */
296const char *ut_strerr(dberr_t num); /*!< in: error number */
297
298namespace ib {
299
300/** For measuring time elapsed. Since std::chrono::high_resolution_clock
301may be influenced by a change in system time, it might not be steady.
302So we use std::chrono::steady_clock for elapsed time. */
303class Timer {
304 public:
305 using SC = std::chrono::steady_clock;
306
307 public:
308 /** Constructor. Starts/resets the timer to the current time. */
309 Timer() noexcept { reset(); }
310
311 /** Reset the timer to the current time. */
312 void reset() { m_start = SC::now(); }
313
314 /** @return the time elapsed in milliseconds. */
315 template <typename T = std::chrono::milliseconds>
316 int64_t elapsed() const noexcept {
317 return std::chrono::duration_cast<T>(SC::now() - m_start).count();
318 }
319
320 /** Print time elapsed since last reset (in milliseconds) to the stream.
321 @param[in,out] out Stream to write to.
322 @param[in] timer Timer to write to the stream.
323 @return stream instance that was passed in. */
324 template <typename T, typename Traits>
325 friend std::basic_ostream<T, Traits> &operator<<(
326 std::basic_ostream<T, Traits> &out, const Timer &timer) noexcept {
327 return out << timer.elapsed();
328 }
329
330 private:
331 /** High resolution timer instance used for timimg. */
332 SC::time_point m_start;
333};
334
335} // namespace ib
336
337#ifdef UNIV_HOTBACKUP
338/** Sprintfs a timestamp to a buffer with no spaces and with ':' characters
339replaced by '_'.
340@param[in] buf buffer where to sprintf */
341void meb_sprintf_timestamp_without_extra_chars(char *buf);
342#endif /* UNIV_HOTBACKUP */
343
345 uint64_t wait_loops;
346
347 explicit Wait_stats(uint64_t wait_loops = 0) : wait_loops(wait_loops) {}
348
350 wait_loops += rhs.wait_loops;
351 return (*this);
352 }
353
354 Wait_stats operator+(const Wait_stats &rhs) const {
355 return (Wait_stats{wait_loops + rhs.wait_loops});
356 }
357
358 bool any_waits() const { return (wait_loops != 0); }
359};
360
361namespace ib {
362
363/** Allows to monitor an event processing times, allowing to throttle the
364processing to one per throttle_delay_sec. */
366 using seconds = std::chrono::duration<uint64_t>;
367 using clock = std::chrono::steady_clock;
368 using time_point = std::chrono::time_point<clock, seconds>;
369
370 public:
371 explicit Throttler(seconds delay = seconds{10})
373
374 /** Checks if the item should be processed or ignored to not process them more
375 frequently than one per throttle_delay_sec. */
376 bool apply() {
377 const time_point current_time_in_sec =
378 std::chrono::time_point_cast<seconds>(clock::now());
379 auto last_apply_time = m_last_applied_time.load();
380 if (last_apply_time + m_throttle_delay < current_time_in_sec) {
381 if (m_last_applied_time.compare_exchange_strong(last_apply_time,
382 current_time_in_sec)) {
383 return true;
384 }
385 /* Any race condition with other threads would mean someone just changed
386 the `m_last_apply_time` and will print the message. We don't want
387 to retry the operation again. */
388 }
389 return false;
390 }
391
392 private:
393 /* Time when the last item was not throttled. Stored as number of seconds
394 since epoch. */
395 std::atomic<time_point> m_last_applied_time;
396 static_assert(decltype(m_last_applied_time)::is_always_lock_free);
397
398 /** Throttle all items within that amount seconds from the last non throttled
399 one. */
401};
402
403} // namespace ib
404
405namespace ut {
406
407template <typename T, typename U>
408constexpr bool can_type_fit_value(const U value) {
409 return ((value > U(0)) == (T(value) > T(0))) && U(T(value)) == value;
410}
411template <typename T, typename U>
413 return can_type_fit_value<T>(x) ? T(x)
414 : x < 0 ? std::numeric_limits<T>::min()
416}
417
418} // namespace ut
419
420#include "ut0ut.ic"
421
422#endif /* !ut0ut_h */
Allows to monitor an event processing times, allowing to throttle the processing to one per throttle_...
Definition: ut0ut.h:365
std::atomic< time_point > m_last_applied_time
Definition: ut0ut.h:395
Throttler(seconds delay=seconds{10})
Definition: ut0ut.h:371
std::chrono::steady_clock clock
Definition: ut0ut.h:367
std::chrono::duration< uint64_t > seconds
Definition: ut0ut.h:366
const seconds m_throttle_delay
Throttle all items within that amount seconds from the last non throttled one.
Definition: ut0ut.h:396
std::chrono::time_point< clock, seconds > time_point
Definition: ut0ut.h:368
bool apply()
Checks if the item should be processed or ignored to not process them more frequently than one per th...
Definition: ut0ut.h:376
For measuring time elapsed.
Definition: ut0ut.h:303
std::chrono::steady_clock SC
Definition: ut0ut.h:305
void reset()
Reset the timer to the current time.
Definition: ut0ut.h:312
SC::time_point m_start
High resolution timer instance used for timimg.
Definition: ut0ut.h:332
int64_t elapsed() const noexcept
Definition: ut0ut.h:316
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:325
Timer() noexcept
Constructor.
Definition: ut0ut.h:309
#define U
Definition: ctype-tis620.cc:73
Global error codes for the database.
dberr_t
Definition: db0err.h:39
#define T
Definition: jit_executor_value.cc:373
std::string str(const mysqlrouter::ConfigGenerator::Options::Endpoint &ep)
Definition: config_generator.cc:1084
Definition: buf0block_hint.cc:30
const std::string FILE("FILE")
Definition: ha_prototypes.h:342
ValueType value(const std::optional< ValueType > &v)
Definition: gtid.h:83
ValueType max(X &&first)
Definition: gtid.h:103
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:61
constexpr bool can_type_fit_value(const U value)
Definition: ut0ut.h:408
T clamp(U x)
Definition: ut0ut.h:412
Macros for using atomics.
case opt name
Definition: sslopt-case.h:29
Definition: ut0ut.h:344
Wait_stats & operator+=(const Wait_stats &rhs)
Definition: ut0ut.h:349
Wait_stats(uint64_t wait_loops=0)
Definition: ut0ut.h:347
uint64_t wait_loops
Definition: ut0ut.h:345
Wait_stats operator+(const Wait_stats &rhs) const
Definition: ut0ut.h:354
bool any_waits() const
Definition: ut0ut.h:358
Definition: trx0trx.h:675
Functor that compares two C strings.
Definition: ut0ut.h:204
bool operator()(const char *a, const char *b) const
Definition: ut0ut.h:205
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:215
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:286
ulint ut_2_power_up(ulint n)
Calculates fast the number rounded up to the nearest power of 2.
Definition: ut0ut.cc:119
#define ut_vsnprintf(buf, size, fmt, ap)
A wrapper for vsnprintf(3), formatted output conversion into a limited buffer.
Definition: ut0ut.h:290
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:185
void ut_format_byte_value(uint64_t data_bytes, std::string &data_str)
Convert byte value to string with unit.
Definition: ut0ut.cc:233
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:143
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:159
ulint ut_delay(ulint delay)
Runs an idle loop on CPU.
Definition: ut0ut.cc:95
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