-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsrv0srv.cc
3081 lines (2473 loc) · 89.3 KB
/
srv0srv.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
Copyright (c) 1995, 2017, Oracle and/or its affiliates. All Rights Reserved.
Copyright (c) 2008, 2009 Google Inc.
Copyright (c) 2009, Percona Inc.
Copyright (c) 2013, 2021, MariaDB Corporation.
Portions of this file contain modifications contributed and copyrighted by
Google, Inc. Those modifications are gratefully acknowledged and are described
briefly in the InnoDB documentation. The contributions by Google are
incorporated with their permission, and subject to the conditions contained in
the file COPYING.Google.
Portions of this file contain modifications contributed and copyrighted
by Percona Inc.. Those modifications are
gratefully acknowledged and are described briefly in the InnoDB
documentation. The contributions by Percona Inc. are incorporated with
their permission, and subject to the conditions contained in the file
COPYING.Percona.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file srv/srv0srv.cc
The database server main program
Created 10/8/1995 Heikki Tuuri
*******************************************************/
#include "my_global.h"
// JAN: TODO: MySQL 5.7 missing header
//#include "my_thread.h"
//
// #include "mysql/psi/mysql_stage.h"
// #include "mysql/psi/psi.h"
#include "btr0sea.h"
#include "buf0flu.h"
#include "buf0lru.h"
#include "dict0boot.h"
#include "dict0load.h"
#include "ibuf0ibuf.h"
#include "lock0lock.h"
#include "log0recv.h"
#include "mem0mem.h"
#include "os0proc.h"
#include "pars0pars.h"
#include "que0que.h"
#include "row0mysql.h"
#include "row0trunc.h"
#include "row0log.h"
#include "srv0mon.h"
#include "srv0srv.h"
#include "srv0start.h"
#include "sync0sync.h"
#include "trx0i_s.h"
#include "trx0purge.h"
#include "ut0crc32.h"
#include "btr0defragment.h"
#include "ut0mem.h"
#include "fil0fil.h"
#include "fil0crypt.h"
#include "fil0pagecompress.h"
#include "btr0scrub.h"
#include <my_service_manager.h>
#ifdef WITH_WSREP
extern int wsrep_debug;
extern int wsrep_trx_is_aborting(void *thd_ptr);
#endif
/* The following is the maximum allowed duration of a lock wait. */
UNIV_INTERN ulong srv_fatal_semaphore_wait_threshold = DEFAULT_SRV_FATAL_SEMAPHORE_TIMEOUT;
/* How much data manipulation language (DML) statements need to be delayed,
in microseconds, in order to reduce the lagging of the purge thread. */
ulint srv_dml_needed_delay;
bool srv_monitor_active;
bool srv_error_monitor_active;
bool srv_buf_dump_thread_active;
bool srv_dict_stats_thread_active;
bool srv_buf_resize_thread_active;
my_bool srv_scrub_log;
const char* srv_main_thread_op_info = "";
/** Prefix used by MySQL to indicate pre-5.1 table name encoding */
const char srv_mysql50_table_name_prefix[10] = "#mysql50#";
/* Server parameters which are read from the initfile */
/* The following three are dir paths which are catenated before file
names, where the file name itself may also contain a path */
char* srv_data_home;
/** Rollback files directory, can be absolute. */
char* srv_undo_dir;
/** The number of tablespaces to use for rollback segments. */
ulong srv_undo_tablespaces;
/** The number of UNDO tablespaces that are open and ready to use. */
ulint srv_undo_tablespaces_open;
/** The number of UNDO tablespaces that are active (hosting some rollback
segment). It is quite possible that some of the tablespaces doesn't host
any of the rollback-segment based on configuration used. */
ulint srv_undo_tablespaces_active;
/* The number of rollback segments to use */
ulong srv_undo_logs;
/** Rate at which UNDO records should be purged. */
ulong srv_purge_rseg_truncate_frequency;
/** Enable or Disable Truncate of UNDO tablespace.
Note: If enabled then UNDO tablespace will be selected for truncate.
While Server waits for undo-tablespace to truncate if user disables
it, truncate action is completed but no new tablespace is marked
for truncate (action is never aborted). */
my_bool srv_undo_log_truncate;
/** Maximum size of undo tablespace. */
unsigned long long srv_max_undo_log_size;
/** Default undo tablespace size in UNIV_PAGEs count (10MB). */
const ulint SRV_UNDO_TABLESPACE_SIZE_IN_PAGES =
((1024 * 1024) * 10) / UNIV_PAGE_SIZE_DEF;
/** Set if InnoDB must operate in read-only mode. We don't do any
recovery and open all tables in RO mode instead of RW mode. We don't
sync the max trx id to disk either. */
my_bool srv_read_only_mode;
/** store to its own file each table created by an user; data
dictionary tables are in the system tablespace 0 */
my_bool srv_file_per_table;
/** whether to use backup-safe TRUNCATE and crash-safe RENAME
instead of the MySQL 5.7 WL#6501 TRUNCATE TABLE implementation */
my_bool srv_safe_truncate;
/** The file format to use on new *.ibd files. */
ulint srv_file_format;
/** Whether to check file format during startup. A value of
UNIV_FORMAT_MAX + 1 means no checking ie. FALSE. The default is to
set it to the highest format we support. */
ulint srv_max_file_format_at_startup = UNIV_FORMAT_MAX;
/** Set if InnoDB operates in read-only mode or innodb-force-recovery
is greater than SRV_FORCE_NO_TRX_UNDO. */
my_bool high_level_read_only;
#if UNIV_FORMAT_A
# error "UNIV_FORMAT_A must be 0!"
#endif
/** Place locks to records only i.e. do not use next-key locking except
on duplicate key checking and foreign key checking */
ibool srv_locks_unsafe_for_binlog;
/** Sort buffer size in index creation */
ulong srv_sort_buf_size;
/** Maximum modification log file size for online index creation */
unsigned long long srv_online_max_size;
/* If this flag is TRUE, then we will use the native aio of the
OS (provided we compiled Innobase with it in), otherwise we will
use simulated aio we build below with threads.
Currently we support native aio on windows and linux */
my_bool srv_use_native_aio;
my_bool srv_numa_interleave;
/** innodb_use_trim; whether to use fallocate(PUNCH_HOLE) with
page_compression */
my_bool srv_use_trim;
/** copy of innodb_use_atomic_writes; @see innobase_init() */
my_bool srv_use_atomic_writes;
/** innodb_compression_algorithm; used with page compression */
ulong innodb_compression_algorithm;
/** innodb_mtflush_threads; number of threads used for multi-threaded flush */
long srv_mtflush_threads;
/** innodb_use_mtflush; whether to use multi threaded flush. */
my_bool srv_use_mtflush;
#ifdef UNIV_DEBUG
/** Used by SET GLOBAL innodb_master_thread_disabled_debug = X. */
my_bool srv_master_thread_disabled_debug;
/** Event used to inform that master thread is disabled. */
static os_event_t srv_master_thread_disabled_event;
#endif /* UNIV_DEBUG */
/*------------------------- LOG FILES ------------------------ */
char* srv_log_group_home_dir;
ulong srv_n_log_files;
/** The InnoDB redo log file size, or 0 when changing the redo log format
at startup (while disallowing writes to the redo log). */
ulonglong srv_log_file_size;
/** copy of innodb_log_buffer_size, but in database pages */
ulint srv_log_buffer_size;
/** innodb_flush_log_at_trx_commit */
ulong srv_flush_log_at_trx_commit;
/** innodb_flush_log_at_timeout */
uint srv_flush_log_at_timeout;
/** innodb_page_size */
ulong srv_page_size;
/** log2 of innodb_page_size; @see innobase_init() */
ulong srv_page_size_shift;
/** innodb_log_write_ahead_size */
ulong srv_log_write_ahead_size;
page_size_t univ_page_size(0, 0, false);
/** innodb_adaptive_flushing; try to flush dirty pages so as to avoid
IO bursts at the checkpoints. */
my_bool srv_adaptive_flushing;
/** innodb_flush_sync; whether to ignore io_capacity at log checkpoints */
my_bool srv_flush_sync;
/** Maximum number of times allowed to conditionally acquire
mutex before switching to blocking wait on the mutex */
#define MAX_MUTEX_NOWAIT 20
/** Check whether the number of failed nonblocking mutex
acquisition attempts exceeds maximum allowed value. If so,
srv_printf_innodb_monitor() will request mutex acquisition
with mutex_enter(), which will wait until it gets the mutex. */
#define MUTEX_NOWAIT(mutex_skipped) ((mutex_skipped) < MAX_MUTEX_NOWAIT)
#ifdef WITH_INNODB_DISALLOW_WRITES
UNIV_INTERN os_event_t srv_allow_writes_event;
#endif /* WITH_INNODB_DISALLOW_WRITES */
/** copy of innodb_buffer_pool_size */
ulint srv_buf_pool_size;
/** Requested buffer pool chunk size. Each buffer pool instance consists
of one or more chunks. */
ulong srv_buf_pool_chunk_unit;
/** innodb_buffer_pool_instances (0 is interpreted as 1) */
ulong srv_buf_pool_instances;
/** Default value of innodb_buffer_pool_instances */
const ulong srv_buf_pool_instances_default = 0;
/** innodb_page_hash_locks (a debug-only parameter);
number of locks to protect buf_pool->page_hash */
ulong srv_n_page_hash_locks = 16;
/** innodb_lru_scan_depth; number of blocks scanned in LRU flush batch */
ulong srv_LRU_scan_depth;
/** innodb_flush_neighbors; whether or not to flush neighbors of a block */
ulong srv_flush_neighbors;
/** Previously requested size */
ulint srv_buf_pool_old_size;
/** Current size as scaling factor for the other components */
ulint srv_buf_pool_base_size;
/** Current size in bytes */
ulint srv_buf_pool_curr_size;
/** Dump this % of each buffer pool during BP dump */
ulong srv_buf_pool_dump_pct;
/** Lock table size in bytes */
ulint srv_lock_table_size = ULINT_MAX;
/** copy of innodb_read_io_threads */
ulint srv_n_read_io_threads;
/** copy of innodb_write_io_threads */
ulint srv_n_write_io_threads;
/** innodb_random_read_ahead */
my_bool srv_random_read_ahead;
/** innodb_read_ahead_threshold; the number of pages that must be present
in the buffer cache and accessed sequentially for InnoDB to trigger a
readahead request. */
ulong srv_read_ahead_threshold;
/** innodb_change_buffer_max_size; maximum on-disk size of change
buffer in terms of percentage of the buffer pool. */
uint srv_change_buffer_max_size;
char* srv_file_flush_method_str;
enum srv_flush_t srv_file_flush_method = IF_WIN(SRV_ALL_O_DIRECT_FSYNC,SRV_FSYNC);
/** copy of innodb_open_files, initialized by innobase_init() */
ulint srv_max_n_open_files;
/** innodb_io_capacity */
ulong srv_io_capacity;
/** innodb_io_capacity_max */
ulong srv_max_io_capacity;
/** innodb_page_cleaners; the number of page cleaner threads */
ulong srv_n_page_cleaners;
/* The InnoDB main thread tries to keep the ratio of modified pages
in the buffer pool to all database pages in the buffer pool smaller than
the following number. But it is not guaranteed that the value stays below
that during a time of heavy update/insert activity. */
/** innodb_max_dirty_pages_pct */
double srv_max_buf_pool_modified_pct;
/** innodb_max_dirty_pages_pct_lwm */
double srv_max_dirty_pages_pct_lwm;
/** innodb_adaptive_flushing_lwm; the percentage of log capacity at
which adaptive flushing, if enabled, will kick in. */
double srv_adaptive_flushing_lwm;
/** innodb_flushing_avg_loops; number of iterations over which
adaptive flushing is averaged */
ulong srv_flushing_avg_loops;
/** innodb_purge_threads; the number of purge threads to use */
ulong srv_n_purge_threads;
/** innodb_purge_batch_size, in pages */
ulong srv_purge_batch_size;
/** innodb_stats_method decides how InnoDB treats
NULL value when collecting statistics. By default, it is set to
SRV_STATS_NULLS_EQUAL(0), ie. all NULL value are treated equal */
ulong srv_innodb_stats_method;
srv_stats_t srv_stats;
/* structure to pass status variables to MySQL */
export_var_t export_vars;
/** Normally 0. When nonzero, skip some phases of crash recovery,
starting from SRV_FORCE_IGNORE_CORRUPT, so that data can be recovered
by SELECT or mysqldump. When this is nonzero, we do not allow any user
modifications to the data. */
ulong srv_force_recovery;
/** innodb_print_all_deadlocks; whether to print all user-level
transactions deadlocks to the error log */
my_bool srv_print_all_deadlocks;
/** innodb_cmp_per_index_enabled; enable
INFORMATION_SCHEMA.innodb_cmp_per_index */
my_bool srv_cmp_per_index_enabled;
/** innodb_fast_shutdown; if 1 then we do not run purge and insert buffer
merge to completion before shutdown. If it is set to 2, do not even flush the
buffer pool to data files at the shutdown: we effectively 'crash'
InnoDB (but lose no committed transactions). */
uint srv_fast_shutdown;
/** copy of innodb_status_file; generate a innodb_status.<pid> file */
ibool srv_innodb_status;
/** innodb_prefix_index_cluster_optimization; whether to optimize
prefix index queries to skip cluster index lookup when possible */
my_bool srv_prefix_index_cluster_optimization;
/** innodb_stats_transient_sample_pages;
When estimating number of different key values in an index, sample
this many index pages, there are 2 ways to calculate statistics:
* persistent stats that are calculated by ANALYZE TABLE and saved
in the innodb database.
* quick transient stats, that are used if persistent stats for the given
table/index are not found in the innodb database */
unsigned long long srv_stats_transient_sample_pages;
/** innodb_stats_persistent */
my_bool srv_stats_persistent;
/** innodb_stats_include_delete_marked */
my_bool srv_stats_include_delete_marked;
/** innodb_stats_persistent_sample_pages */
unsigned long long srv_stats_persistent_sample_pages;
/** innodb_stats_auto_recalc */
my_bool srv_stats_auto_recalc;
/** innodb_stats_modified_counter; The number of rows modified before
we calculate new statistics (default 0 = current limits) */
unsigned long long srv_stats_modified_counter;
/** innodb_stats_traditional; enable traditional statistic calculation
based on number of configured pages */
my_bool srv_stats_sample_traditional;
/** copy of innodb_doublewrite */
ibool srv_use_doublewrite_buf;
/** innodb_doublewrite_batch_size (a debug parameter) specifies the
number of pages to use in LRU and flush_list batch flushing.
The rest of the doublewrite buffer is used for single-page flushing. */
ulong srv_doublewrite_batch_size = 120;
/** innodb_replication_delay */
ulong srv_replication_delay;
/** innodb_sync_spin_loops */
ulong srv_n_spin_wait_rounds;
/** innodb_spin_wait_delay */
uint srv_spin_wait_delay;
static ulint srv_n_rows_inserted_old;
static ulint srv_n_rows_updated_old;
static ulint srv_n_rows_deleted_old;
static ulint srv_n_rows_read_old;
static ulint srv_n_system_rows_inserted_old;
static ulint srv_n_system_rows_updated_old;
static ulint srv_n_system_rows_deleted_old;
static ulint srv_n_system_rows_read_old;
ulint srv_truncated_status_writes;
/** Number of initialized rollback segments for persistent undo log */
ulong srv_available_undo_logs;
/* Defragmentation */
UNIV_INTERN my_bool srv_defragment;
/** innodb_defragment_n_pages */
UNIV_INTERN uint srv_defragment_n_pages;
UNIV_INTERN uint srv_defragment_stats_accuracy;
/** innodb_defragment_fill_factor_n_recs */
UNIV_INTERN uint srv_defragment_fill_factor_n_recs;
/** innodb_defragment_fill_factor */
UNIV_INTERN double srv_defragment_fill_factor;
/** innodb_defragment_frequency */
UNIV_INTERN uint srv_defragment_frequency;
/** derived from innodb_defragment_frequency;
@see innodb_defragment_frequency_update() */
UNIV_INTERN ulonglong srv_defragment_interval;
/** Current mode of operation */
UNIV_INTERN enum srv_operation_mode srv_operation;
/* Set the following to 0 if you want InnoDB to write messages on
stderr on startup/shutdown. Not enabled on the embedded server. */
ibool srv_print_verbose_log;
my_bool srv_print_innodb_monitor;
my_bool srv_print_innodb_lock_monitor;
/** innodb_force_primary_key; whether to disallow CREATE TABLE without
PRIMARY KEY */
my_bool srv_force_primary_key;
/** Key version to encrypt the temporary tablespace */
my_bool innodb_encrypt_temporary_tables;
/* Array of English strings describing the current state of an
i/o handler thread */
const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
static time_t srv_last_monitor_time;
static ib_mutex_t srv_innodb_monitor_mutex;
/** Mutex protecting page_zip_stat_per_index */
ib_mutex_t page_zip_stat_per_index_mutex;
/* Mutex for locking srv_monitor_file. Not created if srv_read_only_mode */
ib_mutex_t srv_monitor_file_mutex;
/** Temporary file for innodb monitor output */
FILE* srv_monitor_file;
/** Mutex for locking srv_misc_tmpfile. Not created if srv_read_only_mode.
This mutex has a very low rank; threads reserving it should not
acquire any further latches or sleep before releasing this one. */
ib_mutex_t srv_misc_tmpfile_mutex;
/** Temporary file for miscellanous diagnostic output */
FILE* srv_misc_tmpfile;
static ulint srv_main_thread_process_no;
static ulint srv_main_thread_id;
/* The following counts are used by the srv_master_thread. */
/** Iterations of the loop bounded by 'srv_active' label. */
static ulint srv_main_active_loops;
/** Iterations of the loop bounded by the 'srv_idle' label. */
static ulint srv_main_idle_loops;
/** Iterations of the loop bounded by the 'srv_shutdown' label. */
static ulint srv_main_shutdown_loops;
/** Log writes involving flush. */
static ulint srv_log_writes_and_flush;
/* This is only ever touched by the master thread. It records the
time when the last flush of log file has happened. The master
thread ensures that we flush the log files at least once per
second. */
static time_t srv_last_log_flush_time;
/* Interval in seconds at which various tasks are performed by the
master thread when server is active. In order to balance the workload,
we should try to keep intervals such that they are not multiple of
each other. For example, if we have intervals for various tasks
defined as 5, 10, 15, 60 then all tasks will be performed when
current_time % 60 == 0 and no tasks will be performed when
current_time % 5 != 0. */
# define SRV_MASTER_CHECKPOINT_INTERVAL (7)
#ifdef MEM_PERIODIC_CHECK
# define SRV_MASTER_MEM_VALIDATE_INTERVAL (13)
#endif /* MEM_PERIODIC_CHECK */
# define SRV_MASTER_DICT_LRU_INTERVAL (47)
/** Buffer pool dump status frequence in percentages */
UNIV_INTERN ulong srv_buf_dump_status_frequency;
/** Acquire the system_mutex. */
#define srv_sys_mutex_enter() do { \
mutex_enter(&srv_sys.mutex); \
} while (0)
/** Test if the system mutex is owned. */
#define srv_sys_mutex_own() (mutex_own(&srv_sys.mutex) \
&& !srv_read_only_mode)
/** Release the system mutex. */
#define srv_sys_mutex_exit() do { \
mutex_exit(&srv_sys.mutex); \
} while (0)
#define fetch_lock_wait_timeout(trx) \
((trx)->lock.allowed_to_wait \
? thd_lock_wait_timeout((trx)->mysql_thd) \
: 0)
/*
IMPLEMENTATION OF THE SERVER MAIN PROGRAM
=========================================
There is the following analogue between this database
server and an operating system kernel:
DB concept equivalent OS concept
---------- ---------------------
transaction -- process;
query thread -- thread;
lock -- semaphore;
kernel -- kernel;
query thread execution:
(a) without lock mutex
reserved -- process executing in user mode;
(b) with lock mutex reserved
-- process executing in kernel mode;
The server has several backgroind threads all running at the same
priority as user threads. It periodically checks if here is anything
happening in the server which requires intervention of the master
thread. Such situations may be, for example, when flushing of dirty
blocks is needed in the buffer pool or old version of database rows
have to be cleaned away (purged). The user can configure a separate
dedicated purge thread(s) too, in which case the master thread does not
do any purging.
The threads which we call user threads serve the queries of the MySQL
server. They run at normal priority.
When there is no activity in the system, also the master thread
suspends itself to wait for an event making the server totally silent.
There is still one complication in our server design. If a
background utility thread obtains a resource (e.g., mutex) needed by a user
thread, and there is also some other user activity in the system,
the user thread may have to wait indefinitely long for the
resource, as the OS does not schedule a background thread if
there is some other runnable user thread. This problem is called
priority inversion in real-time programming.
One solution to the priority inversion problem would be to keep record
of which thread owns which resource and in the above case boost the
priority of the background thread so that it will be scheduled and it
can release the resource. This solution is called priority inheritance
in real-time programming. A drawback of this solution is that the overhead
of acquiring a mutex increases slightly, maybe 0.2 microseconds on a 100
MHz Pentium, because the thread has to call os_thread_get_curr_id. This may
be compared to 0.5 microsecond overhead for a mutex lock-unlock pair. Note
that the thread cannot store the information in the resource , say mutex,
itself, because competing threads could wipe out the information if it is
stored before acquiring the mutex, and if it stored afterwards, the
information is outdated for the time of one machine instruction, at least.
(To be precise, the information could be stored to lock_word in mutex if
the machine supports atomic swap.)
The above solution with priority inheritance may become actual in the
future, currently we do not implement any priority twiddling solution.
Our general aim is to reduce the contention of all mutexes by making
them more fine grained.
The thread table contains information of the current status of each
thread existing in the system, and also the event semaphores used in
suspending the master thread and utility threads when they have nothing
to do. The thread table can be seen as an analogue to the process table
in a traditional Unix implementation. */
/** The server system struct */
struct srv_sys_t{
ib_mutex_t tasks_mutex; /*!< variable protecting the
tasks queue */
UT_LIST_BASE_NODE_T(que_thr_t)
tasks; /*!< task queue */
ib_mutex_t mutex; /*!< variable protecting the
fields below. */
ulint n_sys_threads; /*!< size of the sys_threads
array */
srv_slot_t
sys_threads[srv_max_purge_threads + 1]; /*!< server thread table;
os_event_set() and
os_event_reset() on
sys_threads[]->event are
covered by srv_sys_t::mutex */
ulint n_threads_active[SRV_MASTER + 1];
/*!< number of threads active
in a thread class; protected
by both my_atomic_addlint()
and mutex */
srv_stats_t::ulint_ctr_1_t
activity_count; /*!< For tracking server
activity */
};
static srv_sys_t srv_sys;
/** Event to signal srv_monitor_thread. Not protected by a mutex.
Set after setting srv_print_innodb_monitor. */
os_event_t srv_monitor_event;
/** Event to signal the shutdown of srv_error_monitor_thread.
Not protected by a mutex. */
os_event_t srv_error_event;
/** Event for waking up buf_dump_thread. Not protected by a mutex.
Set on shutdown or by buf_dump_start() or buf_load_start(). */
os_event_t srv_buf_dump_event;
/** Event to signal the buffer pool resize thread */
os_event_t srv_buf_resize_event;
/** The buffer pool dump/load file name */
char* srv_buf_dump_filename;
/** Boolean config knobs that tell InnoDB to dump the buffer pool at shutdown
and/or load it during startup. */
char srv_buffer_pool_dump_at_shutdown = TRUE;
char srv_buffer_pool_load_at_startup = TRUE;
/** Slot index in the srv_sys.sys_threads array for the master thread. */
#define SRV_MASTER_SLOT 0
/** Slot index in the srv_sys.sys_threads array for the purge thread. */
#define SRV_PURGE_SLOT 1
/** Slot index in the srv_sys.sys_threads array from which purge workers start.
*/
#define SRV_WORKER_SLOTS_START 2
#ifdef HAVE_PSI_STAGE_INTERFACE
/** Performance schema stage event for monitoring ALTER TABLE progress
everything after flush log_make_checkpoint(). */
PSI_stage_info srv_stage_alter_table_end
= {0, "alter table (end)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring ALTER TABLE progress
log_make_checkpoint(). */
PSI_stage_info srv_stage_alter_table_flush
= {0, "alter table (flush)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring ALTER TABLE progress
row_merge_insert_index_tuples(). */
PSI_stage_info srv_stage_alter_table_insert
= {0, "alter table (insert)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring ALTER TABLE progress
row_log_apply(). */
PSI_stage_info srv_stage_alter_table_log_index
= {0, "alter table (log apply index)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring ALTER TABLE progress
row_log_table_apply(). */
PSI_stage_info srv_stage_alter_table_log_table
= {0, "alter table (log apply table)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring ALTER TABLE progress
row_merge_sort(). */
PSI_stage_info srv_stage_alter_table_merge_sort
= {0, "alter table (merge sort)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring ALTER TABLE progress
row_merge_read_clustered_index(). */
PSI_stage_info srv_stage_alter_table_read_pk_internal_sort
= {0, "alter table (read PK and internal sort)", PSI_FLAG_STAGE_PROGRESS};
/** Performance schema stage event for monitoring buffer pool load progress. */
PSI_stage_info srv_stage_buffer_pool_load
= {0, "buffer pool load", PSI_FLAG_STAGE_PROGRESS};
#endif /* HAVE_PSI_STAGE_INTERFACE */
/*********************************************************************//**
Prints counters for work done by srv_master_thread. */
static
void
srv_print_master_thread_info(
/*=========================*/
FILE *file) /* in: output stream */
{
fprintf(file, "srv_master_thread loops: " ULINTPF " srv_active, "
ULINTPF " srv_shutdown, " ULINTPF " srv_idle\n"
"srv_master_thread log flush and writes: " ULINTPF "\n",
srv_main_active_loops,
srv_main_shutdown_loops,
srv_main_idle_loops,
srv_log_writes_and_flush);
}
/*********************************************************************//**
Sets the info describing an i/o thread current state. */
void
srv_set_io_thread_op_info(
/*======================*/
ulint i, /*!< in: the 'segment' of the i/o thread */
const char* str) /*!< in: constant char string describing the
state */
{
ut_a(i < SRV_MAX_N_IO_THREADS);
srv_io_thread_op_info[i] = str;
}
/*********************************************************************//**
Resets the info describing an i/o thread current state. */
void
srv_reset_io_thread_op_info()
/*=========================*/
{
for (ulint i = 0; i < UT_ARR_SIZE(srv_io_thread_op_info); ++i) {
srv_io_thread_op_info[i] = "not started yet";
}
}
#ifdef UNIV_DEBUG
/*********************************************************************//**
Validates the type of a thread table slot.
@return TRUE if ok */
static
ibool
srv_thread_type_validate(
/*=====================*/
srv_thread_type type) /*!< in: thread type */
{
switch (type) {
case SRV_NONE:
break;
case SRV_WORKER:
case SRV_PURGE:
case SRV_MASTER:
return(TRUE);
}
ut_error;
return(FALSE);
}
#endif /* UNIV_DEBUG */
/*********************************************************************//**
Gets the type of a thread table slot.
@return thread type */
static
srv_thread_type
srv_slot_get_type(
/*==============*/
const srv_slot_t* slot) /*!< in: thread slot */
{
srv_thread_type type = slot->type;
ut_ad(srv_thread_type_validate(type));
return(type);
}
/*********************************************************************//**
Reserves a slot in the thread table for the current thread.
@return reserved slot */
static
srv_slot_t*
srv_reserve_slot(
/*=============*/
srv_thread_type type) /*!< in: type of the thread */
{
srv_slot_t* slot = 0;
srv_sys_mutex_enter();
ut_ad(srv_thread_type_validate(type));
switch (type) {
case SRV_MASTER:
slot = &srv_sys.sys_threads[SRV_MASTER_SLOT];
break;
case SRV_PURGE:
slot = &srv_sys.sys_threads[SRV_PURGE_SLOT];
break;
case SRV_WORKER:
/* Find an empty slot, skip the master and purge slots. */
for (slot = &srv_sys.sys_threads[SRV_WORKER_SLOTS_START];
slot->in_use;
++slot) {
ut_a(slot < &srv_sys.sys_threads[
srv_sys.n_sys_threads]);
}
break;
case SRV_NONE:
ut_error;
}
ut_a(!slot->in_use);
slot->in_use = TRUE;
slot->suspended = FALSE;
slot->type = type;
ut_ad(srv_slot_get_type(slot) == type);
my_atomic_addlint(&srv_sys.n_threads_active[type], 1);
srv_sys_mutex_exit();
return(slot);
}
/*********************************************************************//**
Suspends the calling thread to wait for the event in its thread slot.
@return the current signal count of the event. */
static
int64_t
srv_suspend_thread_low(
/*===================*/
srv_slot_t* slot) /*!< in/out: thread slot */
{
ut_ad(!srv_read_only_mode);
ut_ad(srv_sys_mutex_own());
ut_ad(slot->in_use);
srv_thread_type type = srv_slot_get_type(slot);
switch (type) {
case SRV_NONE:
ut_error;
case SRV_MASTER:
/* We have only one master thread and it
should be the first entry always. */
ut_a(srv_sys.n_threads_active[type] == 1);
break;
case SRV_PURGE:
/* We have only one purge coordinator thread
and it should be the second entry always. */
ut_a(srv_sys.n_threads_active[type] == 1);
break;
case SRV_WORKER:
ut_a(srv_n_purge_threads > 1);
break;
}
ut_a(!slot->suspended);
slot->suspended = TRUE;
if (my_atomic_addlint(&srv_sys.n_threads_active[type], -1) < 0) {
ut_error;
}
return(os_event_reset(slot->event));
}
/*********************************************************************//**
Suspends the calling thread to wait for the event in its thread slot.
@return the current signal count of the event. */
static
int64_t
srv_suspend_thread(
/*===============*/
srv_slot_t* slot) /*!< in/out: thread slot */
{
srv_sys_mutex_enter();
int64_t sig_count = srv_suspend_thread_low(slot);
srv_sys_mutex_exit();
return(sig_count);
}
/** Resume the calling thread.
@param[in,out] slot thread slot
@param[in] sig_count signal count (if wait)
@param[in] wait whether to wait for the event
@param[in] timeout_usec timeout in microseconds (0=infinite)
@return whether the wait timed out */
static
bool
srv_resume_thread(srv_slot_t* slot, int64_t sig_count = 0, bool wait = true,
ulint timeout_usec = 0)
{
bool timeout;
ut_ad(!srv_read_only_mode);
ut_ad(slot->in_use);
ut_ad(slot->suspended);
if (!wait) {
timeout = false;
} else if (timeout_usec) {
timeout = OS_SYNC_TIME_EXCEEDED == os_event_wait_time_low(
slot->event, timeout_usec, sig_count);
} else {
timeout = false;
os_event_wait_low(slot->event, sig_count);
}
srv_sys_mutex_enter();
ut_ad(slot->in_use);
ut_ad(slot->suspended);
slot->suspended = FALSE;
my_atomic_addlint(&srv_sys.n_threads_active[slot->type], 1);
srv_sys_mutex_exit();
return(timeout);
}
/** Ensure that a given number of threads of the type given are running
(or are already terminated).
@param[in] type thread type
@param[in] n number of threads that have to run */
void
srv_release_threads(enum srv_thread_type type, ulint n)
{
ulint running;
ut_ad(srv_thread_type_validate(type));
ut_ad(n > 0);
do {
running = 0;
srv_sys_mutex_enter();
for (ulint i = 0; i < srv_sys.n_sys_threads; i++) {
srv_slot_t* slot = &srv_sys.sys_threads[i];
if (!slot->in_use || srv_slot_get_type(slot) != type) {
continue;
} else if (!slot->suspended) {
if (++running >= n) {
break;
}
continue;
}
switch (type) {
case SRV_NONE:
ut_error;
case SRV_MASTER:
/* We have only one master thread and it
should be the first entry always. */
ut_a(n == 1);
ut_a(i == SRV_MASTER_SLOT);
ut_a(srv_sys.n_threads_active[type] == 0);
break;
case SRV_PURGE:
/* We have only one purge coordinator thread
and it should be the second entry always. */
ut_a(n == 1);
ut_a(i == SRV_PURGE_SLOT);
ut_a(srv_n_purge_threads > 0);
ut_a(srv_sys.n_threads_active[type] == 0);
break;
case SRV_WORKER:
ut_a(srv_n_purge_threads > 1);
ut_a(srv_sys.n_threads_active[type]
< srv_n_purge_threads - 1);
break;
}