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