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