Debian Codegraph @

storage/innobase/srv/srv0srv.cc

raw
1 /*****************************************************************************
2
3 Copyright (c) 1995, 2026, Oracle and/or its affiliates.
4 Copyright (c) 2008, 2009 Google Inc.
5 Copyright (c) 2009, Percona Inc.
6
7 Portions of this file contain modifications contributed and copyrighted by
8 Google, Inc. Those modifications are gratefully acknowledged and are described
9 briefly in the InnoDB documentation. The contributions by Google are
10 incorporated with their permission, and subject to the conditions contained in
11 the file COPYING.Google.
12
13 Portions of this file contain modifications contributed and copyrighted
14 by Percona Inc.. Those modifications are
15 gratefully acknowledged and are described briefly in the InnoDB
16 documentation. The contributions by Percona Inc. are incorporated with
17 their permission, and subject to the conditions contained in the file
18 COPYING.Percona.
19
20 This program is free software; you can redistribute it and/or modify it under
21 the terms of the GNU General Public License, version 2.0, as published by the
22 Free Software Foundation.
23
24 This program is designed to work with certain software (including
25 but not limited to OpenSSL) that is licensed under separate terms,
26 as designated in a particular file or component or in included license
27 documentation. The authors of MySQL hereby grant you an additional
28 permission to link the program and your derivative works with the
29 separately licensed software that they have either included with
30 the program or referenced in the documentation.
31
32 This program is distributed in the hope that it will be useful, but WITHOUT
33 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
34 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
35 for more details.
36
37 You should have received a copy of the GNU General Public License along with
38 this program; if not, write to the Free Software Foundation, Inc.,
39 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
40
41 *****************************************************************************/
42
43 /** @file srv/srv0srv.cc
44 The database server main program
45
46 Created 10/8/1995 Heikki Tuuri
47 *******************************************************/
48
49 #ifndef UNIV_HOTBACKUP
50 #include <mysqld.h>
51 #include <sys/types.h>
52 #include <time.h>
53
54 #include <chrono>
55 #include <limits>
56
57 #include "btr0sea.h"
58 #include "buf0flu.h"
59 #include "buf0lru.h"
60 #include "clone0api.h"
61 #include "dict0boot.h"
62 #include "dict0load.h"
63 #include "dict0stats_bg.h"
64 #include "fsp0sysspace.h"
65 #include "ha_prototypes.h"
66 #endif /* !UNIV_HOTBACKUP */
67 #include "ibuf0ibuf.h"
68 #ifndef UNIV_HOTBACKUP
69 #include "lock0lock.h"
70 #include "log0buf.h"
71 #include "log0chkp.h"
72 #include "log0encryption.h"
73 #include "log0recv.h"
74 #include "log0write.h"
75 #include "mem0mem.h"
76 #include "os0proc.h"
77 #include "os0thread-create.h"
78 #include "pars0pars.h"
79 #include "que0que.h"
80 #include "row0mysql.h"
81 #include "sql/sql_class.h"
82 #include "sql_thd_internal_api.h"
83 #include "srv0mon.h"
84
85 #include "my_dbug.h"
86 #include "my_psi_config.h"
87
88 #endif /* !UNIV_HOTBACKUP */
89 #include "srv0srv.h"
90 #include "srv0start.h"
91 #include "sync0sync.h"
92 #ifndef UNIV_HOTBACKUP
93 #include "trx0i_s.h"
94 #include "trx0purge.h"
95 #include "usr0sess.h"
96 #include "ut0crc32.h"
97 #endif /* !UNIV_HOTBACKUP */
98 #include "ut0mem.h"
99
100 #ifdef UNIV_HOTBACKUP
101 #include "page0size.h"
102 #else
103 /** Structure with state of srv background threads. */
104 Srv_threads srv_threads;
105
106 /** Structure with cpu usage information. */
107 Srv_cpu_usage srv_cpu_usage;
108 #endif /* UNIV_HOTBACKUP */
109
110 #ifdef INNODB_DD_TABLE
111 /* true when upgrading. */
112 bool srv_is_upgrade_mode = false;
113 bool srv_downgrade_logs = false;
114 bool srv_upgrade_old_undo_found = false;
115 #endif /* INNODB_DD_TABLE */
116
117 /* Revert to old partition file name if upgrade fails. */
118 bool srv_downgrade_partition_files = false;
119
120 /* The following is the maximum allowed duration of a lock wait. */
121 ulong srv_fatal_semaphore_wait_threshold = 600;
122 std::atomic<int> srv_fatal_semaphore_wait_extend{0};
123
124 std::chrono::seconds get_srv_fatal_semaphore_wait_threshold() {
125 return std::chrono::seconds{srv_fatal_semaphore_wait_threshold};
126 }
127
128 /* How much data manipulation language (DML) statements need to be delayed,
129 in microseconds, in order to reduce the lagging of the purge thread. */
130 ulint srv_dml_needed_delay = 0;
131
132 const char *srv_main_thread_op_info = "";
133
134 /* Server parameters which are read from the initfile */
135
136 /* The following three are dir paths which are concatenated before file
137 names, where the file name itself may also contain a path */
138
139 char *srv_data_home = nullptr;
140
141 /** Separate directory for doublewrite files, if it is not NULL */
142 char *srv_doublewrite_dir = nullptr;
143
144 /** The innodb_directories variable value. This a list of directories
145 deliminated by ';', i.e the FIL_PATH_SEPARATOR. */
146 char *srv_innodb_directories = nullptr;
147
148 /** Number of threads spawned for initializing rollback segments
149 in parallel */
150 uint32_t srv_rseg_init_threads = 1;
151
152 /** Undo tablespace directories. This can be multiple paths
153 separated by ';' and can also be absolute paths. */
154 char *srv_undo_dir = nullptr;
155
156 /** The number of implicit undo tablespaces to use for rollback
157 segments. */
158 ulong srv_undo_tablespaces = FSP_IMPLICIT_UNDO_TABLESPACES;
159
160 #ifndef UNIV_HOTBACKUP
161 /* The number of rollback segments per tablespace */
162 ulong srv_rollback_segments = TRX_SYS_N_RSEGS;
163
164 /* Used for the deprecated setting innodb_undo_logs. This will still get
165 put into srv_rollback_segments if it is set to a non-default value. */
166 ulong srv_undo_logs = 0;
167 const char *deprecated_undo_logs =
168 "The parameter innodb_undo_logs is deprecated"
169 " and may be removed in future releases."
170 " Please use innodb_rollback_segments instead."
171 " See " REFMAN "innodb-undo-logs.html";
172
173 /** Rate at which UNDO records should be purged. */
174 ulong srv_purge_rseg_truncate_frequency =
175 static_cast<ulong>(undo::TRUNCATE_FREQUENCY);
176 #endif /* !UNIV_HOTBACKUP */
177
178 /** Enable or Disable Truncate of UNDO tablespace.
179 Note: If enabled then UNDO tablespace will be selected for truncate.
180 While Server waits for undo-tablespace to truncate if user disables
181 it, truncate action is completed but no new tablespace is marked
182 for truncate (action is never aborted). */
183 bool srv_undo_log_truncate = false;
184
185 /** Enable or disable Encrypt of UNDO tablespace. */
186 bool srv_undo_log_encrypt = false;
187
188 /** Maximum size of undo tablespace. */
189 unsigned long long srv_max_undo_tablespace_size;
190
191 /** Maximum number of recently truncated undo tablespace IDs for
192 the same undo number. */
193 const size_t CONCURRENT_UNDO_TRUNCATE_LIMIT =
194 dict_sys_t::s_undo_space_id_range / 8;
195
196 /** Set if InnoDB must operate in read-only mode. We don't do any
197 recovery and open all tables in RO mode instead of RW mode. We don't
198 sync the max trx id to disk either. */
199 bool srv_read_only_mode;
200
201 /** store to its own file each table created by an user; data
202 dictionary tables are in the system tablespace 0 */
203 bool srv_file_per_table;
204
205 /** Sort buffer size in index creation */
206 ulong srv_sort_buf_size = 1048576;
207 /** Maximum modification log file size for online index creation */
208 unsigned long long srv_online_max_size;
209 /** Set if InnoDB operates in read-only mode or innodb-force-recovery
210 is greater than SRV_FORCE_NO_TRX_UNDO. */
211 bool high_level_read_only;
212
213 /** Number of threads to use for parallel reads. */
214 ulong srv_parallel_read_threads;
215
216 /** If this flag is true, then we will use the native aio of the
217 OS (provided we compiled Innobase with it in), otherwise we will
218 use simulated aio we build below with threads. */
219 bool srv_use_native_aio = false;
220
221 bool srv_numa_interleave = false;
222
223 #ifdef UNIV_DEBUG
224 /** Force all user tables to use page compression. */
225 ulong srv_debug_compress;
226 /** Set when InnoDB has invoked exit(). */
227 bool innodb_calling_exit;
228 /** Used by SET GLOBAL innodb_master_thread_disabled_debug = X. */
229 bool srv_master_thread_disabled_debug;
230 #ifndef UNIV_HOTBACKUP
231 /** Event used to inform that master thread is disabled. */
232 static os_event_t srv_master_thread_disabled_event;
233 #endif /* !UNIV_HOTBACKUP */
234 #endif /* UNIV_DEBUG */
235
236 /*------------------------- LOG FILES ------------------------ */
237 char *srv_log_group_home_dir = nullptr;
238
239 /** Enable or disable Encrypt of REDO tablespace. */
240 bool srv_redo_log_encrypt = false;
241
242 ulong srv_log_n_files = 100; /* Deprecated (used only for deprecated sysvar). */
243
244 ulonglong srv_log_file_size; /* Deprecated (used only for deprecated sysvar). */
245
246 ulonglong srv_redo_log_capacity, srv_redo_log_capacity_used;
247
248 #ifdef UNIV_DEBUG_DEDICATED
249 ulong srv_debug_system_mem_size;
250 #endif /* UNIV_DEBUG_DEDICATED */
251
252 /** Space for log buffer, expressed in bytes. Note, that log buffer
253 will use only the largest power of two, which is not greater than
254 the assigned space. */
255 ulong srv_log_buffer_size;
256
257 /** Size of block, used for writing ahead to avoid read-on-write. */
258 ulong srv_log_write_ahead_size;
259
260 /** Whether to activate/pause the log writer threads. */
261 bool srv_log_writer_threads;
262
263 /** Minimum absolute value of cpu time for which spin-delay is used. */
264 uint srv_log_spin_cpu_abs_lwm;
265
266 /** Maximum percentage of cpu time for which spin-delay is used. */
267 uint srv_log_spin_cpu_pct_hwm;
268
269 /** Maximum value of average log flush time for which spin-delay is used.
270 When flushing takes longer, user threads no longer spin when waiting for
271 flushed redo. Expressed in microseconds. */
272 ulong srv_log_wait_for_flush_spin_hwm;
273
274 /* EXPERIMENTAL sys vars below - we need defaults set explicitly here. */
275
276 /** When log writer follows links in the log recent written buffer,
277 it stops when it has reached at least that many bytes to write,
278 limiting how many bytes can be written in single call. */
279 ulong srv_log_write_max_size = INNODB_LOG_WRITE_MAX_SIZE_DEFAULT;
280
281 /** Number of events used for notifications about redo write. */
282 ulong srv_log_write_events = INNODB_LOG_EVENTS_DEFAULT;
283
284 /** Number of events used for notifications about redo flush. */
285 ulong srv_log_flush_events = INNODB_LOG_EVENTS_DEFAULT;
286
287 /** Number of slots in a small buffer, which is used to allow concurrent
288 writes to log buffer. The slots are addressed by LSN values modulo number
289 of the slots. */
290 ulong srv_log_recent_written_size = INNODB_LOG_RECENT_WRITTEN_SIZE_DEFAULT;
291
292 /** Number of slots in a small buffer, which is used to break requirement
293 for total order of dirty pages, when they are added to flush lists.
294 The slots are addressed by LSN values modulo number of the slots. */
295 ulong srv_log_recent_closed_size = INNODB_LOG_RECENT_CLOSED_SIZE_DEFAULT;
296
297 /** Number of spin iterations, when spinning and waiting for log buffer
298 written up to given LSN, before we fallback to loop with sleeps.
299 This is not used when user thread has to wait for log flushed to disk. */
300 ulong srv_log_wait_for_write_spin_delay =
301 INNODB_LOG_WAIT_FOR_WRITE_SPIN_DELAY_DEFAULT;
302
303 /** Timeout used when waiting for redo write (microseconds). */
304 ulong srv_log_wait_for_write_timeout =
305 INNODB_LOG_WAIT_FOR_WRITE_TIMEOUT_DEFAULT;
306
307 std::chrono::microseconds get_srv_log_wait_for_write_timeout() {
308 return std::chrono::microseconds{srv_log_wait_for_write_timeout};
309 }
310
311 /** Number of spin iterations, when spinning and waiting for log flushed. */
312 ulong srv_log_wait_for_flush_spin_delay =
313 INNODB_LOG_WAIT_FOR_FLUSH_SPIN_DELAY_DEFAULT;
314
315 /** Timeout used when waiting for redo flush (microseconds). */
316 ulong srv_log_wait_for_flush_timeout =
317 INNODB_LOG_WAIT_FOR_FLUSH_TIMEOUT_DEFAULT;
318
319 std::chrono::microseconds get_srv_log_wait_for_flush_timeout() {
320 return std::chrono::microseconds{srv_log_wait_for_flush_timeout};
321 }
322
323 /** Number of spin iterations, for which log writer thread is waiting
324 for new data to write or flush without sleeping. */
325 ulong srv_log_writer_spin_delay = INNODB_LOG_WRITER_SPIN_DELAY_DEFAULT;
326
327 /** Initial timeout used to wait on writer_event. */
328 ulong srv_log_writer_timeout = INNODB_LOG_WRITER_TIMEOUT_DEFAULT;
329
330 std::chrono::microseconds get_srv_log_writer_timeout() {
331 return std::chrono::microseconds{srv_log_writer_timeout};
332 }
333
334 /** Number of milliseconds every which a periodical checkpoint is written
335 by the log checkpointer thread (unless periodical checkpoints are disabled,
336 which is a case during initial phase of startup). */
337 ulong srv_log_checkpoint_every = INNODB_LOG_CHECKPOINT_EVERY_DEFAULT;
338
339 std::chrono::milliseconds get_srv_log_checkpoint_every() {
340 return std::chrono::milliseconds{srv_log_checkpoint_every};
341 }
342
343 /** Number of spin iterations, for which log flusher thread is waiting
344 for new data to flush, without sleeping. */
345 ulong srv_log_flusher_spin_delay = INNODB_LOG_FLUSHER_SPIN_DELAY_DEFAULT;
346
347 /** Initial timeout used to wait on flusher_event. */
348 ulong srv_log_flusher_timeout = INNODB_LOG_FLUSHER_TIMEOUT_DEFAULT;
349
350 std::chrono::microseconds get_srv_log_flusher_timeout() {
351 return std::chrono::microseconds{srv_log_flusher_timeout};
352 }
353
354 /** Number of spin iterations, for which log write notifier thread is waiting
355 for advanced flushed_to_disk_lsn without sleeping. */
356 ulong srv_log_write_notifier_spin_delay =
357 INNODB_LOG_WRITE_NOTIFIER_SPIN_DELAY_DEFAULT;
358
359 /** Initial timeout used to wait on write_notifier_event. */
360 ulong srv_log_write_notifier_timeout =
361 INNODB_LOG_WRITE_NOTIFIER_TIMEOUT_DEFAULT;
362
363 std::chrono::microseconds get_srv_log_write_notifier_timeout() {
364 return std::chrono::microseconds{srv_log_write_notifier_timeout};
365 }
366
367 /** Number of spin iterations, for which log flush notifier thread is waiting
368 for advanced flushed_to_disk_lsn without sleeping. */
369 ulong srv_log_flush_notifier_spin_delay =
370 INNODB_LOG_FLUSH_NOTIFIER_SPIN_DELAY_DEFAULT;
371
372 /** Initial timeout used to wait on flush_notifier_event. */
373 ulong srv_log_flush_notifier_timeout =
374 INNODB_LOG_FLUSH_NOTIFIER_TIMEOUT_DEFAULT;
375
376 std::chrono::microseconds get_srv_log_flush_notifier_timeout() {
377 return std::chrono::microseconds{srv_log_flush_notifier_timeout};
378 }
379
380 /* End of EXPERIMENTAL sys vars */
381
382 /** Whether to generate and require checksums on the redo log pages. */
383 bool srv_log_checksums;
384
385 #ifdef UNIV_DEBUG
386
387 bool srv_checkpoint_disabled = false;
388
389 bool srv_inject_too_many_concurrent_trxs = false;
390
391 #endif /* UNIV_DEBUG */
392
393 ulong srv_flush_log_at_trx_commit = 1;
394 uint srv_flush_log_at_timeout = 1;
395 std::chrono::seconds get_srv_flush_log_at_timeout() {
396 return std::chrono::seconds(srv_flush_log_at_timeout);
397 }
398 ulong srv_page_size = UNIV_PAGE_SIZE_DEF;
399 ulong srv_page_size_shift = UNIV_PAGE_SIZE_SHIFT_DEF;
400
401 page_size_t univ_page_size(0, 0, false);
402
403 /* Try to flush dirty pages so as to avoid IO bursts at
404 the checkpoints. */
405 bool srv_adaptive_flushing = true;
406
407 /* Allow IO bursts at the checkpoints ignoring io_capacity setting. */
408 bool srv_flush_sync = true;
409
410 /** Maximum number of times allowed to conditionally acquire
411 mutex before switching to blocking wait on the mutex */
412 #define MAX_MUTEX_NOWAIT 20
413
414 /** Check whether the number of failed nonblocking mutex
415 acquisition attempts exceeds maximum allowed value. If so,
416 srv_printf_innodb_monitor() will request mutex acquisition
417 with mutex_enter(), which will wait until it gets the mutex. */
418 #define MUTEX_NOWAIT(mutex_skipped) ((mutex_skipped) < MAX_MUTEX_NOWAIT)
419
420 /** Dedicated server setting */
421 bool srv_dedicated_server = true;
422 /** Requested size in bytes */
423 ulint srv_buf_pool_size = ULINT_MAX;
424 /** Minimum pool size in bytes */
425 const ulint srv_buf_pool_min_size = 5 * 1024 * 1024;
426 /** Default pool size in bytes */
427 const ulint srv_buf_pool_def_size = 128 * 1024 * 1024;
428 /** Maximum pool size in bytes */
429 const longlong srv_buf_pool_max_size = LLONG_MAX;
430 /** Requested buffer pool chunk size. Each buffer pool instance consists
431 of one or more chunks. */
432 ulonglong srv_buf_pool_chunk_unit;
433 /** Minimum buffer pool chunk size. */
434 const ulonglong srv_buf_pool_chunk_unit_min = (1024 * 1024);
435 /** The buffer pool chunk size must be a multiple of this number. */
436 const ulonglong srv_buf_pool_chunk_unit_blk_sz = (1024 * 1024);
437 /** Maximum buffer pool chunk size. */
438 const ulonglong srv_buf_pool_chunk_unit_max =
439 srv_buf_pool_max_size / MAX_BUFFER_POOLS;
440 /** Requested number of buffer pool instances */
441 ulong srv_buf_pool_instances;
442 /** Default number of buffer pool instances */
443 const ulong srv_buf_pool_instances_default = 0;
444 /** Number of locks to protect buf_pool->page_hash */
445 ulong srv_n_page_hash_locks = 16;
446 /** Whether to validate InnoDB tablespace paths on startup */
447 bool srv_validate_tablespace_paths = true;
448 /** Use fdatasync() instead of fsync(). */
449 bool srv_use_fdatasync = false;
450 /** Scan depth for LRU flush batch i.e.: number of blocks scanned*/
451 ulong srv_LRU_scan_depth = 1024;
452 /** Whether or not to flush neighbors of a block */
453 ulong srv_flush_neighbors = 1;
454 /** Previously requested size. Accesses protected by memory barriers. */
455 ulint srv_buf_pool_old_size = 0;
456 /** Current size as scaling factor for the other components */
457 ulint srv_buf_pool_base_size = 0;
458 /** Current size in bytes */
459 long long srv_buf_pool_curr_size = 0;
460 /** Dump this % of each buffer pool during BP dump */
461 ulong srv_buf_pool_dump_pct;
462 /** Lock table size in bytes */
463 ulint srv_lock_table_size = ULINT_MAX;
464
465 const ulong srv_idle_flush_pct_default = 100;
466 ulong srv_idle_flush_pct = srv_idle_flush_pct_default;
467
468 /* This parameter is deprecated. Use srv_n_io_[read|write]_threads
469 instead. */
470 ulong srv_n_read_io_threads;
471 ulong srv_n_write_io_threads;
472
473 /* Switch to enable random read ahead. */
474 bool srv_random_read_ahead = false;
475 /* User settable value of the number of pages that must be present
476 in the buffer cache and accessed sequentially for InnoDB to trigger a
477 readahead request. */
478 ulong srv_read_ahead_threshold = 56;
479
480 /** Maximum on-disk size of change buffer in terms of percentage
481 of the buffer pool. */
482 uint srv_change_buffer_max_size = CHANGE_BUFFER_DEFAULT_SIZE;
483
484 #ifndef _WIN32
485 enum srv_unix_flush_t srv_unix_file_flush_method = SRV_UNIX_FSYNC;
486 #else
487 enum srv_win_flush_t srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;
488 #endif /* _WIN32 */
489
490 /* Number of IO operations per second the server can do */
491 ulong srv_io_capacity = 200;
492 ulong srv_max_io_capacity = 400;
493
494 /* The number of page cleaner threads to use.*/
495 ulong srv_n_page_cleaners = 4;
496
497 /* The InnoDB main thread tries to keep the ratio of modified pages
498 in the buffer pool to all database pages in the buffer pool smaller than
499 the following number. But it is not guaranteed that the value stays below
500 that during a time of heavy update/insert activity. */
501
502 double srv_max_buf_pool_modified_pct = 75.0;
503 double srv_max_dirty_pages_pct_lwm = 0.0;
504
505 /* This is the percentage of log capacity at which adaptive flushing,
506 if enabled, will kick in. */
507 ulong srv_adaptive_flushing_lwm = 10;
508
509 /* Number of iterations over which adaptive flushing is averaged. */
510 ulong srv_flushing_avg_loops = 30;
511
512 /* The number of purge threads to use.*/
513 ulong srv_n_purge_threads = 4;
514
515 /* the number of pages to purge in one batch */
516 ulong srv_purge_batch_size = 20;
517
518 /* Internal setting for "innodb_stats_method". Decides how InnoDB treats
519 NULL value when collecting statistics. By default, it is set to
520 SRV_STATS_NULLS_EQUAL(0), ie. all NULL value are treated equal */
521 ulong srv_innodb_stats_method = SRV_STATS_NULLS_EQUAL;
522
523 bool tbsp_extend_and_initialize = true;
524
525 #ifndef UNIV_HOTBACKUP
526 srv_stats_t srv_stats;
527 #endif /* !UNIV_HOTBACKUP */
528
529 /* structure to pass status variables to MySQL */
530 export_var_t export_vars;
531
532 /** Normally 0. When nonzero, skip some phases of crash recovery,
533 starting from SRV_FORCE_IGNORE_CORRUPT, so that data can be recovered
534 by SELECT or mysqldump. When this is nonzero, we do not allow any user
535 modifications to the data. */
536 ulong srv_force_recovery;
537 #ifdef UNIV_DEBUG
538 /** Inject a crash at different steps of the recovery process.
539 This is for testing and debugging only. */
540 ulong srv_force_recovery_crash;
541 #endif /* UNIV_DEBUG */
542
543 /** Print all user-level transactions deadlocks to mysqld stderr */
544 bool srv_print_all_deadlocks = false;
545
546 /** Print all DDL logs to mysqld stderr */
547 bool srv_print_ddl_logs = false;
548
549 /** Enable INFORMATION_SCHEMA.innodb_cmp_per_index */
550 bool srv_cmp_per_index_enabled = false;
551
552 /** If innodb redo logging is enabled. */
553 bool srv_redo_log = true;
554
555 /** The value of the configuration parameter innodb_fast_shutdown,
556 controlling the InnoDB shutdown.
557
558 If innodb_fast_shutdown=0, InnoDB shutdown will purge all undo log
559 records (except XA PREPARE transactions) and complete the merge of the
560 entire change buffer, and then shut down the redo log.
561
562 If innodb_fast_shutdown=1, InnoDB shutdown will only flush the buffer
563 pool to data files, cleanly shutting down the redo log.
564
565 If innodb_fast_shutdown=2, shutdown will effectively 'crash' InnoDB
566 (but lose no committed transactions). */
567 ulong srv_fast_shutdown;
568
569 /* Generate a innodb_status.<pid> file */
570 bool srv_innodb_status = false;
571
572 /* When estimating number of different key values in an index, sample
573 this many index pages, there are 2 ways to calculate statistics:
574 * persistent stats that are calculated by ANALYZE TABLE and saved
575 in the innodb database.
576 * quick transient stats, that are used if persistent stats for the given
577 table/index are not found in the innodb database */
578 unsigned long long srv_stats_transient_sample_pages = 8;
579 bool srv_stats_persistent = true;
580 bool srv_stats_include_delete_marked = false;
581 unsigned long long srv_stats_persistent_sample_pages = 20;
582 bool srv_stats_auto_recalc = true;
583
584 ulong srv_replication_delay = 0;
585 std::chrono::milliseconds get_srv_replication_delay() {
586 return std::chrono::milliseconds{srv_replication_delay};
587 }
588
589 /*-------------------------------------------*/
590 ulong srv_n_spin_wait_rounds = 30;
591 ulong srv_spin_wait_delay = 6;
592 bool srv_priority_boost = true;
593
594 #ifndef UNIV_HOTBACKUP
595 static ulint srv_n_rows_inserted_old = 0;
596 static ulint srv_n_rows_updated_old = 0;
597 static ulint srv_n_rows_deleted_old = 0;
598 static ulint srv_n_rows_read_old = 0;
599
600 static ulint srv_n_system_rows_inserted_old = 0;
601 static ulint srv_n_system_rows_updated_old = 0;
602 static ulint srv_n_system_rows_deleted_old = 0;
603 static ulint srv_n_system_rows_read_old = 0;
604 #endif /* !UNIV_HOTBACKUP */
605
606 ulint srv_truncated_status_writes = 0;
607
608 bool srv_print_innodb_monitor = false;
609 std::atomic_uint32_t srv_innodb_needs_monitoring{0};
610 bool srv_print_innodb_lock_monitor = false;
611
612 /* Array of English strings describing the current state of an
613 i/o handler thread */
614
615 const char *srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
616 const char *srv_io_thread_function[SRV_MAX_N_IO_THREADS];
617
618 #ifndef UNIV_HOTBACKUP
619 static std::chrono::steady_clock::time_point srv_monitor_stats_refreshed_at;
620 #endif /* !UNIV_HOTBACKUP */
621
622 static ib_mutex_t srv_innodb_monitor_mutex;
623
624 /** Mutex protecting page_zip_stat_per_index */
625 ib_mutex_t page_zip_stat_per_index_mutex;
626
627 /* Mutex for locking srv_monitor_file. Not created if srv_read_only_mode */
628 ib_mutex_t srv_monitor_file_mutex;
629
630 /** Temporary file for innodb monitor output */
631 FILE *srv_monitor_file;
632 /** Mutex for locking srv_misc_tmpfile. Not created if srv_read_only_mode.
633 This mutex has a very low rank; threads reserving it should not
634 acquire any further latches or sleep before releasing this one. */
635 ib_mutex_t srv_misc_tmpfile_mutex;
636 /** Temporary file for miscellaneous diagnostic output */
637 FILE *srv_misc_tmpfile;
638
639 #ifndef UNIV_HOTBACKUP
640 static ulint srv_main_thread_process_no = 0;
641 static std::thread::id srv_main_thread_id{};
642
643 /* The following counts are used by the srv_master_thread. */
644
645 /** Iterations of the loop bounded by 'srv_active' label. */
646 static ulint srv_main_active_loops = 0;
647 /** Iterations of the loop bounded by the 'srv_idle' label. */
648 static ulint srv_main_idle_loops = 0;
649 /** Iterations of the loop bounded by the 'srv_shutdown' label. */
650 static ulint srv_main_shutdown_loops = 0;
651 /** Log writes involving flush. */
652 static ulint srv_log_writes_and_flush = 0;
653
654 #endif /* !UNIV_HOTBACKUP */
655
656 /* Interval in seconds at which various tasks are performed by the
657 master thread when server is active. In order to balance the workload,
658 we should try to keep intervals such that they are not multiple of
659 each other. For example, if we have intervals for various tasks
660 defined as 5, 10, 15, 60 then all tasks will be performed when
661 current_time % 60 == 0 and no tasks will be performed when
662 current_time % 5 != 0. */
663
664 constexpr std::chrono::seconds SRV_MASTER_DICT_LRU_INTERVAL{47};
665
666 /** Acquire the system_mutex. */
667 #define srv_sys_mutex_enter() \
668 do { \
669 mutex_enter(&srv_sys->mutex); \
670 } while (0)
671
672 /** Test if the system mutex is owned. */
673 #define srv_sys_mutex_own() (mutex_own(&srv_sys->mutex) && !srv_read_only_mode)
674
675 /** Release the system mutex. */
676 #define srv_sys_mutex_exit() \
677 do { \
678 mutex_exit(&srv_sys->mutex); \
679 } while (0)
680
681 #ifndef UNIV_HOTBACKUP
682 /*
683 IMPLEMENTATION OF THE SERVER MAIN PROGRAM
684 =========================================
685
686 There is the following analogue between this database
687 server and an operating system kernel:
688
689 DB concept equivalent OS concept
690 ---------- ---------------------
691 transaction -- process;
692
693 query thread -- thread;
694
695 lock -- semaphore;
696
697 kernel -- kernel;
698
699 query thread execution:
700 (a) without lock mutex
701 reserved -- process executing in user mode;
702 (b) with lock mutex reserved
703 -- process executing in kernel mode;
704
705 The server has several backgroind threads all running at the same
706 priority as user threads. It periodically checks if here is anything
707 happening in the server which requires intervention of the master
708 thread. Such situations may be, for example, when flushing of dirty
709 blocks is needed in the buffer pool or old version of database rows
710 have to be cleaned away (purged). The user can configure a separate
711 dedicated purge thread(s) too, in which case the master thread does not
712 do any purging.
713
714 The threads which we call user threads serve the queries of the MySQL
715 server. They run at normal priority.
716
717 When there is no activity in the system, also the master thread
718 suspends itself to wait for an event making the server totally silent.
719
720 There is still one complication in our server design. If a
721 background utility thread obtains a resource (e.g., mutex) needed by a user
722 thread, and there is also some other user activity in the system,
723 the user thread may have to wait indefinitely long for the
724 resource, as the OS does not schedule a background thread if
725 there is some other runnable user thread. This problem is called
726 priority inversion in real-time programming.
727
728 One solution to the priority inversion problem would be to keep record
729 of which thread owns which resource and in the above case boost the
730 priority of the background thread so that it will be scheduled and it
731 can release the resource. This solution is called priority inheritance
732 in real-time programming. A drawback of this solution is that the overhead
733 of acquiring a mutex increases slightly, maybe 0.2 microseconds on a 100
734 MHz Pentium, because the thread has to call std::this_thread::get_id(). This
735 may be compared to 0.5 microsecond overhead for a mutex lock-unlock pair. Note
736 that the thread cannot store the information in the resource , say mutex,
737 itself, because competing threads could wipe out the information if it is
738 stored before acquiring the mutex, and if it stored afterwards, the
739 information is outdated for the time of one machine instruction, at least.
740 (To be precise, the information could be stored to lock_word in mutex if
741 the machine supports atomic swap.)
742
743 The above solution with priority inheritance may become actual in the
744 future, currently we do not implement any priority twiddling solution.
745 Our general aim is to reduce the contention of all mutexes by making
746 them more fine grained.
747
748 The thread table contains information of the current status of each
749 thread existing in the system, and also the event semaphores used in
750 suspending the master thread and utility threads when they have nothing
751 to do. The thread table can be seen as an analogue to the process table
752 in a traditional Unix implementation. */
753
754 /** The server system struct */
755 struct srv_sys_t {
756 ib_mutex_t tasks_mutex; /*!< variable protecting the
757 tasks queue */
758 UT_LIST_BASE_NODE_T(que_thr_t, queue)
759 tasks; /*!< task queue */
760
761 ib_mutex_t mutex; /*!< variable protecting the
762 fields below. */
763 ulint n_sys_threads; /*!< size of the sys_threads
764 array */
765
766 srv_slot_t *sys_threads; /*!< server thread table */
767
768 ulint n_threads_active[SRV_MASTER + 1];
769 /*!< number of threads active
770 in a thread class */
771
772 srv_stats_t::ulint_ctr_1_t activity_count; /*!< For tracking server
773 activity */
774 };
775
776 static srv_sys_t *srv_sys = nullptr;
777
778 /** Event to signal the monitor thread. */
779 os_event_t srv_monitor_event;
780
781 /** Event to signal the error thread */
782 os_event_t srv_error_event;
783
784 /** Event to signal the buffer pool dump/load thread */
785 os_event_t srv_buf_dump_event;
786
787 /** Event to signal the buffer pool resize thread */
788 os_event_t srv_buf_resize_event;
789
790 /** The buffer pool dump/load file name */
791 char *srv_buf_dump_filename;
792
793 /** Boolean config knobs that tell InnoDB to dump the buffer pool at shutdown
794 and/or load it during startup. */
795 bool srv_buffer_pool_dump_at_shutdown = true;
796 bool srv_buffer_pool_load_at_startup = true;
797
798 /** Slot index in the srv_sys->sys_threads array for the purge thread. */
799 static const ulint SRV_PURGE_SLOT = 1;
800
801 /** Slot index in the srv_sys->sys_threads array for the master thread. */
802 static const ulint SRV_MASTER_SLOT = 0;
803
804 #ifdef HAVE_PSI_STAGE_INTERFACE
805 /** Performance schema stage event for monitoring ALTER TABLE progress
806 everything after flush log_make_latest_checkpoint(). */
807 PSI_stage_info srv_stage_alter_table_end = {
808 0, "alter table (end)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
809
810 /** Performance schema stage event for monitoring ALTER TABLE progress
811 log_make_latest_checkpoint(). */
812 PSI_stage_info srv_stage_alter_table_flush = {
813 0, "alter table (flush)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
814
815 /** Performance schema stage event for monitoring ALTER TABLE progress. */
816 PSI_stage_info srv_stage_alter_table_insert = {
817 0, "alter table (insert)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
818
819 /** Performance schema stage event for monitoring ALTER TABLE progress
820 row_log_apply(). */
821 PSI_stage_info srv_stage_alter_table_log_index = {
822 0, "alter table (log apply index)", PSI_FLAG_STAGE_PROGRESS,
823 PSI_DOCUMENT_ME};
824
825 /** Performance schema stage event for monitoring ALTER TABLE progress
826 row_log_table_apply(). */
827 PSI_stage_info srv_stage_alter_table_log_table = {
828 0, "alter table (log apply table)", PSI_FLAG_STAGE_PROGRESS,
829 PSI_DOCUMENT_ME};
830
831 /** Performance schema stage event for monitoring ALTER TABLE progress. */
832 PSI_stage_info srv_stage_alter_table_merge_sort = {
833 0, "alter table (merge sort)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
834
835 /** Performance schema stage event for monitoring ALTER TABLE progress. */
836 PSI_stage_info srv_stage_alter_table_read_pk_internal_sort = {
837 0, "alter table (read PK and internal sort)", PSI_FLAG_STAGE_PROGRESS,
838 PSI_DOCUMENT_ME};
839
840 /** Performance schema stage event for monitoring ALTER TABLESPACE
841 ENCRYPTION progress. */
842 PSI_stage_info srv_stage_alter_tablespace_encryption = {
843 0, "alter tablespace (encryption)", PSI_FLAG_STAGE_PROGRESS,
844 PSI_DOCUMENT_ME};
845
846 /** Performance schema stage event for monitoring buffer pool load progress. */
847 PSI_stage_info srv_stage_buffer_pool_load = {
848 0, "buffer pool load", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
849 #endif /* HAVE_PSI_STAGE_INTERFACE */
850
851 /** Performance schema stage event for monitoring clone file copy progress. */
852 PSI_stage_info srv_stage_clone_file_copy = {
853 0, "clone (file copy)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
854
855 /** Performance schema stage event for monitoring clone redo copy progress. */
856 PSI_stage_info srv_stage_clone_redo_copy = {
857 0, "clone (redo copy)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
858
859 /** Performance schema stage event for monitoring clone page copy progress. */
860 PSI_stage_info srv_stage_clone_page_copy = {
861 0, "clone (page copy)", PSI_FLAG_STAGE_PROGRESS, PSI_DOCUMENT_ME};
862
863 /** Prints counters for work done by srv_master_thread. */
864 static void srv_print_master_thread_info(FILE *file) /* in: output stream */
865 {
866 fprintf(file,
867 "srv_master_thread loops: " ULINTPF " srv_active, " ULINTPF
868 " srv_shutdown, " ULINTPF " srv_idle\n",
869 srv_main_active_loops, srv_main_shutdown_loops, srv_main_idle_loops);
870 fprintf(file, "srv_master_thread log flush and writes: " ULINTPF "\n",
871 srv_log_writes_and_flush);
872 }
873 #endif /* !UNIV_HOTBACKUP */
874
875 /** Sets the info describing an i/o thread current state.
876 @param[in] i The 'segment' of the i/o thread
877 @param[in] str Constant char string describing the state */
878 void srv_set_io_thread_op_info(ulint i, const char *str) {
879 ut_a(i < SRV_MAX_N_IO_THREADS);
880
881 srv_io_thread_op_info[i] = str;
882 }
883
884 /** Resets the info describing an i/o thread current state. */
885 void srv_reset_io_thread_op_info() {
886 for (ulint i = 0; i < UT_ARR_SIZE(srv_io_thread_op_info); ++i) {
887 srv_io_thread_op_info[i] = "not started yet";
888 }
889 }
890
891 #ifndef UNIV_HOTBACKUP
892 #ifdef UNIV_DEBUG
893 /** Validates the type of a thread table slot.
894 @return true if ok */
895 static bool srv_thread_type_validate(
896 srv_thread_type type) /*!< in: thread type */
897 {
898 switch (type) {
899 case SRV_NONE:
900 break;
901 case SRV_WORKER:
902 case SRV_PURGE:
903 case SRV_MASTER:
904 return true;
905 }
906 ut_error;
907 }
908 #endif /* UNIV_DEBUG */
909
910 /** Gets the type of a thread table slot.
911 @return thread type */
912 static srv_thread_type srv_slot_get_type(
913 const srv_slot_t *slot) /*!< in: thread slot */
914 {
915 srv_thread_type type = slot->type;
916 ut_ad(srv_thread_type_validate(type));
917 return (type);
918 }
919
920 /** Reserves a slot in the thread table for the current thread.
921 @return reserved slot */
922 static srv_slot_t *srv_reserve_slot(
923 srv_thread_type type) /*!< in: type of the thread */
924 {
925 srv_slot_t *slot = nullptr;
926
927 srv_sys_mutex_enter();
928
929 ut_ad(srv_thread_type_validate(type));
930
931 switch (type) {
932 case SRV_MASTER:
933 slot = &srv_sys->sys_threads[SRV_MASTER_SLOT];
934 break;
935
936 case SRV_PURGE:
937 slot = &srv_sys->sys_threads[SRV_PURGE_SLOT];
938 break;
939
940 case SRV_WORKER:
941 /* Find an empty slot, skip the master and purge slots. */
942 for (slot = &srv_sys->sys_threads[2]; slot->in_use; ++slot) {
943 ut_a(slot < &srv_sys->sys_threads[srv_sys->n_sys_threads]);
944 }
945 break;
946
947 case SRV_NONE:
948 ut_error;
949 }
950
951 ut_a(!slot->in_use);
952
953 slot->in_use = true;
954 slot->suspended = false;
955 slot->type = type;
956
957 ut_ad(srv_slot_get_type(slot) == type);
958
959 ++srv_sys->n_threads_active[type];
960
961 srv_sys_mutex_exit();
962
963 return (slot);
964 }
965
966 /** Suspends the calling thread to wait for the event in its thread slot.
967 @return the current signal count of the event. */
968 static int64_t srv_suspend_thread_low(
969 srv_slot_t *slot) /*!< in/out: thread slot */
970 {
971 ut_ad(!srv_read_only_mode);
972 ut_ad(srv_sys_mutex_own());
973
974 ut_ad(slot->in_use);
975
976 srv_thread_type type = srv_slot_get_type(slot);
977
978 switch (type) {
979 case SRV_NONE:
980 ut_error;
981
982 case SRV_MASTER:
983 /* We have only one master thread and it
984 should be the first entry always. */
985 ut_a(srv_sys->n_threads_active[type] == 1);
986 break;
987
988 case SRV_PURGE:
989 /* We have only one purge coordinator thread
990 and it should be the second entry always. */
991 ut_a(srv_sys->n_threads_active[type] == 1);
992 break;
993
994 case SRV_WORKER:
995 ut_a(srv_n_purge_threads > 1);
996 ut_a(srv_sys->n_threads_active[type] > 0);
997 break;
998 }
999
1000 ut_a(!slot->suspended);
1001 slot->suspended = true;
1002
1003 ut_a(srv_sys->n_threads_active[type] > 0);
1004
1005 srv_sys->n_threads_active[type]--;
1006
1007 return (os_event_reset(slot->event));
1008 }
1009
1010 /** Suspends the calling thread to wait for the event in its thread slot.
1011 @return the current signal count of the event. */
1012 static int64_t srv_suspend_thread(srv_slot_t *slot) /*!< in/out: thread slot */
1013 {
1014 srv_sys_mutex_enter();
1015
1016 int64_t sig_count = srv_suspend_thread_low(slot);
1017
1018 srv_sys_mutex_exit();
1019
1020 return (sig_count);
1021 }
1022
1023 /** Releases threads of the type given from suspension in the thread table.
1024 NOTE! The server mutex has to be reserved by the caller!
1025 @return number of threads released: this may be less than n if not
1026 enough threads were suspended at the moment. */
1027 ulint srv_release_threads(srv_thread_type type, /*!< in: thread type */
1028 ulint n) /*!< in: number of threads to release */
1029 {
1030 ulint i;
1031 ulint count = 0;
1032
1033 ut_ad(srv_thread_type_validate(type));
1034 ut_ad(n > 0);
1035
1036 srv_sys_mutex_enter();
1037
1038 for (i = 0; i < srv_sys->n_sys_threads; i++) {
1039 srv_slot_t *slot;
1040
1041 slot = &srv_sys->sys_threads[i];
1042
1043 if (slot->in_use && srv_slot_get_type(slot) == type && slot->suspended) {
1044 switch (type) {
1045 case SRV_NONE:
1046 ut_error;
1047
1048 case SRV_MASTER:
1049 /* We have only one master thread and it
1050 should be the first entry always. */
1051 ut_a(n == 1);
1052 ut_a(i == SRV_MASTER_SLOT);
1053 ut_a(srv_sys->n_threads_active[type] == 0);
1054 break;
1055
1056 case SRV_PURGE:
1057 /* We have only one purge coordinator thread
1058 and it should be the second entry always. */
1059 ut_a(n == 1);
1060 ut_a(i == SRV_PURGE_SLOT);
1061 ut_a(srv_n_purge_threads > 0);
1062 ut_a(srv_sys->n_threads_active[type] == 0);
1063 break;
1064
1065 case SRV_WORKER:
1066 ut_a(srv_n_purge_threads > 1);
1067 ut_a(srv_sys->n_threads_active[type] < srv_n_purge_threads - 1);
1068 break;
1069 }
1070
1071 slot->suspended = false;
1072
1073 ++srv_sys->n_threads_active[type];
1074
1075 os_event_set(slot->event);
1076
1077 if (++count == n) {
1078 break;
1079 }
1080 }
1081 }
1082
1083 srv_sys_mutex_exit();
1084
1085 return (count);
1086 }
1087
1088 /** Release a thread's slot. */
1089 static void srv_free_slot(srv_slot_t *slot) /*!< in/out: thread slot */
1090 {
1091 srv_sys_mutex_enter();
1092
1093 if (!slot->suspended) {
1094 /* Mark the thread as inactive. */
1095 srv_suspend_thread_low(slot);
1096 }
1097
1098 /* Free the slot for reuse. */
1099 ut_ad(slot->in_use);
1100 slot->in_use = false;
1101
1102 srv_sys_mutex_exit();
1103 }
1104
1105 /** Initializes the server. */
1106 static void srv_init(void) {
1107 ulint n_sys_threads = 0;
1108 ulint srv_sys_sz = sizeof(*srv_sys);
1109
1110 /* Create mutex to protect encryption master_key_id. */
1111 {
1112 /* This is defined in ha_innodb.cc and used during create_log_files(), which
1113 we call after calling srv_boot() which defines types of mutexes, so we have
1114 to create this mutex in between the two calls. */
1115 extern ib_mutex_t master_key_id_mutex;
1116
1117 mutex_create(LATCH_ID_MASTER_KEY_ID_MUTEX, &master_key_id_mutex);
1118 }
1119
1120 mutex_create(LATCH_ID_SRV_INNODB_MONITOR, &srv_innodb_monitor_mutex);
1121
1122 ut_d(srv_threads.m_shutdown_cleanup_dbg = os_event_create());
1123
1124 srv_threads.m_master_ready_for_dd_shutdown = os_event_create();
1125
1126 srv_threads.m_purge_coordinator = {};
1127
1128 srv_threads.m_purge_workers_n = srv_n_purge_threads;
1129
1130 srv_threads.m_purge_workers = ut::new_arr_withkey<IB_thread>(
1131 UT_NEW_THIS_FILE_PSI_KEY, ut::Count{srv_threads.m_purge_workers_n});
1132
1133 if (!srv_read_only_mode) {
1134 /* Number of purge threads + master thread */
1135 n_sys_threads = srv_n_purge_threads + 1;
1136
1137 srv_sys_sz += n_sys_threads * sizeof(*srv_sys->sys_threads);
1138 }
1139
1140 srv_threads.m_page_cleaner_coordinator = {};
1141
1142 srv_threads.m_page_cleaner_workers_n = srv_n_page_cleaners;
1143
1144 srv_threads.m_page_cleaner_workers = ut::new_arr_withkey<IB_thread>(
1145 UT_NEW_THIS_FILE_PSI_KEY,
1146 ut::Count{srv_threads.m_page_cleaner_workers_n});
1147
1148 srv_sys = static_cast<srv_sys_t *>(
1149 ut::zalloc_withkey(UT_NEW_THIS_FILE_PSI_KEY, srv_sys_sz));
1150
1151 srv_sys->n_sys_threads = n_sys_threads;
1152
1153 /* Even in read-only mode we flush pages related to intrinsic table
1154 and so mutex creation is needed. */
1155 {
1156 mutex_create(LATCH_ID_SRV_SYS, &srv_sys->mutex);
1157
1158 mutex_create(LATCH_ID_SRV_SYS_TASKS, &srv_sys->tasks_mutex);
1159
1160 srv_sys->sys_threads = (srv_slot_t *)&srv_sys[1];
1161
1162 for (ulint i = 0; i < srv_sys->n_sys_threads; ++i) {
1163 srv_slot_t *slot = &srv_sys->sys_threads[i];
1164
1165 slot->event = os_event_create();
1166
1167 slot->in_use = false;
1168
1169 ut_a(slot->event);
1170 }
1171
1172 srv_error_event = os_event_create();
1173
1174 srv_monitor_event = os_event_create();
1175
1176 srv_buf_dump_event = os_event_create();
1177
1178 buf_flush_event = os_event_create();
1179
1180 buf_flush_tick_event = os_event_create();
1181
1182 UT_LIST_INIT(srv_sys->tasks);
1183 }
1184
1185 srv_buf_resize_event = os_event_create();
1186
1187 ut_d(srv_master_thread_disabled_event = os_event_create());
1188
1189 /* page_zip_stat_per_index_mutex is acquired from:
1190 1. page_zip_compress() (after SYNC_FSP)
1191 2. page_zip_decompress()
1192 3. i_s_cmp_per_index_fill_low() (where SYNC_DICT is acquired)
1193 4. innodb_cmp_per_index_update(), no other latches
1194 since we do not acquire any other latches while holding this mutex,
1195 it can have very low level. We pick SYNC_ANY_LATCH for it. */
1196 mutex_create(LATCH_ID_PAGE_ZIP_STAT_PER_INDEX,
1197 &page_zip_stat_per_index_mutex);
1198
1199 /* Create dummy indexes for infimum and supremum records */
1200
1201 dict_ind_init();
1202
1203 /* Initialize some INFORMATION SCHEMA internal structures */
1204 trx_i_s_cache_init(trx_i_s_cache);
1205
1206 ut_crc32_init();
1207
1208 dict_mem_init();
1209 }
1210
1211 /** Frees the data structures created in srv_init(). */
1212 void srv_free(void) {
1213 mutex_free(&srv_innodb_monitor_mutex);
1214 mutex_free(&page_zip_stat_per_index_mutex);
1215
1216 {
1217 mutex_free(&srv_sys->mutex);
1218 mutex_free(&srv_sys->tasks_mutex);
1219
1220 for (ulint i = 0; i < srv_sys->n_sys_threads; ++i) {
1221 srv_slot_t *slot = &srv_sys->sys_threads[i];
1222
1223 os_event_destroy(slot->event);
1224 }
1225
1226 os_event_destroy(srv_error_event);
1227 os_event_destroy(srv_monitor_event);
1228 os_event_destroy(srv_buf_dump_event);
1229 os_event_destroy(buf_flush_event);
1230 os_event_destroy(buf_flush_tick_event);
1231 }
1232
1233 os_event_destroy(srv_buf_resize_event);
1234
1235 #ifdef UNIV_DEBUG
1236 os_event_destroy(srv_master_thread_disabled_event);
1237 srv_master_thread_disabled_event = nullptr;
1238 #endif /* UNIV_DEBUG */
1239
1240 trx_i_s_cache_free(trx_i_s_cache);
1241
1242 ut::free(srv_sys);
1243
1244 srv_sys = nullptr;
1245
1246 if (srv_threads.m_page_cleaner_workers != nullptr) {
1247 for (size_t i = 0; i < srv_threads.m_page_cleaner_workers_n; ++i) {
1248 srv_threads.m_page_cleaner_workers[i] = {};
1249 }
1250 ut::delete_arr(srv_threads.m_page_cleaner_workers);
1251 srv_threads.m_page_cleaner_workers = nullptr;
1252 }
1253
1254 if (srv_threads.m_purge_workers != nullptr) {
1255 for (size_t i = 0; i < srv_threads.m_purge_workers_n; ++i) {
1256 srv_threads.m_purge_workers[i] = {};
1257 }
1258 ut::delete_arr(srv_threads.m_purge_workers);
1259 srv_threads.m_purge_workers = nullptr;
1260 }
1261
1262 os_event_destroy(srv_threads.m_master_ready_for_dd_shutdown);
1263
1264 ut_d(os_event_destroy(srv_threads.m_shutdown_cleanup_dbg));
1265
1266 srv_threads = {};
1267 }
1268
1269 /** Initializes the synchronization primitives, memory system, and the thread
1270 local storage. */
1271 static void srv_general_init() {
1272 sync_check_init(srv_max_n_threads);
1273 /* Reset the system variables in the recovery module. */
1274 recv_sys_var_init();
1275 os_thread_open();
1276 trx_pool_init();
1277 que_init();
1278 row_mysql_init();
1279 undo_spaces_init();
1280 }
1281
1282 /** Boots the InnoDB server. */
1283 void srv_boot(void) {
1284 /* Initialize synchronization primitives, memory management, and thread
1285 local storage */
1286
1287 srv_general_init();
1288
1289 /* Initialize this module */
1290
1291 srv_init();
1292 }
1293
1294 /** Refreshes the values used to calculate per-second averages. */
1295 static void srv_refresh_innodb_monitor_stats(void) {
1296 mutex_enter(&srv_innodb_monitor_mutex);
1297
1298 srv_monitor_stats_refreshed_at = std::chrono::steady_clock::now();
1299
1300 os_aio_refresh_stats();
1301
1302 btr_cur_n_sea_old = btr_cur_n_sea;
1303 btr_cur_n_non_sea_old = btr_cur_n_non_sea;
1304
1305 log_refresh_stats(*log_sys);
1306
1307 buf_refresh_io_stats_all();
1308
1309 srv_n_rows_inserted_old = srv_stats.n_rows_inserted;
1310 srv_n_rows_updated_old = srv_stats.n_rows_updated;
1311 srv_n_rows_deleted_old = srv_stats.n_rows_deleted;
1312 srv_n_rows_read_old = srv_stats.n_rows_read;
1313
1314 srv_n_system_rows_inserted_old = srv_stats.n_system_rows_inserted;
1315 srv_n_system_rows_updated_old = srv_stats.n_system_rows_updated;
1316 srv_n_system_rows_deleted_old = srv_stats.n_system_rows_deleted;
1317 srv_n_system_rows_read_old = srv_stats.n_system_rows_read;
1318
1319 mutex_exit(&srv_innodb_monitor_mutex);
1320 }
1321
1322 /**
1323 Prints info summary and info about all transactions to the file, recording the
1324 position where the part about transactions starts.
1325 @param[in] file output stream
1326 @param[out] trx_start_pos file position of the start of the list of active
1327 transactions
1328 */
1329 static void srv_printf_locks_and_transactions(FILE *file,
1330 ulint *trx_start_pos) {
1331 ut_ad(locksys::owns_exclusive_global_latch());
1332 lock_print_info_summary(file);
1333 if (trx_start_pos) {
1334 long t = ftell(file);
1335 if (t < 0) {
1336 *trx_start_pos = ULINT_UNDEFINED;
1337 } else {
1338 *trx_start_pos = (ulint)t;
1339 }
1340 }
1341 lock_print_info_all_transactions(file);
1342 }
1343
1344 bool srv_printf_innodb_monitor(FILE *file, bool nowait, ulint *trx_start_pos,
1345 ulint *trx_end) {
1346 ulint n_reserved;
1347 bool ret;
1348
1349 mutex_enter(&srv_innodb_monitor_mutex);
1350
1351 const auto current_time = std::chrono::steady_clock::now();
1352
1353 /* We add 0.001 seconds to time_elapsed to prevent division
1354 by zero if two users happen to call SHOW ENGINE INNODB STATUS at the
1355 same time */
1356
1357 const auto time_elapsed = std::chrono::duration_cast<std::chrono::seconds>(
1358 current_time - srv_monitor_stats_refreshed_at)
1359 .count() +
1360 0.001;
1361
1362 srv_monitor_stats_refreshed_at = current_time;
1363
1364 fputs("\n=====================================\n", file);
1365
1366 ut_print_timestamp(file);
1367 fprintf(file,
1368 " INNODB MONITOR OUTPUT\n"
1369 "=====================================\n"
1370 "Per second averages calculated from the last %lu seconds\n",
1371 (ulong)time_elapsed);
1372
1373 fputs(
1374 "-----------------\n"
1375 "BACKGROUND THREAD\n"
1376 "-----------------\n",
1377 file);
1378 srv_print_master_thread_info(file);
1379
1380 fputs(
1381 "----------\n"
1382 "SEMAPHORES\n"
1383 "----------\n",
1384 file);
1385
1386 sync_print(file);
1387
1388 /* Conceptually, srv_innodb_monitor_mutex has a very high latching
1389 order level in sync0sync.h, while dict_foreign_err_mutex has a very
1390 low level 135. Therefore we can reserve the latter mutex here without
1391 a danger of a deadlock of threads. */
1392
1393 mutex_enter(&dict_foreign_err_mutex);
1394
1395 if (!srv_read_only_mode && ftell(dict_foreign_err_file) != 0L) {
1396 fputs(
1397 "------------------------\n"
1398 "LATEST FOREIGN KEY ERROR\n"
1399 "------------------------\n",
1400 file);
1401 ut_copy_file(file, dict_foreign_err_file);
1402 }
1403
1404 mutex_exit(&dict_foreign_err_mutex);
1405
1406 ret = true;
1407 if (nowait) {
1408 locksys::Global_exclusive_try_latch guard{UT_LOCATION_HERE};
1409 if (guard.owns_lock()) {
1410 srv_printf_locks_and_transactions(file, trx_start_pos);
1411 } else {
1412 fputs("FAIL TO OBTAIN LOCK MUTEX, SKIP LOCK INFO PRINTING\n", file);
1413 ret = false;
1414 }
1415 } else {
1416 locksys::Global_exclusive_latch_guard guard{UT_LOCATION_HERE};
1417 srv_printf_locks_and_transactions(file, trx_start_pos);
1418 }
1419
1420 if (ret) {
1421 ut_ad(lock_validate());
1422
1423 if (trx_end) {
1424 long t = ftell(file);
1425 if (t < 0) {
1426 *trx_end = ULINT_UNDEFINED;
1427 } else {
1428 *trx_end = (ulint)t;
1429 }
1430 }
1431 }
1432
1433 fputs(
1434 "--------\n"
1435 "FILE I/O\n"
1436 "--------\n",
1437 file);
1438 os_aio_print(file);
1439
1440 fputs(
1441 "-------------------------------------\n"
1442 "INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
1443 "-------------------------------------\n",
1444 file);
1445 ibuf_print(file);
1446
1447 for (ulint i = 0; i < btr_ahi_parts; ++i) {
1448 auto &part = btr_search_sys->parts[i];
1449 rw_lock_s_lock(&part.latch, UT_LOCATION_HERE);
1450 ha_print_info(file, part.hash_table);
1451 rw_lock_s_unlock(&part.latch);
1452 }
1453
1454 fprintf(file, "%.2f hash searches/s, %.2f non-hash searches/s\n",
1455 (btr_cur_n_sea - btr_cur_n_sea_old) / time_elapsed,
1456 (btr_cur_n_non_sea - btr_cur_n_non_sea_old) / time_elapsed);
1457 btr_cur_n_sea_old = btr_cur_n_sea;
1458 btr_cur_n_non_sea_old = btr_cur_n_non_sea;
1459
1460 fputs(
1461 "---\n"
1462 "LOG\n"
1463 "---\n",
1464 file);
1465 log_print(*log_sys, file);
1466
1467 fputs(
1468 "----------------------\n"
1469 "BUFFER POOL AND MEMORY\n"
1470 "----------------------\n",
1471 file);
1472 fprintf(file,
1473 "Total large memory allocated " ULINTPF
1474 "\n"
1475 "Dictionary memory allocated %zu\n",
1476 os_total_large_mem_allocated.load(), dict_sys->size);
1477
1478 buf_print_io(file);
1479
1480 fputs(
1481 "--------------\n"
1482 "ROW OPERATIONS\n"
1483 "--------------\n",
1484 file);
1485 fprintf(file,
1486 "%" PRId32 " queries inside InnoDB, %" PRId32 " queries in queue\n",
1487 srv_conc_get_active_threads(), srv_conc_get_waiting_threads());
1488
1489 /* This is a dirty read, without holding trx_sys->mutex. */
1490 fprintf(file, ULINTPF " read views open inside InnoDB\n",
1491 trx_sys->mvcc->size());
1492
1493 n_reserved = fil_space_get_n_reserved_extents(0);
1494 if (n_reserved > 0) {
1495 fprintf(file,
1496 ULINTPF
1497 " tablespace extents now reserved for"
1498 " B-tree split operations\n",
1499 n_reserved);
1500 }
1501
1502 std::ostringstream msg;
1503
1504 msg << "Process ID=" << srv_main_thread_process_no
1505 << ", Main thread ID=" << srv_main_thread_id
1506 << " , state=" << srv_main_thread_op_info;
1507
1508 fprintf(file, "%s\n", msg.str().c_str());
1509
1510 fprintf(file,
1511 "Number of rows inserted " ULINTPF ", updated " ULINTPF
1512 ", deleted " ULINTPF ", read " ULINTPF "\n",
1513 (ulint)srv_stats.n_rows_inserted, (ulint)srv_stats.n_rows_updated,
1514 (ulint)srv_stats.n_rows_deleted, (ulint)srv_stats.n_rows_read);
1515 fprintf(
1516 file,
1517 "%.2f inserts/s, %.2f updates/s,"
1518 " %.2f deletes/s, %.2f reads/s\n",
1519 ((ulint)srv_stats.n_rows_inserted - srv_n_rows_inserted_old) /
1520 time_elapsed,
1521 ((ulint)srv_stats.n_rows_updated - srv_n_rows_updated_old) / time_elapsed,
1522 ((ulint)srv_stats.n_rows_deleted - srv_n_rows_deleted_old) / time_elapsed,
1523 ((ulint)srv_stats.n_rows_read - srv_n_rows_read_old) / time_elapsed);
1524
1525 fprintf(file,
1526 "Number of system rows inserted " ULINTPF ", updated " ULINTPF
1527 ", deleted " ULINTPF ", read " ULINTPF "\n",
1528 (ulint)srv_stats.n_system_rows_inserted,
1529 (ulint)srv_stats.n_system_rows_updated,
1530 (ulint)srv_stats.n_system_rows_deleted,
1531 (ulint)srv_stats.n_system_rows_read);
1532 fprintf(
1533 file,
1534 "%.2f inserts/s, %.2f updates/s,"
1535 " %.2f deletes/s, %.2f reads/s\n",
1536 ((ulint)srv_stats.n_system_rows_inserted -
1537 srv_n_system_rows_inserted_old) /
1538 time_elapsed,
1539 ((ulint)srv_stats.n_system_rows_updated - srv_n_system_rows_updated_old) /
1540 time_elapsed,
1541 ((ulint)srv_stats.n_system_rows_deleted - srv_n_system_rows_deleted_old) /
1542 time_elapsed,
1543 ((ulint)srv_stats.n_system_rows_read - srv_n_system_rows_read_old) /
1544 time_elapsed);
1545
1546 srv_n_rows_inserted_old = srv_stats.n_rows_inserted;
1547 srv_n_rows_updated_old = srv_stats.n_rows_updated;
1548 srv_n_rows_deleted_old = srv_stats.n_rows_deleted;
1549 srv_n_rows_read_old = srv_stats.n_rows_read;
1550
1551 srv_n_system_rows_inserted_old = srv_stats.n_system_rows_inserted;
1552 srv_n_system_rows_updated_old = srv_stats.n_system_rows_updated;
1553 srv_n_system_rows_deleted_old = srv_stats.n_system_rows_deleted;
1554 srv_n_system_rows_read_old = srv_stats.n_system_rows_read;
1555
1556 fputs(
1557 "----------------------------\n"
1558 "END OF INNODB MONITOR OUTPUT\n"
1559 "============================\n",
1560 file);
1561 mutex_exit(&srv_innodb_monitor_mutex);
1562 fflush(file);
1563
1564 return (ret);
1565 }
1566
1567 /** Function to pass InnoDB status variables to MySQL */
1568 void srv_export_innodb_status(void) {
1569 buf_pool_stat_t stat;
1570 buf_pools_list_size_t buf_pools_list_size;
1571 ulint LRU_len;
1572 ulint free_len;
1573 ulint flush_list_len;
1574
1575 buf_get_total_stat(&stat);
1576 buf_get_total_list_len(&LRU_len, &free_len, &flush_list_len);
1577 buf_get_total_list_size_in_bytes(&buf_pools_list_size);
1578
1579 mutex_enter(&srv_innodb_monitor_mutex);
1580
1581 export_vars.innodb_data_pending_reads = os_n_pending_reads;
1582
1583 export_vars.innodb_data_pending_writes = os_n_pending_writes;
1584
1585 export_vars.innodb_data_pending_fsyncs =
1586 log_pending_flushes() + fil_n_pending_tablespace_flushes.load();
1587
1588 // Check against unsigned underflow in debug - values close to max value
1589 // may be result of mismatched increment/decrement or data race; investigate
1590 // on failure
1591 ut_ad(export_vars.innodb_data_pending_fsyncs <=
1592 std::numeric_limits<ulint>::max() - 1000);
1593
1594 export_vars.innodb_data_fsyncs = os_n_fsyncs;
1595
1596 export_vars.innodb_data_read = srv_stats.data_read;
1597
1598 export_vars.innodb_data_reads = os_n_file_reads;
1599
1600 export_vars.innodb_data_writes = os_n_file_writes;
1601
1602 export_vars.innodb_data_written = srv_stats.data_written;
1603
1604 export_vars.innodb_buffer_pool_read_requests =
1605 Counter::total(stat.m_n_page_gets);
1606
1607 export_vars.innodb_buffer_pool_write_requests =
1608 srv_stats.buf_pool_write_requests;
1609
1610 export_vars.innodb_buffer_pool_wait_free = srv_stats.buf_pool_wait_free;
1611
1612 export_vars.innodb_buffer_pool_pages_flushed = srv_stats.buf_pool_flushed;
1613
1614 export_vars.innodb_buffer_pool_reads = srv_stats.buf_pool_reads;
1615
1616 export_vars.innodb_buffer_pool_read_ahead_rnd = stat.n_ra_pages_read_rnd;
1617
1618 export_vars.innodb_buffer_pool_read_ahead = stat.n_ra_pages_read;
1619
1620 export_vars.innodb_buffer_pool_read_ahead_evicted = stat.n_ra_pages_evicted;
1621
1622 export_vars.innodb_buffer_pool_pages_data = LRU_len;
1623
1624 export_vars.innodb_buffer_pool_bytes_data =
1625 buf_pools_list_size.LRU_bytes + buf_pools_list_size.unzip_LRU_bytes;
1626
1627 export_vars.innodb_buffer_pool_pages_dirty = flush_list_len;
1628
1629 export_vars.innodb_buffer_pool_bytes_dirty =
1630 buf_pools_list_size.flush_list_bytes;
1631
1632 export_vars.innodb_buffer_pool_pages_free = free_len;
1633
1634 export_vars.innodb_buffer_pool_pages_total = buf_pool_get_n_pages();
1635
1636 export_vars.innodb_buffer_pool_pages_misc =
1637 buf_pool_get_n_pages() - LRU_len - free_len;
1638
1639 export_vars.innodb_buffer_pool_resize_status_code =
1640 buf_pool_resize_status_code.load();
1641
1642 export_vars.innodb_buffer_pool_resize_status_progress =
1643 buf_pool_resize_status_progress.load();
1644
1645 export_vars.innodb_page_size = UNIV_PAGE_SIZE;
1646
1647 export_vars.innodb_log_waits = srv_stats.log_waits;
1648
1649 export_vars.innodb_os_log_written = srv_stats.os_log_written;
1650
1651 export_vars.innodb_os_log_fsyncs = log_total_flushes();
1652
1653 export_vars.innodb_os_log_pending_fsyncs = log_pending_flushes();
1654
1655 export_vars.innodb_os_log_pending_writes = srv_stats.os_log_pending_writes;
1656
1657 export_vars.innodb_log_write_requests = srv_stats.log_write_requests;
1658
1659 export_vars.innodb_log_writes = srv_stats.log_writes;
1660
1661 export_vars.innodb_dblwr_pages_written = srv_stats.dblwr_pages_written;
1662
1663 export_vars.innodb_dblwr_writes = srv_stats.dblwr_writes;
1664
1665 export_vars.innodb_pages_created = stat.n_pages_created;
1666
1667 export_vars.innodb_pages_read = stat.n_pages_read;
1668
1669 export_vars.innodb_pages_written = stat.n_pages_written;
1670
1671 export_vars.innodb_redo_log_enabled = srv_redo_log;
1672
1673 export_vars.innodb_row_lock_waits = srv_stats.n_lock_wait_count;
1674
1675 export_vars.innodb_row_lock_current_waits =
1676 srv_stats.n_lock_wait_current_count;
1677
1678 export_vars.innodb_row_lock_time = srv_stats.n_lock_wait_time / 1000;
1679
1680 if (srv_stats.n_lock_wait_count > 0) {
1681 export_vars.innodb_row_lock_time_avg =
1682 (ulint)(srv_stats.n_lock_wait_time / 1000 /
1683 srv_stats.n_lock_wait_count);
1684
1685 } else {
1686 export_vars.innodb_row_lock_time_avg = 0;
1687 }
1688
1689 export_vars.innodb_row_lock_time_max =
1690 std::chrono::duration_cast<std::chrono::milliseconds>(
1691 lock_sys->n_lock_max_wait_time)
1692 .count();
1693
1694 export_vars.innodb_rows_read = srv_stats.n_rows_read;
1695
1696 export_vars.innodb_rows_inserted = srv_stats.n_rows_inserted;
1697
1698 export_vars.innodb_rows_updated = srv_stats.n_rows_updated;
1699
1700 export_vars.innodb_rows_deleted = srv_stats.n_rows_deleted;
1701
1702 export_vars.innodb_system_rows_read = srv_stats.n_system_rows_read;
1703
1704 export_vars.innodb_system_rows_inserted = srv_stats.n_system_rows_inserted;
1705
1706 export_vars.innodb_system_rows_updated = srv_stats.n_system_rows_updated;
1707
1708 export_vars.innodb_system_rows_deleted = srv_stats.n_system_rows_deleted;
1709
1710 export_vars.innodb_sampled_pages_read = srv_stats.n_sampled_pages_read;
1711
1712 export_vars.innodb_sampled_pages_skipped = srv_stats.n_sampled_pages_skipped;
1713
1714 export_vars.innodb_num_open_files = fil_n_files_open;
1715
1716 export_vars.innodb_truncated_status_writes = srv_truncated_status_writes;
1717
1718 export_vars.innodb_undo_tablespaces_implicit = FSP_IMPLICIT_UNDO_TABLESPACES;
1719
1720 undo::spaces->s_lock();
1721
1722 export_vars.innodb_undo_tablespaces_total = undo::spaces->size();
1723
1724 export_vars.innodb_undo_tablespaces_explicit =
1725 export_vars.innodb_undo_tablespaces_total - FSP_IMPLICIT_UNDO_TABLESPACES;
1726
1727 export_vars.innodb_undo_tablespaces_active = 0;
1728
1729 for (auto undo_space : undo::spaces->m_spaces) {
1730 if (undo_space->is_active()) {
1731 export_vars.innodb_undo_tablespaces_active++;
1732 }
1733 }
1734 undo::spaces->s_unlock();
1735
1736 #ifdef UNIV_DEBUG
1737 rw_lock_s_lock(&purge_sys->latch, UT_LOCATION_HERE);
1738 trx_id_t done_trx_no = purge_sys->done.trx_no;
1739
1740 /* Purge always deals with transaction end points represented by
1741 transaction number. We are allowed to purge transactions with number
1742 below the low limit. */
1743 ReadView oldest_view;
1744 trx_sys->mvcc->clone_oldest_view(&oldest_view);
1745 trx_id_t low_limit_no = oldest_view.view_low_limit_no();
1746
1747 rw_lock_s_unlock(&purge_sys->latch);
1748
1749 trx_sys_serialisation_mutex_enter();
1750 /* Maximum transaction number added to history list for purge. */
1751 trx_id_t max_trx_no = trx_sys->rw_max_trx_no;
1752 trx_sys_serialisation_mutex_exit();
1753
1754 if (done_trx_no == 0 || max_trx_no < done_trx_no) {
1755 export_vars.innodb_purge_trx_id_age = 0;
1756 } else {
1757 /* Add 1 as done_trx_no always points to the next transaction ID. */
1758 export_vars.innodb_purge_trx_id_age = (ulint)(max_trx_no - done_trx_no + 1);
1759 }
1760
1761 if (low_limit_no == 0 || max_trx_no < low_limit_no) {
1762 export_vars.innodb_purge_view_trx_id_age = 0;
1763 } else {
1764 /* Add 1 as low_limit_no always points to the next transaction ID. */
1765 export_vars.innodb_purge_view_trx_id_age =
1766 (ulint)(max_trx_no - low_limit_no + 1);
1767 }
1768 #endif /* UNIV_DEBUG */
1769
1770 mutex_exit(&srv_innodb_monitor_mutex);
1771 }
1772
1773 /** A thread which prints the info output by various InnoDB monitors. */
1774 void srv_monitor_thread() {
1775 uint16_t mutex_skipped{0};
1776 bool last_srv_print_monitor = srv_print_innodb_monitor;
1777
1778 ut_ad(!srv_read_only_mode);
1779
1780 srv_monitor_stats_refreshed_at = std::chrono::steady_clock::now();
1781 const auto sleep_interval = std::chrono::seconds{15};
1782 while (0 != os_event_wait_time(srv_monitor_event, sleep_interval)) {
1783 if (srv_print_innodb_monitor || 0 < srv_innodb_needs_monitoring.load()) {
1784 /* Reset mutex_skipped counter every time the condition above becomes
1785 true. This is to ensure we will not be blocked by lock_sys global
1786 latch for short duration information printing, such as requested by
1787 sync_array_print_long_waits() */
1788 if (!last_srv_print_monitor) {
1789 mutex_skipped = 0;
1790 last_srv_print_monitor = true;
1791 }
1792
1793 if (!srv_printf_innodb_monitor(stderr, MUTEX_NOWAIT(mutex_skipped),
1794 nullptr, nullptr)) {
1795 mutex_skipped++;
1796 } else {
1797 /* Reset the counter */
1798 mutex_skipped = 0;
1799 }
1800 } else {
1801 last_srv_print_monitor = false;
1802 }
1803
1804 /* We don't create the temp files or associated mutexes in read-only-mode */
1805
1806 if (!srv_read_only_mode && srv_innodb_status) {
1807 mutex_enter(&srv_monitor_file_mutex);
1808 rewind(srv_monitor_file);
1809 if (!srv_printf_innodb_monitor(srv_monitor_file,
1810 MUTEX_NOWAIT(mutex_skipped), nullptr,
1811 nullptr)) {
1812 mutex_skipped++;
1813 } else {
1814 mutex_skipped = 0;
1815 }
1816
1817 os_file_set_eof(srv_monitor_file);
1818 mutex_exit(&srv_monitor_file_mutex);
1819 }
1820
1821 if (srv_monitor_stats_refreshed_at + std::chrono::minutes{1} <
1822 std::chrono::steady_clock::now() + sleep_interval) {
1823 /* We refresh InnoDB Monitor values so that averages are printed from at
1824 most 60 last seconds and at least 15 seconds*/
1825
1826 srv_refresh_innodb_monitor_stats();
1827 }
1828 }
1829 ut_ad(SRV_SHUTDOWN_CLEANUP <= srv_shutdown_state.load());
1830 }
1831
1832 /** A thread which prints warnings about semaphore waits which have lasted
1833 too long. These can be used to track bugs which cause hangs. */
1834 void srv_error_monitor_thread() {
1835 /* number of successive fatal timeouts observed */
1836 ulint fatal_cnt = 0;
1837 lsn_t old_lsn;
1838 lsn_t new_lsn;
1839 int64_t sig_count;
1840 /* longest waiting thread for a semaphore */
1841 auto waiter = std::this_thread::get_id();
1842 auto old_waiter = waiter;
1843 /* the semaphore that is being waited for */
1844 const void *sema = nullptr;
1845 const void *old_sema = nullptr;
1846
1847 ut_ad(!srv_read_only_mode);
1848
1849 old_lsn = log_get_lsn(*log_sys);
1850
1851 loop:
1852 /* Try to track a strange bug reported by Harald Fuchs and others,
1853 where the lsn seems to decrease at times */
1854
1855 new_lsn = log_get_lsn(*log_sys);
1856
1857 if (new_lsn < old_lsn) {
1858 ib::error(ER_IB_MSG_1046, ulonglong{old_lsn}, ulonglong{new_lsn});
1859 ut_d(ut_error);
1860 }
1861
1862 old_lsn = new_lsn;
1863
1864 /* Update the statistics collected for deciding LRU eviction policy.
1865 NOTE: While this doesn't relate to error monitoring, it's here for historical
1866 reasons, as it depends on being called ~1Hz. It is lock-free, so can't cause a
1867 deadlock itself. */
1868 buf_LRU_stat_update();
1869
1870 /* In case mutex_exit is not a memory barrier, it is
1871 theoretically possible some threads are left waiting though
1872 the semaphore is already released. Wake up those threads: */
1873 sync_arr_wake_threads_if_sema_free();
1874
1875 sync_array_detect_deadlock();
1876
1877 if (sync_array_print_long_waits(&waiter, &sema) && sema == old_sema &&
1878 waiter == old_waiter) {
1879 fatal_cnt++;
1880 if (fatal_cnt > 10) {
1881 ib::fatal(UT_LOCATION_HERE, ER_IB_MSG_1047,
1882 ulonglong{srv_fatal_semaphore_wait_threshold});
1883 }
1884 } else {
1885 fatal_cnt = 0;
1886 old_waiter = waiter;
1887 old_sema = sema;
1888 }
1889
1890 /* Flush stderr so that a database user gets the output
1891 to possible MySQL error file */
1892
1893 fflush(stderr);
1894
1895 sig_count = os_event_reset(srv_error_event);
1896
1897 os_event_wait_time_low(srv_error_event, std::chrono::seconds{1}, sig_count);
1898
1899 if (srv_shutdown_state.load() < SRV_SHUTDOWN_CLEANUP) {
1900 goto loop;
1901 }
1902 }
1903
1904 /** Increment the server activity count. */
1905 void srv_inc_activity_count(void) { srv_sys->activity_count.inc(); }
1906
1907 /** Check whether the master thread is active.
1908 This is polled during the final phase of shutdown.
1909 The first phase of server shutdown must have already been executed
1910 (or the server must not have been fully started up).
1911 @see srv_pre_dd_shutdown()
1912 @retval true if any thread is active
1913 @retval false if no thread is active */
1914 bool srv_master_thread_is_active() {
1915 return (srv_thread_is_active(srv_threads.m_master));
1916 }
1917
1918 /** Tells the InnoDB server that there has been activity in the database
1919 and wakes up the master thread if it is suspended (not sleeping). Used
1920 in the MySQL interface. Note that there is a small chance that the master
1921 thread stays suspended (we do not protect our operation with the
1922 srv_sys_t->mutex, for performance reasons). */
1923 void srv_active_wake_master_thread_low() {
1924 ut_ad(!srv_read_only_mode);
1925 ut_ad(!srv_sys_mutex_own());
1926
1927 srv_inc_activity_count();
1928
1929 if (srv_sys->n_threads_active[SRV_MASTER] == 0) {
1930 srv_slot_t *slot;
1931
1932 srv_sys_mutex_enter();
1933
1934 slot = &srv_sys->sys_threads[SRV_MASTER_SLOT];
1935
1936 /* Only if the master thread has been started. */
1937
1938 if (slot->in_use) {
1939 ut_a(srv_slot_get_type(slot) == SRV_MASTER);
1940
1941 if (slot->suspended) {
1942 slot->suspended = false;
1943
1944 ++srv_sys->n_threads_active[SRV_MASTER];
1945
1946 os_event_set(slot->event);
1947 }
1948 }
1949
1950 srv_sys_mutex_exit();
1951 }
1952 }
1953
1954 /** Tells the purge thread that there has been activity in the database
1955 and wakes up the purge thread if it is suspended (not sleeping). Note
1956 that there is a small chance that the purge thread stays suspended
1957 (we do not protect our check with the srv_sys_t:mutex and the
1958 purge_sys->latch, for performance reasons). */
1959 void srv_wake_purge_thread_if_not_active(void) {
1960 ut_ad(!srv_sys_mutex_own());
1961
1962 if (purge_sys->state == PURGE_STATE_RUN &&
1963 srv_sys->n_threads_active[SRV_PURGE] == 0) {
1964 srv_release_threads(SRV_PURGE, 1);
1965 }
1966 }
1967
1968 /** Wakes up the master thread if it is suspended or being suspended. */
1969 void srv_wake_master_thread(void) {
1970 ut_ad(!srv_sys_mutex_own());
1971
1972 srv_inc_activity_count();
1973
1974 srv_release_threads(SRV_MASTER, 1);
1975 }
1976
1977 /** Get current server activity count. We don't hold srv_sys::mutex while
1978 reading this value as it is only used in heuristics.
1979 @return activity count. */
1980 ulint srv_get_activity_count(void) {
1981 return (srv_sys == nullptr ? 0 : srv_sys->activity_count);
1982 }
1983
1984 /** Check if there has been any activity.
1985 @return false if no change in activity counter. */
1986 bool srv_check_activity(ulint old_activity_count) /*!< in: old activity count */
1987 {
1988 return (srv_sys == nullptr ? false
1989 : srv_sys->activity_count != old_activity_count);
1990 }
1991
1992 /** Make room in the table cache by evicting an unused table.
1993 @return number of tables evicted. */
1994 static ulint srv_master_evict_from_table_cache(
1995 ulint pct_check) /*!< in: max percent to check */
1996 {
1997 ulint n_tables_evicted = 0;
1998
1999 rw_lock_x_lock(dict_operation_lock, UT_LOCATION_HERE);
2000
2001 dict_mutex_enter_for_mysql();
2002
2003 n_tables_evicted =
2004 dict_make_room_in_cache(innobase_get_table_cache_size(), pct_check);
2005
2006 dict_mutex_exit_for_mysql();
2007
2008 rw_lock_x_unlock(dict_operation_lock);
2009
2010 return (n_tables_evicted);
2011 }
2012
2013 /** This function prints progress message every 60 seconds during server
2014 shutdown, for any activities that master thread is pending on. */
2015 static void srv_shutdown_print_master_pending(
2016 std::chrono::steady_clock::time_point *last_print_time, /*!< last time the
2017 function print the message */
2018 ulint n_tables_to_drop, /*!< number of tables to
2019 be dropped */
2020 ulint n_bytes_merged) /*!< number of change buffer
2021 just merged */
2022 {
2023 const auto current_time = std::chrono::steady_clock::now();
2024
2025 const auto time_elapsed = current_time - *last_print_time;
2026
2027 if (time_elapsed > std::chrono::seconds(60)) {
2028 *last_print_time = std::chrono::steady_clock::now();
2029
2030 if (n_tables_to_drop) {
2031 ib::info(ER_IB_MSG_1048, ulonglong{n_tables_to_drop});
2032 }
2033
2034 /* Check change buffer merge, we only wait for change buffer
2035 merge if it is a slow shutdown */
2036 if (!srv_fast_shutdown && n_bytes_merged) {
2037 ib::info(ER_IB_MSG_1049, ulonglong{n_bytes_merged});
2038 }
2039 }
2040 }
2041
2042 #ifdef UNIV_DEBUG
2043 /** Waits in loop as long as master thread is disabled (debug) */
2044 static void srv_master_do_disabled_loop(void) {
2045 if (!srv_master_thread_disabled_debug) {
2046 /* We return here to avoid changing op_info. */
2047 return;
2048 }
2049
2050 srv_main_thread_op_info = "disabled";
2051
2052 while (srv_master_thread_disabled_debug) {
2053 os_event_set(srv_master_thread_disabled_event);
2054 if (srv_shutdown_state.load() >=
2055 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2056 break;
2057 }
2058 std::this_thread::sleep_for(std::chrono::milliseconds(100));
2059 }
2060
2061 srv_main_thread_op_info = "";
2062 }
2063
2064 void srv_master_thread_disabled_debug_update(THD *, SYS_VAR *, void *,
2065 const void *save) {
2066 /* This method is protected by mutex, as every SET GLOBAL .. */
2067 ut_ad(srv_master_thread_disabled_event != nullptr);
2068
2069 const bool disable = *static_cast<const bool *>(save);
2070
2071 const int64_t sig_count = os_event_reset(srv_master_thread_disabled_event);
2072
2073 srv_master_thread_disabled_debug = disable;
2074
2075 if (disable) {
2076 os_event_wait_low(srv_master_thread_disabled_event, sig_count);
2077 }
2078 }
2079 #endif /* UNIV_DEBUG */
2080
2081 #ifdef UNIV_LINUX
2082 /** Calculates difference between two timeval values.
2083 @param[in] a later timeval
2084 @param[in] b earlier timeval
2085 @return a - b; number of microseconds between b and a */
2086 [[maybe_unused]] static int64_t timeval_diff_us(timeval a, timeval b) {
2087 return ((a.tv_sec - b.tv_sec) * 1000000LL + a.tv_usec - b.tv_usec);
2088 }
2089
2090 /** Updates statistics about current CPU usage. */
2091 static void srv_update_cpu_usage() {
2092 using Clock = std::chrono::high_resolution_clock;
2093 using Clock_point = std::chrono::time_point<Clock>;
2094
2095 static Clock_point last_time = Clock::now();
2096
2097 static timeval last_cpu_utime;
2098 static timeval last_cpu_stime;
2099 static bool last_cpu_times_set = false;
2100
2101 Clock_point cur_time = Clock::now();
2102
2103 const auto time_diff = std::chrono::duration_cast<std::chrono::microseconds>(
2104 cur_time - last_time)
2105 .count();
2106
2107 if (time_diff < 100 * 1000LL) {
2108 return;
2109 }
2110 last_time = cur_time;
2111
2112 rusage usage;
2113 if (getrusage(RUSAGE_SELF, &usage) != 0) {
2114 return;
2115 }
2116
2117 if (!last_cpu_times_set) {
2118 last_cpu_utime = usage.ru_utime;
2119 last_cpu_stime = usage.ru_stime;
2120 last_cpu_times_set = true;
2121 return;
2122 }
2123
2124 const auto cpu_utime_diff = timeval_diff_us(usage.ru_utime, last_cpu_utime);
2125 last_cpu_utime = usage.ru_utime;
2126
2127 const auto cpu_stime_diff = timeval_diff_us(usage.ru_stime, last_cpu_stime);
2128 last_cpu_stime = usage.ru_stime;
2129
2130 /* Calculate absolute. */
2131
2132 double cpu_utime = cpu_utime_diff * 100.0 / time_diff;
2133 MONITOR_SET(MONITOR_CPU_UTIME_ABS, int64_t(cpu_utime));
2134 srv_cpu_usage.utime_abs = cpu_utime;
2135
2136 double cpu_stime = cpu_stime_diff * 100.0 / time_diff;
2137 MONITOR_SET(MONITOR_CPU_STIME_ABS, int64_t(cpu_stime));
2138 srv_cpu_usage.stime_abs = cpu_stime;
2139
2140 /* Calculate relative. */
2141
2142 cpu_set_t cs;
2143 CPU_ZERO(&cs);
2144 if (sched_getaffinity(0, sizeof(cs), &cs) != 0) {
2145 return;
2146 }
2147
2148 const int n_cpu = CPU_COUNT(&cs);
2149
2150 srv_cpu_usage.n_cpu = n_cpu;
2151 MONITOR_SET(MONITOR_CPU_N, int64_t(n_cpu));
2152
2153 if (n_cpu == 0) {
2154 return;
2155 }
2156
2157 cpu_utime /= n_cpu;
2158 MONITOR_SET(MONITOR_CPU_UTIME_PCT, int64_t(cpu_utime));
2159 srv_cpu_usage.utime_pct = cpu_utime;
2160
2161 cpu_stime /= n_cpu;
2162 MONITOR_SET(MONITOR_CPU_STIME_PCT, int64_t(cpu_stime));
2163 srv_cpu_usage.stime_pct = cpu_stime;
2164 }
2165 #else /* !UNIV_LINUX */
2166 #ifdef _WIN32
2167 /** Convert a FILETIME to microseconds.
2168 Do not cast a pointer to a FILETIME structure to either a ULARGE_INTEGER* or
2169 __int64* value because it can cause alignment faults on 64-bit Windows.
2170 */
2171 static uint64_t FILETIME_to_microseconds(const FILETIME &ft) {
2172 ULARGE_INTEGER ulg;
2173 ulg.HighPart = ft.dwHighDateTime;
2174 ulg.LowPart = ft.dwLowDateTime;
2175 return ulg.QuadPart / 10;
2176 }
2177
2178 /** Updates statistics about current CPU usage. */
2179 static void srv_update_cpu_usage() {
2180 using Clock = std::chrono::high_resolution_clock;
2181 using Clock_point = std::chrono::time_point<Clock>;
2182
2183 static Clock_point last_time = Clock::now();
2184
2185 static uint64_t last_cpu_utime;
2186 static uint64_t last_cpu_stime;
2187 static bool last_cpu_times_set = false;
2188
2189 Clock_point cur_time = Clock::now();
2190
2191 const auto time_diff = std::chrono::duration_cast<std::chrono::microseconds>(
2192 cur_time - last_time)
2193 .count();
2194
2195 if (time_diff < 100 * 1000LL) {
2196 return;
2197 }
2198 last_time = cur_time;
2199
2200 FILETIME process_creation_time;
2201 FILETIME process_exit_time;
2202 FILETIME process_kernel_time;
2203 FILETIME process_user_time;
2204
2205 if (!GetProcessTimes(GetCurrentProcess(), &process_creation_time,
2206 &process_exit_time, &process_kernel_time,
2207 &process_user_time)) {
2208 return;
2209 }
2210
2211 uint64_t cur_cpu_utime = FILETIME_to_microseconds(process_user_time);
2212 uint64_t cur_cpu_stime = FILETIME_to_microseconds(process_kernel_time);
2213 if (!last_cpu_times_set) {
2214 last_cpu_utime = cur_cpu_utime;
2215 last_cpu_stime = cur_cpu_stime;
2216 last_cpu_times_set = true;
2217 return;
2218 }
2219
2220 const auto cpu_utime_diff = cur_cpu_utime - last_cpu_utime;
2221 last_cpu_utime = cur_cpu_utime;
2222
2223 const auto cpu_stime_diff = cur_cpu_stime - last_cpu_stime;
2224 last_cpu_stime = cur_cpu_stime;
2225
2226 /* Calculate absolute. */
2227
2228 double cpu_utime = cpu_utime_diff * 100.0 / time_diff;
2229 MONITOR_SET(MONITOR_CPU_UTIME_ABS, int64_t(cpu_utime));
2230 srv_cpu_usage.utime_abs = cpu_utime;
2231
2232 double cpu_stime = cpu_stime_diff * 100.0 / time_diff;
2233 MONITOR_SET(MONITOR_CPU_STIME_ABS, int64_t(cpu_stime));
2234 srv_cpu_usage.stime_abs = cpu_stime;
2235
2236 /* Calculate relative. */
2237
2238 DWORD_PTR process_affinity_mask;
2239 DWORD_PTR system_affinity_mask;
2240 if (!GetProcessAffinityMask(GetCurrentProcess(), &process_affinity_mask,
2241 &system_affinity_mask)) {
2242 return;
2243 }
2244
2245 /* If the system has more than 64 processors and the current process
2246 contains threads in multiple groups, GetProcessAffinityMask returns
2247 zero for both affinity masks.
2248 */
2249 if ((process_affinity_mask == 0) && (system_affinity_mask == 0)) {
2250 return;
2251 }
2252
2253 int n_cpu = 0;
2254 constexpr int MAX_CPU_N = 64;
2255 uint64_t j = 1;
2256 for (int i = 0; i < MAX_CPU_N; ++i) {
2257 if (j & process_affinity_mask) {
2258 ++n_cpu;
2259 }
2260 j = j << 1;
2261 }
2262
2263 srv_cpu_usage.n_cpu = n_cpu;
2264 MONITOR_SET(MONITOR_CPU_N, int64_t(n_cpu));
2265
2266 if (n_cpu == 0) {
2267 return;
2268 }
2269
2270 cpu_utime /= n_cpu;
2271 MONITOR_SET(MONITOR_CPU_UTIME_PCT, int64_t(cpu_utime));
2272 srv_cpu_usage.utime_pct = cpu_utime;
2273
2274 cpu_stime /= n_cpu;
2275 MONITOR_SET(MONITOR_CPU_STIME_PCT, int64_t(cpu_stime));
2276 srv_cpu_usage.stime_pct = cpu_stime;
2277 }
2278 #else
2279 static void srv_update_cpu_usage() {
2280 srv_cpu_usage.utime_pct = 0;
2281 srv_cpu_usage.utime_abs = 0;
2282 srv_cpu_usage.stime_pct = 0;
2283 srv_cpu_usage.stime_abs = 0;
2284 srv_cpu_usage.n_cpu = 1;
2285 }
2286 #endif
2287
2288 #endif /* UNIV_LINUX || WIN32 */
2289
2290 /** Perform the tasks that the master thread is supposed to do when the
2291 server is active. There are two types of tasks. The first category is
2292 of such tasks which are performed at each invocation of this function.
2293 We assume that this function is called roughly every second when the
2294 server is active. The second category is of such tasks which are
2295 performed at some interval e.g.: purge, dict_LRU cleanup etc. */
2296 static void srv_master_do_active_tasks(void) {
2297 const auto cur_time = std::chrono::steady_clock::now();
2298 static std::chrono::steady_clock::time_point last_dict_lru_check;
2299
2300 /* First do the tasks that we are suppose to do at each
2301 invocation of this function. */
2302
2303 ++srv_main_active_loops;
2304
2305 MONITOR_INC(MONITOR_MASTER_ACTIVE_LOOPS);
2306
2307 /* ALTER TABLE in MySQL requires on Unix that the table handler
2308 can drop tables lazily after there no longer are SELECT
2309 queries to them. */
2310 {
2311 srv_main_thread_op_info = "doing background drop tables";
2312 const auto counter_time = std::chrono::steady_clock::now();
2313 row_drop_tables_for_mysql_in_background();
2314 MONITOR_INC_TIME(MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND,
2315 counter_time);
2316 }
2317
2318 ut_d(srv_master_do_disabled_loop());
2319
2320 if (srv_shutdown_state.load() >=
2321 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2322 return;
2323 }
2324
2325 /* Do an ibuf merge */
2326 {
2327 srv_main_thread_op_info = "doing insert buffer merge";
2328 const auto counter_time = std::chrono::steady_clock::now();
2329
2330 ibuf_merge_in_background(false);
2331 MONITOR_INC_TIME(MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time);
2332 }
2333
2334 /* Flush logs if needed */
2335 log_buffer_sync_in_background();
2336
2337 /* Now see if various tasks that are performed at defined
2338 intervals need to be performed. */
2339
2340 if (srv_shutdown_state.load() >=
2341 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2342 return;
2343 }
2344
2345 srv_update_cpu_usage();
2346
2347 if (trx_sys->rseg_history_len.load() > 0) {
2348 srv_wake_purge_thread_if_not_active();
2349 }
2350
2351 if (cur_time - last_dict_lru_check > SRV_MASTER_DICT_LRU_INTERVAL) {
2352 last_dict_lru_check = cur_time;
2353 srv_main_thread_op_info = "enforcing dict cache limit";
2354 const auto counter_time = std::chrono::steady_clock::now();
2355 ulint n_evicted = srv_master_evict_from_table_cache(50);
2356 if (n_evicted != 0) {
2357 MONITOR_INC_VALUE(MONITOR_SRV_DICT_LRU_EVICT_COUNT, n_evicted);
2358 }
2359 MONITOR_INC_TIME(MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time);
2360 }
2361 }
2362
2363 /** Perform the tasks that the master thread is supposed to do whenever the
2364 server is idle. We do check for the server state during this function
2365 and if the server has entered the shutdown phase we may return from
2366 the function without completing the required tasks.
2367 Note that the server can move to active state when we are executing this
2368 function but we don't check for that as we are suppose to perform more
2369 or less same tasks when server is active. */
2370 static void srv_master_do_idle_tasks(void) {
2371 ++srv_main_idle_loops;
2372
2373 MONITOR_INC(MONITOR_MASTER_IDLE_LOOPS);
2374
2375 /* ALTER TABLE in MySQL requires on Unix that the table handler
2376 can drop tables lazily after there no longer are SELECT
2377 queries to them. */
2378 {
2379 srv_main_thread_op_info = "doing background drop tables";
2380 const auto counter_time = std::chrono::steady_clock::now();
2381 row_drop_tables_for_mysql_in_background();
2382 MONITOR_INC_TIME(MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND,
2383 counter_time);
2384
2385 ut_d(srv_master_do_disabled_loop());
2386
2387 if (srv_shutdown_state.load() >=
2388 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2389 return;
2390 }
2391 }
2392
2393 /* Do an ibuf merge */
2394 {
2395 srv_main_thread_op_info = "doing insert buffer merge";
2396 const auto counter_time = std::chrono::steady_clock::now();
2397 ibuf_merge_in_background(true);
2398 MONITOR_INC_TIME(MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time);
2399 }
2400
2401 if (srv_shutdown_state.load() >=
2402 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2403 return;
2404 }
2405
2406 srv_update_cpu_usage();
2407
2408 if (trx_sys->rseg_history_len > 0) {
2409 srv_wake_purge_thread_if_not_active();
2410 }
2411
2412 srv_main_thread_op_info = "enforcing dict cache limit";
2413 const auto counter_time = std::chrono::steady_clock::now();
2414 ulint n_evicted = srv_master_evict_from_table_cache(100);
2415 if (n_evicted != 0) {
2416 MONITOR_INC_VALUE(MONITOR_SRV_DICT_LRU_EVICT_COUNT, n_evicted);
2417 }
2418 MONITOR_INC_TIME(MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time);
2419
2420 /* Flush logs if needed */
2421 log_buffer_sync_in_background();
2422 }
2423
2424 /** Perform the tasks during pre_dd_shutdown phase. The tasks that we do
2425 depend on srv_fast_shutdown:
2426 2 => very fast shutdown => do no book keeping
2427 0, 1 => normal or slow shutdown => clear drop table queue
2428 @param[in,out] last_print_time last time log message (about pending
2429 operations of shutdown) was printed
2430 @return true if there might be some work left to be done, false otherwise */
2431 static bool srv_master_do_pre_dd_shutdown_tasks(
2432 std::chrono::steady_clock::time_point *last_print_time) /*!< last time the
2433 function print the message */
2434 {
2435 ulint n_tables_to_drop = 0;
2436
2437 ut_ad(!srv_read_only_mode);
2438
2439 ++srv_main_shutdown_loops;
2440
2441 ut_a(srv_shutdown_state_matches([](auto state) {
2442 return state == SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS ||
2443 state == SRV_SHUTDOWN_EXIT_THREADS;
2444 }));
2445
2446 /* In very fast shutdown none of the following is necessary */
2447 if (srv_fast_shutdown == 2) {
2448 return (false);
2449 }
2450
2451 /* ALTER TABLE in MySQL requires on Unix that the table handler
2452 can drop tables lazily after there no longer are SELECT
2453 queries to them. */
2454 if (srv_force_recovery < SRV_FORCE_NO_BACKGROUND) {
2455 srv_main_thread_op_info = "doing background drop tables";
2456 n_tables_to_drop = row_drop_tables_for_mysql_in_background();
2457 }
2458
2459 /* Print progress message every 60 seconds during shutdown */
2460 srv_shutdown_print_master_pending(last_print_time, n_tables_to_drop, 0);
2461
2462 return (n_tables_to_drop != 0);
2463 }
2464
2465 /** Perform the tasks during shutdown. The tasks that we do at shutdown
2466 depend on srv_fast_shutdown:
2467 1, 2 => very fast shutdown => do no book keeping
2468 0 => slow shutdown => do ibuf merge
2469 @param[in,out] last_print_time last time log message (about pending
2470 operations of shutdown) was printed
2471 @return true if there might be some work left to be done, false otherwise */
2472 static bool srv_master_do_shutdown_tasks(
2473 std::chrono::steady_clock::time_point *last_print_time) /*!< last time the
2474 function print the message */
2475 {
2476 ulint n_bytes_merged = 0;
2477
2478 ut_ad(!srv_read_only_mode);
2479
2480 ++srv_main_shutdown_loops;
2481
2482 ut_a(srv_shutdown_state_matches([](auto state) {
2483 return state == SRV_SHUTDOWN_MASTER_STOP ||
2484 state == SRV_SHUTDOWN_EXIT_THREADS;
2485 }));
2486
2487 /* In very fast shutdown none of the following is necessary */
2488 if (srv_fast_shutdown >= 1) {
2489 return (false);
2490 }
2491
2492 /* In case of slow shutdown we do ibuf merge (unless innodb_force_recovery
2493 is greater or equal to SRV_FORCE_NO_IBUF_MERGE). */
2494 if (srv_force_recovery < SRV_FORCE_NO_IBUF_MERGE) {
2495 srv_main_thread_op_info = "doing insert buffer merge";
2496 n_bytes_merged = ibuf_merge_in_background(true);
2497 }
2498
2499 /* Print progress message every 60 seconds during shutdown */
2500 srv_shutdown_print_master_pending(last_print_time, 0, n_bytes_merged);
2501
2502 return (n_bytes_merged != 0);
2503 }
2504
2505 /* Enable REDO tablespace encryption */
2506 bool srv_enable_redo_encryption() {
2507 log_t &log = *log_sys;
2508
2509 /* While enabling encryption, make sure not to overwrite the existing
2510 redo log encryption key (if it has already been generated).
2511
2512 Note that we can safely check log.m_encryption_metadata without acquiring
2513 any of mutexes which are enlisted as required to protect updates of this
2514 field. That's because srv_enable_redo_encryption() is called either in
2515 startup phase, or during update of innodb_redo_log_encrypt. Server ensures
2516 that sysvars are not being updated concurrently and that they are not being
2517 updated during startup phase. */
2518 if (log_can_encrypt(log)) {
2519 return false;
2520 }
2521
2522 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT,
2523 dict_sys_t::s_log_space_id, false);
2524 if (notifier.failed()) {
2525 return true;
2526 }
2527
2528 /* Start to encrypt the redo log block from now on. */
2529 if (log_encryption_generate_metadata(log) != DB_SUCCESS) {
2530 ib::error(ER_IB_MSG_LOG_FILES_ENCRYPTION_INIT_FAILED);
2531 return true;
2532 }
2533
2534 /* Announce encryption is successfully enabled for the redo log. */
2535 ib::info(ER_IB_MSG_1245);
2536 return false;
2537 }
2538
2539 /* Set encryption for UNDO tablespace with given space id. */
2540 bool set_undo_tablespace_encryption(space_id_t space_id, mtr_t *mtr) {
2541 ut_ad(fsp_is_undo_tablespace(space_id));
2542 fil_space_t *space = fil_space_get(space_id);
2543
2544 dberr_t err;
2545 byte encrypt_info[Encryption::INFO_SIZE];
2546
2547 Encryption_metadata encryption_metadata;
2548
2549 Encryption::set_or_generate(Encryption::AES, nullptr, nullptr,
2550 encryption_metadata);
2551
2552 /* 0 fill encryption info */
2553 memset(encrypt_info, 0, Encryption::INFO_SIZE);
2554
2555 /* Fill up encryption info to be set */
2556 if (!Encryption::fill_encryption_info(encryption_metadata, true,
2557 encrypt_info)) {
2558 ib::error(ER_IB_MSG_1052, space->name);
2559 return true;
2560 }
2561
2562 uint32_t new_flags = space->flags | FSP_FLAGS_MASK_ENCRYPTION;
2563
2564 /* Write encryption info on tablespace header page */
2565 if (!fsp_header_write_encryption(space->id, new_flags, encrypt_info, true,
2566 false, mtr)) {
2567 ib::error(ER_IB_MSG_1053, space->name);
2568 return true;
2569 }
2570
2571 /* Update In-Mem encryption information for UNDO tablespace */
2572 fsp_flags_set_encryption(space->flags);
2573 err = fil_set_encryption(space->id, encryption_metadata.m_type,
2574 encryption_metadata.m_key, encryption_metadata.m_iv);
2575 if (err != DB_SUCCESS) {
2576 ib::error(ER_IB_MSG_1054, space->name, int{err}, ut_strerr(err));
2577 return true;
2578 }
2579
2580 return false;
2581 }
2582
2583 /* Enable UNDO tablespace encryption */
2584 bool srv_enable_undo_encryption() {
2585 /* Make sure undo::ddl_mutex is owned. */
2586 ut_ad(mutex_own(&undo::ddl_mutex));
2587 bool ret_val = false;
2588
2589 /* Traverse over all UNDO tablespaces and mark them encrypted. */
2590 undo::spaces->s_lock();
2591 for (auto undo_space : undo::spaces->m_spaces) {
2592 /* Skip system tablespace. */
2593 if (undo_space->id() == TRX_SYS_SPACE) {
2594 continue;
2595 }
2596
2597 fil_space_t *space = fil_space_get(undo_space->id());
2598 ut_ad(fsp_is_undo_tablespace(undo_space->id()));
2599
2600 /* While enabling encryption, make sure not to overwrite the tablespace key.
2601 Otherwise, pages encrypted with the old tablespace key can't be read. */
2602 if (FSP_FLAGS_GET_ENCRYPTION(space->flags)) {
2603 continue;
2604 }
2605
2606 Clone_notify notifier(Clone_notify::Type::SPACE_ALTER_ENCRYPT, space->id,
2607 false);
2608 if (notifier.failed()) {
2609 ret_val = true;
2610 break;
2611 }
2612
2613 undo_space->rsegs()->s_lock();
2614
2615 /* Make sure that there is enough reusable space in the redo log files. */
2616 log_free_check();
2617
2618 mtr_t mtr;
2619 mtr_start(&mtr);
2620 mtr_x_lock_space(space, &mtr);
2621
2622 if (set_undo_tablespace_encryption(undo_space->id(), &mtr)) {
2623 mtr_commit(&mtr);
2624 undo_space->rsegs()->s_unlock();
2625 ret_val = true;
2626 break;
2627 }
2628
2629 mtr_commit(&mtr);
2630 undo_space->rsegs()->s_unlock();
2631
2632 /* Announce encryption is successfully enabled for the undo tablespace. */
2633 ib::info(ER_IB_MSG_1055, undo_space->space_name());
2634 }
2635
2636 undo::spaces->s_unlock();
2637 return ret_val;
2638 }
2639
2640 /** Puts master thread to sleep. At this point we are using polling to
2641 service various activities. Master thread sleeps for one second before
2642 checking the state of the server again */
2643 static void srv_master_sleep(void) {
2644 srv_main_thread_op_info = "sleeping";
2645 std::this_thread::sleep_for(std::chrono::seconds(1));
2646 srv_main_thread_op_info = "";
2647 }
2648
2649 /** Waits on event in provided slot.
2650 @param[in] slot slot reserved as SRV_MASTER */
2651 static void srv_master_wait(srv_slot_t *slot) {
2652 srv_main_thread_op_info = "suspending";
2653
2654 srv_suspend_thread(slot);
2655
2656 /* DO NOT CHANGE THIS STRING.
2657 InnoDB manual also mentions this string in several places. */
2658 srv_main_thread_op_info = "waiting for server activity";
2659
2660 os_event_wait(slot->event);
2661 }
2662
2663 /** Executes the main loop of the master thread.
2664 @param[in] slot slot reserved as SRV_MASTER */
2665 static void srv_master_main_loop(srv_slot_t *slot) {
2666 if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
2667 /* When innodb_force_recovery is at least SRV_FORCE_NO_BACKGROUND,
2668 we avoid performing active/idle master's tasks. However, we still
2669 need to ensure that:
2670 srv_shutdown_state >= SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS,
2671 after we exited srv_master_main_loop(). Keep waiting until that
2672 is satisfied and then exit. */
2673 while (srv_shutdown_state.load() <
2674 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2675 srv_master_wait(slot);
2676 }
2677 return;
2678 }
2679
2680 ulint old_activity_count = srv_get_activity_count();
2681
2682 while (srv_shutdown_state.load() <
2683 SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS) {
2684 srv_master_sleep();
2685
2686 MONITOR_INC(MONITOR_MASTER_THREAD_SLEEP);
2687
2688 /* Just in case - if there is not much free space in redo,
2689 try to avoid asking for troubles because of extra work
2690 performed in such background thread. */
2691 srv_main_thread_op_info = "checking free log space";
2692 log_free_check();
2693
2694 if (srv_check_activity(old_activity_count)) {
2695 old_activity_count = srv_get_activity_count();
2696 srv_master_do_active_tasks();
2697 } else {
2698 srv_master_do_idle_tasks();
2699 }
2700
2701 /* Purge any deleted tablespace pages. */
2702 fil_purge();
2703 }
2704 }
2705
2706 /** Executes pre_dd_shutdown tasks in the master thread. */
2707 static void srv_master_pre_dd_shutdown_loop() {
2708 ut_a(srv_shutdown_state_matches([](auto state) {
2709 return state == SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS ||
2710 state == SRV_SHUTDOWN_EXIT_THREADS;
2711 }));
2712 auto last_print_time = std::chrono::steady_clock::now();
2713 while (srv_shutdown_state.load() < SRV_SHUTDOWN_EXIT_THREADS &&
2714 srv_master_do_pre_dd_shutdown_tasks(&last_print_time)) {
2715 /* Shouldn't loop here in case of very fast shutdown */
2716 ut_ad(srv_fast_shutdown < 2);
2717 }
2718 }
2719
2720 /** Executes shutdown tasks in the master thread. */
2721 static void srv_master_shutdown_loop() {
2722 ut_a(srv_shutdown_state_matches([](auto state) {
2723 return state == SRV_SHUTDOWN_MASTER_STOP ||
2724 state == SRV_SHUTDOWN_EXIT_THREADS;
2725 }));
2726 auto last_print_time = std::chrono::steady_clock::now();
2727 while (srv_shutdown_state.load() < SRV_SHUTDOWN_EXIT_THREADS &&
2728 srv_master_do_shutdown_tasks(&last_print_time)) {
2729 /* Shouldn't loop here in case of very fast shutdown */
2730 ut_ad(srv_fast_shutdown < 2);
2731 }
2732 }
2733
2734 /** The master thread controlling the server. */
2735 void srv_master_thread() {
2736 DBUG_TRACE;
2737
2738 srv_slot_t *slot;
2739
2740 THD *thd = create_internal_thd();
2741
2742 ut_ad(!srv_read_only_mode);
2743
2744 srv_main_thread_process_no = os_proc_get_number();
2745 srv_main_thread_id = std::this_thread::get_id();
2746
2747 slot = srv_reserve_slot(SRV_MASTER);
2748 ut_a(slot == srv_sys->sys_threads);
2749
2750 srv_master_main_loop(slot);
2751
2752 srv_master_pre_dd_shutdown_loop();
2753
2754 os_event_set(srv_threads.m_master_ready_for_dd_shutdown);
2755
2756 /* This is just for test scenarios. */
2757 srv_thread_delay_cleanup_if_needed(true);
2758
2759 while (srv_shutdown_state.load() < SRV_SHUTDOWN_MASTER_STOP) {
2760 srv_master_wait(slot);
2761 }
2762
2763 srv_master_shutdown_loop();
2764
2765 srv_main_thread_op_info = "exiting";
2766 destroy_internal_thd(thd);
2767 }
2768
2769 /**
2770 Check if purge should stop.
2771 @return true if it should shutdown. */
2772 static bool srv_purge_should_exit(
2773 ulint n_purged) /*!< in: pages purged in last batch */
2774 {
2775 switch (srv_shutdown_state.load()) {
2776 case SRV_SHUTDOWN_NONE:
2777 case SRV_SHUTDOWN_RECOVERY_ROLLBACK:
2778 case SRV_SHUTDOWN_PRE_DD_AND_SYSTEM_TRANSACTIONS:
2779 /* Normal operation. */
2780 break;
2781
2782 case SRV_SHUTDOWN_PURGE:
2783 /* Exit unless slow shutdown requested or all done. */
2784 return (srv_fast_shutdown != 0 || n_purged == 0);
2785
2786 case SRV_SHUTDOWN_EXIT_THREADS:
2787 return (true);
2788
2789 case SRV_SHUTDOWN_LAST_PHASE:
2790 case SRV_SHUTDOWN_FLUSH_PHASE:
2791 case SRV_SHUTDOWN_MASTER_STOP:
2792 case SRV_SHUTDOWN_CLEANUP:
2793 case SRV_SHUTDOWN_DD:
2794 ut_error;
2795 }
2796
2797 return (false);
2798 }
2799
2800 /** Fetch and execute a task from the work queue.
2801 @return true if a task was executed */
2802 static bool srv_task_execute(void) {
2803 que_thr_t *thr = nullptr;
2804
2805 ut_ad(!srv_read_only_mode);
2806 ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
2807
2808 if (UT_LIST_GET_LEN(srv_sys->tasks) == 0) {
2809 return false;
2810 }
2811
2812 mutex_enter(&srv_sys->tasks_mutex);
2813
2814 if (UT_LIST_GET_LEN(srv_sys->tasks) > 0) {
2815 thr = UT_LIST_GET_FIRST(srv_sys->tasks);
2816
2817 ut_a(que_node_get_type(thr->child) == QUE_NODE_PURGE);
2818
2819 UT_LIST_REMOVE(srv_sys->tasks, thr);
2820 }
2821
2822 mutex_exit(&srv_sys->tasks_mutex);
2823
2824 if (thr != nullptr) {
2825 que_run_threads(thr);
2826
2827 purge_sys->n_completed.fetch_add(1);
2828 }
2829
2830 return (thr != nullptr);
2831 }
2832
2833 /** Worker thread that reads tasks from the work queue and executes them. */
2834 void srv_worker_thread() {
2835 srv_slot_t *slot;
2836
2837 ut_ad(!srv_read_only_mode);
2838 ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
2839
2840 THD *thd = create_internal_thd();
2841
2842 purge_sys->is_this_a_purge_thread = true;
2843
2844 slot = srv_reserve_slot(SRV_WORKER);
2845
2846 ut_a(srv_n_purge_threads > 1);
2847
2848 srv_sys_mutex_enter();
2849
2850 ut_a(srv_sys->n_threads_active[SRV_WORKER] < srv_n_purge_threads);
2851
2852 srv_sys_mutex_exit();
2853
2854 /* We need to ensure that the worker threads exit after the
2855 purge coordinator thread. Otherwise the purge coordinaor can
2856 end up waiting forever in trx_purge_wait_for_workers_to_complete() */
2857
2858 do {
2859 srv_suspend_thread(slot);
2860
2861 os_event_wait(slot->event);
2862
2863 if (srv_task_execute()) {
2864 /* If there are tasks in the queue, wakeup
2865 the purge coordinator thread. */
2866
2867 srv_wake_purge_thread_if_not_active();
2868 }
2869
2870 /* Note: we are checking the state without holding the
2871 purge_sys->latch here. */
2872 } while (purge_sys->state != PURGE_STATE_EXIT);
2873
2874 srv_free_slot(slot);
2875
2876 rw_lock_x_lock(&purge_sys->latch, UT_LOCATION_HERE);
2877
2878 ut_a(!purge_sys->running);
2879 ut_a(purge_sys->state == PURGE_STATE_EXIT);
2880 ut_a(srv_shutdown_state.load() >= SRV_SHUTDOWN_PURGE);
2881
2882 rw_lock_x_unlock(&purge_sys->latch);
2883
2884 destroy_internal_thd(thd);
2885 }
2886
2887 /** Do the actual purge operation.
2888 @param[in,out] n_total_purged Total pages purged in this call
2889 @return length of history list before the last purge batch. */
2890 static ulint srv_do_purge(ulint *n_total_purged) {
2891 ulint n_pages_purged;
2892
2893 static ulint count = 0;
2894 static ulint n_use_threads = 0;
2895 static uint64_t rseg_history_len = 0;
2896 ulint old_activity_count = srv_get_activity_count();
2897 bool need_explicit_truncate = false;
2898
2899 const auto n_threads = srv_threads.m_purge_workers_n;
2900
2901 ut_a(n_threads > 0);
2902 ut_ad(!srv_read_only_mode);
2903
2904 /* Purge until there are no more records to purge and there is
2905 no change in configuration or server state. If the user has
2906 configured more than one purge thread then we treat that as a
2907 pool of threads and only use the extra threads if purge can't
2908 keep up with updates. */
2909
2910 if (n_use_threads == 0) {
2911 n_use_threads = n_threads;
2912 }
2913
2914 do {
2915 if (trx_sys->rseg_history_len.load() > rseg_history_len ||
2916 (srv_max_purge_lag > 0 && rseg_history_len > srv_max_purge_lag)) {
2917 /* History length is now longer than what it was
2918 when we took the last snapshot. Use more threads. */
2919
2920 if (n_use_threads < n_threads) {
2921 ++n_use_threads;
2922 }
2923
2924 } else if (srv_check_activity(old_activity_count) && n_use_threads > 1) {
2925 /* History length same or smaller since last snapshot,
2926 use fewer threads. */
2927
2928 --n_use_threads;
2929
2930 old_activity_count = srv_get_activity_count();
2931 }
2932
2933 /* Ensure that the purge threads are less than what
2934 was configured. */
2935
2936 ut_a(n_use_threads > 0);
2937 ut_a(n_use_threads <= n_threads);
2938
2939 /* Take a snapshot of the history list before purge. */
2940 if ((rseg_history_len = trx_sys->rseg_history_len.load()) == 0) {
2941 break;
2942 }
2943
2944 bool do_truncate = need_explicit_truncate ||
2945 srv_shutdown_state.load() == SRV_SHUTDOWN_PURGE ||
2946 (++count % srv_purge_rseg_truncate_frequency) == 0;
2947
2948 n_pages_purged =
2949 trx_purge(n_use_threads, srv_purge_batch_size, do_truncate);
2950
2951 *n_total_purged += n_pages_purged;
2952
2953 need_explicit_truncate = (n_pages_purged == 0);
2954 if (need_explicit_truncate) {
2955 undo::spaces->s_lock();
2956 need_explicit_truncate =
2957 (undo::spaces->find_first_inactive_explicit(nullptr) != nullptr);
2958 undo::spaces->s_unlock();
2959 }
2960 } while (purge_sys->state == PURGE_STATE_RUN &&
2961 (n_pages_purged > 0 || need_explicit_truncate) &&
2962 !srv_purge_should_exit(n_pages_purged));
2963
2964 return rseg_history_len;
2965 }
2966
2967 /** Suspend the purge coordinator thread. */
2968 static void srv_purge_coordinator_suspend(
2969 srv_slot_t *slot, /*!< in/out: Purge coordinator
2970 thread slot */
2971 ulint rseg_history_len) /*!< in: history list length
2972 before last purge */
2973 {
2974 ut_ad(!srv_read_only_mode);
2975 ut_a(slot->type == SRV_PURGE);
2976
2977 bool stop = false;
2978
2979 /** Maximum wait time on the purge event. */
2980 constexpr std::chrono::milliseconds SRV_PURGE_MAX_TIMEOUT{10};
2981
2982 int64_t sig_count = srv_suspend_thread(slot);
2983
2984 do {
2985 ulint ret;
2986
2987 rw_lock_x_lock(&purge_sys->latch, UT_LOCATION_HERE);
2988
2989 purge_sys->running = false;
2990
2991 rw_lock_x_unlock(&purge_sys->latch);
2992
2993 /* We don't wait right away on the the non-timed wait because
2994 we want to signal the thread that wants to suspend purge. */
2995
2996 if (stop) {
2997 os_event_wait_low(slot->event, sig_count);
2998 ret = 0;
2999 } else if (rseg_history_len <= trx_sys->rseg_history_len.load()) {
3000 ret =
3001 os_event_wait_time_low(slot->event, SRV_PURGE_MAX_TIMEOUT, sig_count);
3002 } else {
3003 /* We don't want to waste time waiting, if the
3004 history list increased by the time we got here,
3005 unless purge has been stopped. */
3006 ret = 0;
3007 }
3008
3009 srv_sys_mutex_enter();
3010
3011 /* The thread can be in state !suspended after the timeout
3012 but before this check if another thread sent a wakeup signal. */
3013
3014 if (slot->suspended) {
3015 slot->suspended = false;
3016 ++srv_sys->n_threads_active[slot->type];
3017 ut_a(srv_sys->n_threads_active[slot->type] == 1);
3018 }
3019
3020 srv_sys_mutex_exit();
3021
3022 sig_count = srv_suspend_thread(slot);
3023
3024 rw_lock_x_lock(&purge_sys->latch, UT_LOCATION_HERE);
3025
3026 stop = (srv_shutdown_state.load() < SRV_SHUTDOWN_PURGE &&
3027 purge_sys->state == PURGE_STATE_STOP);
3028
3029 if (!stop) {
3030 bool check = true;
3031 DBUG_EXECUTE_IF(
3032 "skip_purge_check_shutdown",
3033 if (srv_shutdown_state.load() >= SRV_SHUTDOWN_PURGE &&
3034 purge_sys->state == PURGE_STATE_STOP &&
3035 srv_fast_shutdown != 0) { check = false; };);
3036
3037 if (check) {
3038 ut_a(purge_sys->n_stop == 0);
3039 }
3040 purge_sys->running = true;
3041 } else {
3042 ut_a(purge_sys->n_stop > 0);
3043
3044 /* Signal that we are suspended. */
3045 os_event_set(purge_sys->event);
3046 }
3047
3048 rw_lock_x_unlock(&purge_sys->latch);
3049
3050 if (ret == OS_SYNC_TIME_EXCEEDED) {
3051 /* No new records added since wait started then simply
3052 wait for new records. The magic number 5000 is an
3053 approximation for the case where we have cached UNDO
3054 log records which prevent truncate of the UNDO
3055 segments. */
3056
3057 if (rseg_history_len == trx_sys->rseg_history_len &&
3058 trx_sys->rseg_history_len < 5000) {
3059 stop = true;
3060 }
3061 }
3062
3063 } while (stop);
3064
3065 srv_sys_mutex_enter();
3066
3067 if (slot->suspended) {
3068 slot->suspended = false;
3069 ++srv_sys->n_threads_active[slot->type];
3070 ut_a(srv_sys->n_threads_active[slot->type] == 1);
3071 }
3072
3073 srv_sys_mutex_exit();
3074 }
3075
3076 /** Purge coordinator thread that schedules the purge tasks. */
3077 void srv_purge_coordinator_thread() {
3078 srv_slot_t *slot;
3079
3080 THD *thd = create_internal_thd();
3081
3082 // Allow purge in read only mode as well.
3083 thd->set_skip_readonly_check();
3084
3085 purge_sys->is_this_a_purge_thread = true;
3086
3087 ulint n_total_purged = ULINT_UNDEFINED;
3088
3089 ut_ad(!srv_read_only_mode);
3090 ut_a(srv_n_purge_threads >= 1);
3091 ut_a(trx_purge_state() == PURGE_STATE_INIT);
3092 ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
3093
3094 rw_lock_x_lock(&purge_sys->latch, UT_LOCATION_HERE);
3095
3096 purge_sys->running = true;
3097 purge_sys->state = PURGE_STATE_RUN;
3098
3099 rw_lock_x_unlock(&purge_sys->latch);
3100
3101 slot = srv_reserve_slot(SRV_PURGE);
3102
3103 ulint rseg_history_len = trx_sys->rseg_history_len;
3104
3105 do {
3106 /* If there are no records to purge or the last
3107 purge didn't purge any records then wait for activity. */
3108
3109 if (srv_shutdown_state.load() < SRV_SHUTDOWN_PURGE &&
3110 (purge_sys->state == PURGE_STATE_STOP || n_total_purged == 0)) {
3111 srv_purge_coordinator_suspend(slot, rseg_history_len);
3112 }
3113
3114 if (srv_purge_should_exit(n_total_purged)) {
3115 ut_a(!slot->suspended);
3116 break;
3117 }
3118
3119 n_total_purged = 0;
3120
3121 rseg_history_len = srv_do_purge(&n_total_purged);
3122
3123 } while (!srv_purge_should_exit(n_total_purged));
3124
3125 /* This is just for test scenarios. Do not pass thd here,
3126 because it would lead to wait on event then, and we would
3127 never exit the srv_pre_dd_shutdown() which waits for this
3128 thread to exit. That's because the signal for which we
3129 would wait is signalled in srv_shutdown which happens
3130 after the srv_pre_dd_shutdown is ended. */
3131 srv_thread_delay_cleanup_if_needed(false);
3132
3133 /* Ensure that we don't jump out of the loop unless the
3134 exit condition is satisfied. */
3135
3136 ut_a(srv_purge_should_exit(n_total_purged));
3137
3138 ulint n_pages_purged = ULINT_MAX;
3139
3140 /* Ensure that all records are purged if it is not a fast shutdown.
3141 This covers the case where a record can be added after we exit the
3142 loop above. */
3143 while (srv_fast_shutdown == 0 && n_pages_purged > 0) {
3144 n_pages_purged = trx_purge(1, srv_purge_batch_size, false);
3145 }
3146
3147 /* This trx_purge is called to remove any undo records (added by
3148 background threads) after completion of the above loop. When
3149 srv_fast_shutdown != 0, a large batch size can cause significant
3150 delay in shutdown, so reducing the batch size to magic number 20
3151 (which was default in 5.5), which we hope will be sufficient to
3152 remove all the undo records */
3153 const uint temp_batch_size = 20;
3154
3155 n_pages_purged =
3156 trx_purge(1,
3157 srv_purge_batch_size <= temp_batch_size ? srv_purge_batch_size
3158 : temp_batch_size,
3159 true);
3160 ut_a(n_pages_purged == 0 || srv_fast_shutdown != 0);
3161
3162 /* The task queue should always be empty, independent of fast
3163 shutdown state. */
3164 ut_a(srv_get_task_queue_length() == 0);
3165
3166 srv_free_slot(slot);
3167
3168 /* Note that we are shutting down. */
3169 rw_lock_x_lock(&purge_sys->latch, UT_LOCATION_HERE);
3170
3171 purge_sys->state = PURGE_STATE_EXIT;
3172
3173 /* Clear out any pending undo-tablespaces to truncate and reset
3174 the list as we plan to shutdown the purge thread. */
3175 purge_sys->undo_trunc.reset();
3176
3177 purge_sys->running = false;
3178
3179 rw_lock_x_unlock(&purge_sys->latch);
3180
3181 /* Ensure that all the worker threads quit. */
3182 if (srv_n_purge_threads > 1) {
3183 srv_release_threads(SRV_WORKER, srv_n_purge_threads - 1);
3184 }
3185
3186 /* This is just for test scenarios. Do not pass thd here.
3187 For explanation look at comment for similar usage above. */
3188 srv_thread_delay_cleanup_if_needed(false);
3189
3190 destroy_internal_thd(thd);
3191 }
3192
3193 /** Enqueues a task to server task queue and releases a worker thread, if there
3194 is a suspended one. */
3195 void srv_que_task_enqueue_low(que_thr_t *thr) /*!< in: query thread */
3196 {
3197 ut_ad(!srv_read_only_mode);
3198 mutex_enter(&srv_sys->tasks_mutex);
3199
3200 UT_LIST_ADD_LAST(srv_sys->tasks, thr);
3201
3202 mutex_exit(&srv_sys->tasks_mutex);
3203
3204 srv_release_threads(SRV_WORKER, 1);
3205 }
3206
3207 /** Get count of tasks in the queue.
3208 @return number of tasks in queue */
3209 ulint srv_get_task_queue_length(void) {
3210 ut_ad(!srv_read_only_mode);
3211
3212 return UT_LIST_GET_LEN(srv_sys->tasks);
3213 }
3214
3215 /** Wakeup the purge threads. */
3216 void srv_purge_wakeup(void) {
3217 ut_ad(!srv_read_only_mode);
3218
3219 if (srv_force_recovery < SRV_FORCE_NO_BACKGROUND) {
3220 srv_release_threads(SRV_PURGE, 1);
3221
3222 if (srv_threads.m_purge_workers_n > 1) {
3223 /* SRV_PURGE is not counted here. */
3224 ulint n_workers = srv_threads.m_purge_workers_n - 1;
3225
3226 srv_release_threads(SRV_WORKER, n_workers);
3227 }
3228 }
3229 }
3230
3231 /** Check if the purge threads are active, both coordinator and worker threads
3232 @return true if any thread is active, false if no thread is active */
3233 bool srv_purge_threads_active() {
3234 if (srv_threads.m_purge_workers == nullptr) {
3235 #ifdef UNIV_DEBUG
3236 ut_a(srv_read_only_mode);
3237 #endif /* UNIV_DEBUG */
3238 ut_ad(!srv_thread_is_active(srv_threads.m_purge_coordinator));
3239 return (false);
3240 }
3241
3242 for (size_t i = 0; i < srv_threads.m_purge_workers_n; ++i) {
3243 if (srv_thread_is_active(srv_threads.m_purge_workers[i])) {
3244 ut_ad(!srv_read_only_mode);
3245 return (true);
3246 }
3247 }
3248
3249 ut_ad(!srv_thread_is_active(srv_threads.m_purge_coordinator));
3250
3251 return (false);
3252 }
3253
3254 bool srv_thread_is_active(const IB_thread &thread) {
3255 return (thread_is_active(thread));
3256 }
3257
3258 bool srv_thread_is_stopped(const IB_thread &thread) {
3259 return (thread_is_stopped(thread));
3260 }
3261
3262 #endif /* !UNIV_HOTBACKUP */
3263
3264 const char *srv_get_server_errmsgs(int errcode) {
3265 return (error_message_for_error_log(errcode));
3266 }
3267
3268 void set_srv_redo_log(bool enable) {
3269 mutex_enter(&srv_innodb_monitor_mutex);
3270 srv_redo_log = enable;
3271 mutex_exit(&srv_innodb_monitor_mutex);
3272 }