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