1
/*****************************************************************************
3
Copyright (c) 1995, 2009, Innobase Oy. All Rights Reserved.
4
Copyright (c) 2008, 2009 Google Inc.
6
Portions of this file contain modifications contributed and copyrighted by
7
Google, Inc. Those modifications are gratefully acknowledged and are described
8
briefly in the InnoDB documentation. The contributions by Google are
9
incorporated with their permission, and subject to the conditions contained in
10
the file COPYING.Google.
12
This program is free software; you can redistribute it and/or modify it under
13
the terms of the GNU General Public License as published by the Free Software
14
Foundation; version 2 of the License.
16
This program is distributed in the hope that it will be useful, but WITHOUT
17
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
20
You should have received a copy of the GNU General Public License along with
21
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
22
Place, Suite 330, Boston, MA 02111-1307 USA
24
*****************************************************************************/
25
/***********************************************************************
27
Copyright (c) 1995, 2009, Innobase Oy. All Rights Reserved.
28
Copyright (c) 2009, Percona Inc.
30
Portions of this file contain modifications contributed and copyrighted
31
by Percona Inc.. Those modifications are
32
gratefully acknowledged and are described briefly in the InnoDB
33
documentation. The contributions by Percona Inc. are incorporated with
34
their permission, and subject to the conditions contained in the file
37
This program is free software; you can redistribute it and/or modify it
38
under the terms of the GNU General Public License as published by the
39
Free Software Foundation; version 2 of the License.
41
This program is distributed in the hope that it will be useful, but
42
WITHOUT ANY WARRANTY; without even the implied warranty of
43
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
44
Public License for more details.
46
You should have received a copy of the GNU General Public License along
47
with this program; if not, write to the Free Software Foundation, Inc.,
48
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
50
***********************************************************************/
52
/**************************************************//**
54
The database server main program
56
NOTE: SQL Server 7 uses something which the documentation
57
calls user mode scheduled threads (UMS threads). One such
58
thread is usually allocated per processor. Win32
59
documentation does not know any UMS threads, which suggests
60
that the concept is internal to SQL Server 7. It may mean that
61
SQL Server 7 does all the scheduling of threads itself, even
62
in i/o waits. We should maybe modify InnoDB to use the same
63
technique, because thread switches within NT may be too slow.
65
SQL Server 7 also mentions fibers, which are cooperatively
66
scheduled threads. They can boost performance by 5 %,
67
according to the Delaney and Soukup's book.
69
Windows 2000 will have something called thread pooling
70
(see msdn website), which we could possibly use.
72
Another possibility could be to use some very fast user space
73
thread library. This might confuse NT though.
75
Created 10/8/1995 Heikki Tuuri
76
*******************************************************/
86
#include "sync0sync.h"
91
#include "pars0pars.h"
93
#include "lock0lock.h"
94
#include "trx0purge.h"
95
#include "ibuf0ibuf.h"
99
#include "dict0load.h"
100
#include "dict0boot.h"
101
#include "srv0start.h"
102
#include "row0mysql.h"
103
#include "ha_prototypes.h"
106
/* This is set to TRUE if the MySQL user has set it in MySQL; currently
107
affects only FOREIGN KEY definition parsing */
108
UNIV_INTERN ibool srv_lower_case_table_names = FALSE;
110
/* The following counter is incremented whenever there is some user activity
112
UNIV_INTERN ulint srv_activity_count = 0;
114
/* The following is the maximum allowed duration of a lock wait. */
115
UNIV_INTERN ulint srv_fatal_semaphore_wait_threshold = 600;
117
/* How much data manipulation language (DML) statements need to be delayed,
118
in microseconds, in order to reduce the lagging of the purge thread. */
119
UNIV_INTERN ulint srv_dml_needed_delay = 0;
121
UNIV_INTERN ibool srv_lock_timeout_and_monitor_active = FALSE;
122
UNIV_INTERN ibool srv_error_monitor_active = FALSE;
124
UNIV_INTERN const char* srv_main_thread_op_info = "";
126
/** Prefix used by MySQL to indicate pre-5.1 table name encoding */
127
UNIV_INTERN const char srv_mysql50_table_name_prefix[9] = "#mysql50#";
129
/* Server parameters which are read from the initfile */
131
/* The following three are dir paths which are catenated before file
132
names, where the file name itself may also contain a path */
134
UNIV_INTERN char* srv_data_home = NULL;
135
#ifdef UNIV_LOG_ARCHIVE
136
UNIV_INTERN char* srv_arch_dir = NULL;
137
#endif /* UNIV_LOG_ARCHIVE */
139
/** store to its own file each table created by an user; data
140
dictionary tables are in the system tablespace 0 */
141
UNIV_INTERN my_bool srv_file_per_table;
142
/** The file format to use on new *.ibd files. */
143
UNIV_INTERN ulint srv_file_format = 0;
144
/** Whether to check file format during startup. A value of
145
DICT_TF_FORMAT_MAX + 1 means no checking ie. FALSE. The default is to
146
set it to the highest format we support. */
147
UNIV_INTERN ulint srv_check_file_format_at_startup = DICT_TF_FORMAT_MAX;
149
#if DICT_TF_FORMAT_51
150
# error "DICT_TF_FORMAT_51 must be 0!"
152
/** Place locks to records only i.e. do not use next-key locking except
153
on duplicate key checking and foreign key checking */
154
UNIV_INTERN ibool srv_locks_unsafe_for_binlog = FALSE;
156
UNIV_INTERN ulint srv_n_data_files = 0;
157
UNIV_INTERN char** srv_data_file_names = NULL;
158
/* size in database pages */
159
UNIV_INTERN ulint* srv_data_file_sizes = NULL;
161
/* if TRUE, then we auto-extend the last data file */
162
UNIV_INTERN ibool srv_auto_extend_last_data_file = FALSE;
163
/* if != 0, this tells the max size auto-extending may increase the
164
last data file size */
165
UNIV_INTERN ulint srv_last_file_size_max = 0;
166
/* If the last data file is auto-extended, we add this
167
many pages to it at a time */
168
UNIV_INTERN unsigned int srv_auto_extend_increment = 8;
169
UNIV_INTERN ulint* srv_data_file_is_raw_partition = NULL;
171
/* If the following is TRUE we do not allow inserts etc. This protects
172
the user from forgetting the 'newraw' keyword to my.cnf */
174
UNIV_INTERN ibool srv_created_new_raw = FALSE;
176
UNIV_INTERN char** srv_log_group_home_dirs = NULL;
178
UNIV_INTERN ulint srv_n_log_groups = ULINT_MAX;
179
UNIV_INTERN ulint srv_n_log_files = ULINT_MAX;
180
/* size in database pages */
181
UNIV_INTERN ulint srv_log_file_size = ULINT_MAX;
182
/* size in database pages */
183
UNIV_INTERN ulint srv_log_buffer_size = ULINT_MAX;
184
UNIV_INTERN ulong srv_flush_log_at_trx_commit = 1;
186
/* Try to flush dirty pages so as to avoid IO bursts at
188
UNIV_INTERN bool srv_adaptive_flushing = TRUE;
190
/* The sort order table of the MySQL latin1_swedish_ci character set
192
#if defined(BUILD_DRIZZLE)
193
UNIV_INTERN const byte srv_latin1_ordering[256] /* The sort order table of the latin1
194
character set. The following table is
195
the MySQL order as of Feb 10th, 2002 */
197
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
198
, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
199
, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17
200
, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
201
, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27
202
, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F
203
, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37
204
, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
205
, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
206
, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F
207
, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57
208
, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F
209
, 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
210
, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F
211
, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57
212
, 0x58, 0x59, 0x5A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F
213
, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87
214
, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F
215
, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97
216
, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F
217
, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7
218
, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF
219
, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7
220
, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF
221
, 0x41, 0x41, 0x41, 0x41, 0x5C, 0x5B, 0x5C, 0x43
222
, 0x45, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x49
223
, 0x44, 0x4E, 0x4F, 0x4F, 0x4F, 0x4F, 0x5D, 0xD7
224
, 0xD8, 0x55, 0x55, 0x55, 0x59, 0x59, 0xDE, 0xDF
225
, 0x41, 0x41, 0x41, 0x41, 0x5C, 0x5B, 0x5C, 0x43
226
, 0x45, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x49
227
, 0x44, 0x4E, 0x4F, 0x4F, 0x4F, 0x4F, 0x5D, 0xF7
228
, 0xD8, 0x55, 0x55, 0x55, 0x59, 0x59, 0xDE, 0xFF
231
UNIV_INTERN const byte* srv_latin1_ordering;
232
#endif /* BUILD_DRIZZLE */
235
/* use os/external memory allocator */
236
UNIV_INTERN my_bool srv_use_sys_malloc = TRUE;
237
/* requested size in kilobytes */
238
UNIV_INTERN ulint srv_buf_pool_size = ULINT_MAX;
239
/* previously requested size */
240
UNIV_INTERN ulint srv_buf_pool_old_size;
241
/* current size in kilobytes */
242
UNIV_INTERN ulint srv_buf_pool_curr_size = 0;
244
UNIV_INTERN ulint srv_mem_pool_size = ULINT_MAX;
245
UNIV_INTERN ulint srv_lock_table_size = ULINT_MAX;
247
/* This parameter is deprecated. Use srv_n_io_[read|write]_threads
249
UNIV_INTERN ulint srv_n_file_io_threads = ULINT_MAX;
250
UNIV_INTERN ulint srv_n_read_io_threads = ULINT_MAX;
251
UNIV_INTERN ulint srv_n_write_io_threads = ULINT_MAX;
253
/* User settable value of the number of pages that must be present
254
in the buffer cache and accessed sequentially for InnoDB to trigger a
255
readahead request. */
256
UNIV_INTERN ulong srv_read_ahead_threshold = 56;
258
#ifdef UNIV_LOG_ARCHIVE
259
UNIV_INTERN ibool srv_log_archive_on = FALSE;
260
UNIV_INTERN ibool srv_archive_recovery = 0;
261
UNIV_INTERN ib_uint64_t srv_archive_recovery_limit_lsn;
262
#endif /* UNIV_LOG_ARCHIVE */
264
/* This parameter is used to throttle the number of insert buffers that are
265
merged in a batch. By increasing this parameter on a faster disk you can
266
possibly reduce the number of I/O operations performed to complete the
267
merge operation. The value of this parameter is used as is by the
268
background loop when the system is idle (low load), on a busy system
269
the parameter is scaled down by a factor of 4, this is to avoid putting
270
a heavier load on the I/O sub system. */
272
UNIV_INTERN ulong srv_insert_buffer_batch_size = 20;
274
UNIV_INTERN char* srv_file_flush_method_str = NULL;
275
UNIV_INTERN ulint srv_unix_file_flush_method = SRV_UNIX_FSYNC;
276
UNIV_INTERN ulint srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;
278
UNIV_INTERN ulint srv_max_n_open_files = 300;
280
/* Number of IO operations per second the server can do */
281
UNIV_INTERN ulong srv_io_capacity = 200;
283
/* The InnoDB main thread tries to keep the ratio of modified pages
284
in the buffer pool to all database pages in the buffer pool smaller than
285
the following number. But it is not guaranteed that the value stays below
286
that during a time of heavy update/insert activity. */
288
UNIV_INTERN ulong srv_max_buf_pool_modified_pct = 75;
290
/* variable counts amount of data read in total (in bytes) */
291
UNIV_INTERN ulint srv_data_read = 0;
293
/* here we count the amount of data written in total (in bytes) */
294
UNIV_INTERN ulint srv_data_written = 0;
296
/* the number of the log write requests done */
297
UNIV_INTERN ulint srv_log_write_requests = 0;
299
/* the number of physical writes to the log performed */
300
UNIV_INTERN ulint srv_log_writes = 0;
302
/* amount of data written to the log files in bytes */
303
UNIV_INTERN ulint srv_os_log_written = 0;
305
/* amount of writes being done to the log files */
306
UNIV_INTERN ulint srv_os_log_pending_writes = 0;
308
/* we increase this counter, when there we don't have enough space in the
309
log buffer and have to flush it */
310
UNIV_INTERN ulint srv_log_waits = 0;
312
/* this variable counts the amount of times, when the doublewrite buffer
314
UNIV_INTERN ulint srv_dblwr_writes = 0;
316
/* here we store the number of pages that have been flushed to the
317
doublewrite buffer */
318
UNIV_INTERN ulint srv_dblwr_pages_written = 0;
320
/* in this variable we store the number of write requests issued */
321
UNIV_INTERN ulint srv_buf_pool_write_requests = 0;
323
/* here we store the number of times when we had to wait for a free page
324
in the buffer pool. It happens when the buffer pool is full and we need
325
to make a flush, in order to be able to read or create a page. */
326
UNIV_INTERN ulint srv_buf_pool_wait_free = 0;
328
/* variable to count the number of pages that were written from buffer
330
UNIV_INTERN ulint srv_buf_pool_flushed = 0;
332
/** Number of buffer pool reads that led to the
333
reading of a disk page */
334
UNIV_INTERN ulint srv_buf_pool_reads = 0;
336
/** Number of sequential read-aheads */
337
UNIV_INTERN ulint srv_read_ahead_seq = 0;
339
/** Number of random read-aheads */
340
UNIV_INTERN ulint srv_read_ahead_rnd = 0;
342
/* structure to pass status variables to MySQL */
343
UNIV_INTERN export_struc export_vars;
345
/* If the following is != 0 we do not allow inserts etc. This protects
346
the user from forgetting the innodb_force_recovery keyword to my.cnf */
348
UNIV_INTERN ulint srv_force_recovery = 0;
349
/*-----------------------*/
350
/* We are prepared for a situation that we have this many threads waiting for
351
a semaphore inside InnoDB. innobase_start_or_create_for_mysql() sets the
354
UNIV_INTERN ulint srv_max_n_threads = 0;
356
/* The following controls how many threads we let inside InnoDB concurrently:
357
threads waiting for locks are not counted into the number because otherwise
358
we could get a deadlock. MySQL creates a thread for each user session, and
359
semaphore contention and convoy problems can occur withput this restriction.
360
Value 10 should be good if there are less than 4 processors + 4 disks in the
361
computer. Bigger computers need bigger values. Value 0 will disable the
362
concurrency check. */
364
UNIV_INTERN ulong srv_thread_concurrency = 0;
366
/* this mutex protects srv_conc data structures */
367
UNIV_INTERN os_fast_mutex_t srv_conc_mutex;
368
/* number of transactions that have declared_to_be_inside_innodb set.
369
It used to be a non-error for this value to drop below zero temporarily.
370
This is no longer true. We'll, however, keep the lint datatype to add
371
assertions to catch any corner cases that we may have missed. */
372
UNIV_INTERN lint srv_conc_n_threads = 0;
373
/* number of OS threads waiting in the FIFO for a permission to enter
375
UNIV_INTERN ulint srv_conc_n_waiting_threads = 0;
377
typedef struct srv_conc_slot_struct srv_conc_slot_t;
378
struct srv_conc_slot_struct{
379
os_event_t event; /*!< event to wait */
380
ibool reserved; /*!< TRUE if slot
382
ibool wait_ended; /*!< TRUE when another
383
thread has already set
385
thread in this slot is
387
reserved may still be
388
TRUE at that point */
389
UT_LIST_NODE_T(srv_conc_slot_t) srv_conc_queue; /*!< queue node */
392
/* queue of threads waiting to get in */
393
UNIV_INTERN UT_LIST_BASE_NODE_T(srv_conc_slot_t) srv_conc_queue;
394
/* array of wait slots */
395
UNIV_INTERN srv_conc_slot_t* srv_conc_slots;
397
/* Number of times a thread is allowed to enter InnoDB within the same
398
SQL query after it has once got the ticket at srv_conc_enter_innodb */
399
#define SRV_FREE_TICKETS_TO_ENTER srv_n_free_tickets_to_enter
400
#define SRV_THREAD_SLEEP_DELAY srv_thread_sleep_delay
401
/*-----------------------*/
402
/* If the following is set to 1 then we do not run purge and insert buffer
403
merge to completion before shutdown. If it is set to 2, do not even flush the
404
buffer pool to data files at the shutdown: we effectively 'crash'
405
InnoDB (but lose no committed transactions). */
406
UNIV_INTERN ulint srv_fast_shutdown = 0;
408
/* Generate a innodb_status.<pid> file */
409
UNIV_INTERN ibool srv_innodb_status = FALSE;
411
/* When estimating number of different key values in an index, sample
412
this many index pages */
413
UNIV_INTERN ib_uint64_t srv_stats_sample_pages = 8;
415
UNIV_INTERN ibool srv_use_doublewrite_buf = TRUE;
416
UNIV_INTERN ibool srv_use_checksums = TRUE;
418
UNIV_INTERN ulong srv_replication_delay = 0;
420
/*-------------------------------------------*/
421
UNIV_INTERN ulong srv_n_spin_wait_rounds = 30;
422
UNIV_INTERN ulong srv_n_free_tickets_to_enter = 500;
423
UNIV_INTERN ulong srv_thread_sleep_delay = 10000;
424
UNIV_INTERN ulong srv_spin_wait_delay = 6;
425
UNIV_INTERN ibool srv_priority_boost = TRUE;
428
UNIV_INTERN ibool srv_print_thread_releases = FALSE;
429
UNIV_INTERN ibool srv_print_lock_waits = FALSE;
430
UNIV_INTERN ibool srv_print_buf_io = FALSE;
431
UNIV_INTERN ibool srv_print_log_io = FALSE;
432
UNIV_INTERN ibool srv_print_latch_waits = FALSE;
433
#endif /* UNIV_DEBUG */
435
UNIV_INTERN ulint srv_n_rows_inserted = 0;
436
UNIV_INTERN ulint srv_n_rows_updated = 0;
437
UNIV_INTERN ulint srv_n_rows_deleted = 0;
438
UNIV_INTERN ulint srv_n_rows_read = 0;
440
static ulint srv_n_rows_inserted_old = 0;
441
static ulint srv_n_rows_updated_old = 0;
442
static ulint srv_n_rows_deleted_old = 0;
443
static ulint srv_n_rows_read_old = 0;
445
UNIV_INTERN ulint srv_n_lock_wait_count = 0;
446
UNIV_INTERN ulint srv_n_lock_wait_current_count = 0;
447
UNIV_INTERN ib_int64_t srv_n_lock_wait_time = 0;
448
UNIV_INTERN ulint srv_n_lock_max_wait_time = 0;
452
Set the following to 0 if you want InnoDB to write messages on
453
stderr on startup/shutdown
455
UNIV_INTERN ibool srv_print_verbose_log = TRUE;
456
UNIV_INTERN ibool srv_print_innodb_monitor = FALSE;
457
UNIV_INTERN ibool srv_print_innodb_lock_monitor = FALSE;
458
UNIV_INTERN ibool srv_print_innodb_tablespace_monitor = FALSE;
459
UNIV_INTERN ibool srv_print_innodb_table_monitor = FALSE;
461
/* Array of English strings describing the current state of an
462
i/o handler thread */
464
UNIV_INTERN const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
465
UNIV_INTERN const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
467
UNIV_INTERN time_t srv_last_monitor_time;
469
UNIV_INTERN mutex_t srv_innodb_monitor_mutex;
471
/* Mutex for locking srv_monitor_file */
472
UNIV_INTERN mutex_t srv_monitor_file_mutex;
473
/* Temporary file for innodb monitor output */
474
UNIV_INTERN FILE* srv_monitor_file;
475
/* Mutex for locking srv_dict_tmpfile.
476
This mutex has a very high rank; threads reserving it should not
477
be holding any InnoDB latches. */
478
UNIV_INTERN mutex_t srv_dict_tmpfile_mutex;
479
/* Temporary file for output from the data dictionary */
480
UNIV_INTERN FILE* srv_dict_tmpfile;
481
/* Mutex for locking srv_misc_tmpfile.
482
This mutex has a very low rank; threads reserving it should not
483
acquire any further latches or sleep before releasing this one. */
484
UNIV_INTERN mutex_t srv_misc_tmpfile_mutex;
485
/* Temporary file for miscellanous diagnostic output */
486
UNIV_INTERN FILE* srv_misc_tmpfile;
488
UNIV_INTERN ulint srv_main_thread_process_no = 0;
489
UNIV_INTERN ulint srv_main_thread_id = 0;
491
/* The following count work done by srv_master_thread. */
493
/* Iterations by the 'once per second' loop. */
494
static ulint srv_main_1_second_loops = 0;
495
/* Calls to sleep by the 'once per second' loop. */
496
static ulint srv_main_sleeps = 0;
497
/* Iterations by the 'once per 10 seconds' loop. */
498
static ulint srv_main_10_second_loops = 0;
499
/* Iterations of the loop bounded by the 'background_loop' label. */
500
static ulint srv_main_background_loops = 0;
501
/* Iterations of the loop bounded by the 'flush_loop' label. */
502
static ulint srv_main_flush_loops = 0;
503
/* Log writes involving flush. */
504
static ulint srv_log_writes_and_flush = 0;
505
/* Log writes not including flush. */
506
static ulint srv_log_buffer_writes = 0;
508
/* This is only ever touched by the master thread. It records the
509
time when the last flush of log file has happened. The master
510
thread ensures that we flush the log files at least once per
512
static time_t srv_last_log_flush_time;
514
/* The master thread performs various tasks based on the current
515
state of IO activity and the level of IO utilization is past
516
intervals. Following macros define thresholds for these conditions. */
517
#define SRV_PEND_IO_THRESHOLD (PCT_IO(3))
518
#define SRV_RECENT_IO_ACTIVITY (PCT_IO(5))
519
#define SRV_PAST_IO_ACTIVITY (PCT_IO(200))
522
IMPLEMENTATION OF THE SERVER MAIN PROGRAM
523
=========================================
525
There is the following analogue between this database
526
server and an operating system kernel:
528
DB concept equivalent OS concept
529
---------- ---------------------
530
transaction -- process;
532
query thread -- thread;
537
the rollback state -- kill signal delivered to a process;
541
query thread execution:
542
(a) without kernel mutex
543
reserved -- process executing in user mode;
544
(b) with kernel mutex reserved
545
-- process executing in kernel mode;
547
The server is controlled by a master thread which runs at
548
a priority higher than normal, that is, higher than user threads.
549
It sleeps most of the time, and wakes up, say, every 300 milliseconds,
550
to check whether there is anything happening in the server which
551
requires intervention of the master thread. Such situations may be,
552
for example, when flushing of dirty blocks is needed in the buffer
553
pool or old version of database rows have to be cleaned away.
555
The threads which we call user threads serve the queries of
556
the clients and input from the console of the server.
557
They run at normal priority. The server may have several
558
communications endpoints. A dedicated set of user threads waits
559
at each of these endpoints ready to receive a client request.
560
Each request is taken by a single user thread, which then starts
561
processing and, when the result is ready, sends it to the client
562
and returns to wait at the same endpoint the thread started from.
564
So, we do not have dedicated communication threads listening at
565
the endpoints and dealing the jobs to dedicated worker threads.
566
Our architecture saves one thread swithch per request, compared
567
to the solution with dedicated communication threads
568
which amounts to 15 microseconds on 100 MHz Pentium
569
running NT. If the client
570
is communicating over a network, this saving is negligible, but
571
if the client resides in the same machine, maybe in an SMP machine
572
on a different processor from the server thread, the saving
573
can be important as the threads can communicate over shared
574
memory with an overhead of a few microseconds.
576
We may later implement a dedicated communication thread solution
577
for those endpoints which communicate over a network.
579
Our solution with user threads has two problems: for each endpoint
580
there has to be a number of listening threads. If there are many
581
communication endpoints, it may be difficult to set the right number
582
of concurrent threads in the system, as many of the threads
583
may always be waiting at less busy endpoints. Another problem
584
is queuing of the messages, as the server internally does not
585
offer any queue for jobs.
587
Another group of user threads is intended for splitting the
588
queries and processing them in parallel. Let us call these
589
parallel communication threads. These threads are waiting for
590
parallelized tasks, suspended on event semaphores.
592
A single user thread waits for input from the console,
593
like a command to shut the database.
595
Utility threads are a different group of threads which takes
596
care of the buffer pool flushing and other, mainly background
597
operations, in the server.
598
Some of these utility threads always run at a lower than normal
599
priority, so that they are always in background. Some of them
600
may dynamically boost their priority by the pri_adjust function,
601
even to higher than normal priority, if their task becomes urgent.
602
The running of utilities is controlled by high- and low-water marks
603
of urgency. The urgency may be measured by the number of dirty blocks
604
in the buffer pool, in the case of the flush thread, for example.
605
When the high-water mark is exceeded, an utility starts running, until
606
the urgency drops under the low-water mark. Then the utility thread
607
suspend itself to wait for an event. The master thread is
608
responsible of signaling this event when the utility thread is
611
For each individual type of utility, some threads always remain
612
at lower than normal priority. This is because pri_adjust is implemented
613
so that the threads at normal or higher priority control their
614
share of running time by calling sleep. Thus, if the load of the
615
system sudenly drops, these threads cannot necessarily utilize
616
the system fully. The background priority threads make up for this,
617
starting to run when the load drops.
619
When there is no activity in the system, also the master thread
620
suspends itself to wait for an event making
621
the server totally silent. The responsibility to signal this
622
event is on the user thread which again receives a message
625
There is still one complication in our server design. If a
626
background utility thread obtains a resource (e.g., mutex) needed by a user
627
thread, and there is also some other user activity in the system,
628
the user thread may have to wait indefinitely long for the
629
resource, as the OS does not schedule a background thread if
630
there is some other runnable user thread. This problem is called
631
priority inversion in real-time programming.
633
One solution to the priority inversion problem would be to
634
keep record of which thread owns which resource and
635
in the above case boost the priority of the background thread
636
so that it will be scheduled and it can release the resource.
637
This solution is called priority inheritance in real-time programming.
638
A drawback of this solution is that the overhead of acquiring a mutex
639
increases slightly, maybe 0.2 microseconds on a 100 MHz Pentium, because
640
the thread has to call os_thread_get_curr_id.
641
This may be compared to 0.5 microsecond overhead for a mutex lock-unlock
642
pair. Note that the thread
643
cannot store the information in the resource, say mutex, itself,
644
because competing threads could wipe out the information if it is
645
stored before acquiring the mutex, and if it stored afterwards,
646
the information is outdated for the time of one machine instruction,
647
at least. (To be precise, the information could be stored to
648
lock_word in mutex if the machine supports atomic swap.)
650
The above solution with priority inheritance may become actual in the
651
future, but at the moment we plan to implement a more coarse solution,
652
which could be called a global priority inheritance. If a thread
653
has to wait for a long time, say 300 milliseconds, for a resource,
654
we just guess that it may be waiting for a resource owned by a background
655
thread, and boost the the priority of all runnable background threads
656
to the normal level. The background threads then themselves adjust
657
their fixed priority back to background after releasing all resources
658
they had (or, at some fixed points in their program code).
660
What is the performance of the global priority inheritance solution?
661
We may weigh the length of the wait time 300 milliseconds, during
662
which the system processes some other thread
663
to the cost of boosting the priority of each runnable background
664
thread, rescheduling it, and lowering the priority again.
665
On 100 MHz Pentium + NT this overhead may be of the order 100
666
microseconds per thread. So, if the number of runnable background
667
threads is not very big, say < 100, the cost is tolerable.
668
Utility threads probably will access resources used by
669
user threads not very often, so collisions of user threads
670
to preempted utility threads should not happen very often.
672
The thread table contains
673
information of the current status of each thread existing in the system,
674
and also the event semaphores used in suspending the master thread
675
and utility and parallel communication threads when they have nothing to do.
676
The thread table can be seen as an analogue to the process table
677
in a traditional Unix implementation.
679
The thread table is also used in the global priority inheritance
680
scheme. This brings in one additional complication: threads accessing
681
the thread table must have at least normal fixed priority,
682
because the priority inheritance solution does not work if a background
683
thread is preempted while possessing the mutex protecting the thread table.
684
So, if a thread accesses the thread table, its priority has to be
685
boosted at least to normal. This priority requirement can be seen similar to
686
the privileged mode used when processing the kernel calls in traditional
689
/* Thread slot in the thread table */
690
struct srv_slot_struct{
691
os_thread_id_t id; /*!< thread id */
692
os_thread_t handle; /*!< thread handle */
693
unsigned type:3; /*!< thread type: user, utility etc. */
694
unsigned in_use:1; /*!< TRUE if this slot is in use */
695
unsigned suspended:1; /*!< TRUE if the thread is waiting
696
for the event of this slot */
697
ib_time_t suspend_time; /*!< time when the thread was
699
os_event_t event; /*!< event used in suspending the
700
thread when it has nothing to do */
701
que_thr_t* thr; /*!< suspended query thread (only
702
used for MySQL threads) */
705
/* Table for MySQL threads where they will be suspended to wait for locks */
706
UNIV_INTERN srv_slot_t* srv_mysql_table = NULL;
708
UNIV_INTERN os_event_t srv_lock_timeout_thread_event;
710
UNIV_INTERN srv_sys_t* srv_sys = NULL;
712
/* padding to prevent other memory update hotspots from residing on
713
the same memory cache line */
714
UNIV_INTERN byte srv_pad1[64];
715
/* mutex protecting the server, trx structs, query threads, and lock table */
716
UNIV_INTERN mutex_t* kernel_mutex_temp;
717
/* padding to prevent other memory update hotspots from residing on
718
the same memory cache line */
719
UNIV_INTERN byte srv_pad2[64];
722
/* The following three values measure the urgency of the jobs of
723
buffer, version, and insert threads. They may vary from 0 - 1000.
724
The server mutex protects all these variables. The low-water values
725
tell that the server can acquiesce the utility when the value
726
drops below this low-water mark. */
728
static ulint srv_meter[SRV_MASTER + 1];
729
static ulint srv_meter_low_water[SRV_MASTER + 1];
730
static ulint srv_meter_high_water[SRV_MASTER + 1];
731
static ulint srv_meter_high_water2[SRV_MASTER + 1];
732
static ulint srv_meter_foreground[SRV_MASTER + 1];
735
/* The following values give info about the activity going on in
736
the database. They are protected by the server mutex. The arrays
737
are indexed by the type of the thread. */
739
UNIV_INTERN ulint srv_n_threads_active[SRV_MASTER + 1];
740
UNIV_INTERN ulint srv_n_threads[SRV_MASTER + 1];
742
/***********************************************************************
743
Prints counters for work done by srv_master_thread. */
746
srv_print_master_thread_info(
747
/*=========================*/
748
FILE *file) /* in: output stream */
750
fprintf(file, "srv_master_thread loops: %lu 1_second, %lu sleeps, "
751
"%lu 10_second, %lu background, %lu flush\n",
752
srv_main_1_second_loops, srv_main_sleeps,
753
srv_main_10_second_loops, srv_main_background_loops,
754
srv_main_flush_loops);
755
fprintf(file, "srv_master_thread log flush and writes: %lu "
756
" log writes only: %lu\n",
757
srv_log_writes_and_flush, srv_log_buffer_writes);
760
/*********************************************************************//**
761
Sets the info describing an i/o thread current state. */
764
srv_set_io_thread_op_info(
765
/*======================*/
766
ulint i, /*!< in: the 'segment' of the i/o thread */
767
const char* str) /*!< in: constant char string describing the
770
ut_a(i < SRV_MAX_N_IO_THREADS);
772
srv_io_thread_op_info[i] = str;
775
/*********************************************************************//**
776
Accessor function to get pointer to n'th slot in the server thread
778
@return pointer to the slot */
781
srv_table_get_nth_slot(
782
/*===================*/
783
ulint index) /*!< in: index of the slot */
785
ut_a(index < OS_THREAD_MAX_N);
787
return(srv_sys->threads + index);
790
/*********************************************************************//**
791
Gets the number of threads in the system.
792
@return sum of srv_n_threads[] */
795
srv_get_n_threads(void)
796
/*===================*/
801
mutex_enter(&kernel_mutex);
803
for (i = SRV_COM; i < SRV_MASTER + 1; i++) {
805
n_threads += srv_n_threads[i];
808
mutex_exit(&kernel_mutex);
813
/*********************************************************************//**
814
Reserves a slot in the thread table for the current thread. Also creates the
815
thread local storage struct for the current thread. NOTE! The server mutex
816
has to be reserved by the caller!
817
@return reserved slot index */
820
srv_table_reserve_slot(
821
/*===================*/
822
enum srv_thread_type type) /*!< in: type of the thread */
828
ut_a(type <= SRV_MASTER);
831
slot = srv_table_get_nth_slot(i);
833
while (slot->in_use) {
835
slot = srv_table_get_nth_slot(i);
838
ut_a(slot->in_use == FALSE);
841
slot->suspended = FALSE;
843
slot->id = os_thread_get_curr_id();
844
slot->handle = os_thread_get_curr();
848
thr_local_set_slot_no(os_thread_get_curr_id(), i);
853
/*********************************************************************//**
854
Suspends the calling thread to wait for the event in its thread slot.
855
NOTE! The server mutex has to be reserved by the caller!
856
@return event for the calling thread to wait */
859
srv_suspend_thread(void)
860
/*====================*/
865
enum srv_thread_type type;
867
ut_ad(mutex_own(&kernel_mutex));
869
slot_no = thr_local_get_slot_no(os_thread_get_curr_id());
871
if (srv_print_thread_releases) {
873
"Suspending thread %lu to slot %lu\n",
874
(ulong) os_thread_get_curr_id(), (ulong) slot_no);
877
slot = srv_table_get_nth_slot(slot_no);
881
ut_ad(type >= SRV_WORKER);
882
ut_ad(type <= SRV_MASTER);
886
slot->suspended = TRUE;
888
ut_ad(srv_n_threads_active[type] > 0);
890
srv_n_threads_active[type]--;
892
os_event_reset(event);
897
/*********************************************************************//**
898
Releases threads of the type given from suspension in the thread table.
899
NOTE! The server mutex has to be reserved by the caller!
900
@return number of threads released: this may be less than n if not
901
enough threads were suspended at the moment */
906
enum srv_thread_type type, /*!< in: thread type */
907
ulint n) /*!< in: number of threads to release */
913
ut_ad(type >= SRV_WORKER);
914
ut_ad(type <= SRV_MASTER);
916
ut_ad(mutex_own(&kernel_mutex));
918
for (i = 0; i < OS_THREAD_MAX_N; i++) {
920
slot = srv_table_get_nth_slot(i);
922
if (slot->in_use && slot->type == type && slot->suspended) {
924
slot->suspended = FALSE;
926
srv_n_threads_active[type]++;
928
os_event_set(slot->event);
930
if (srv_print_thread_releases) {
932
"Releasing thread %lu type %lu"
934
(ulong) slot->id, (ulong) type,
949
/*********************************************************************//**
950
Returns the calling thread type.
951
@return SRV_COM, ... */
954
srv_get_thread_type(void)
955
/*=====================*/
959
enum srv_thread_type type;
961
mutex_enter(&kernel_mutex);
963
slot_no = thr_local_get_slot_no(os_thread_get_curr_id());
965
slot = srv_table_get_nth_slot(slot_no);
969
ut_ad(type >= SRV_WORKER);
970
ut_ad(type <= SRV_MASTER);
972
mutex_exit(&kernel_mutex);
977
/*********************************************************************//**
978
Initializes the server. */
984
srv_conc_slot_t* conc_slot;
988
srv_sys = mem_alloc(sizeof(srv_sys_t));
990
kernel_mutex_temp = mem_alloc(sizeof(mutex_t));
991
mutex_create(&kernel_mutex, SYNC_KERNEL);
993
mutex_create(&srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
995
srv_sys->threads = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));
997
for (i = 0; i < OS_THREAD_MAX_N; i++) {
998
slot = srv_table_get_nth_slot(i);
999
slot->in_use = FALSE;
1000
slot->type=0; /* Avoid purify errors */
1001
slot->event = os_event_create(NULL);
1005
srv_mysql_table = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));
1007
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1008
slot = srv_mysql_table + i;
1009
slot->in_use = FALSE;
1011
slot->event = os_event_create(NULL);
1015
srv_lock_timeout_thread_event = os_event_create(NULL);
1017
for (i = 0; i < SRV_MASTER + 1; i++) {
1018
srv_n_threads_active[i] = 0;
1019
srv_n_threads[i] = 0;
1022
srv_meter_low_water[i] = 50;
1023
srv_meter_high_water[i] = 100;
1024
srv_meter_high_water2[i] = 200;
1025
srv_meter_foreground[i] = 250;
1029
UT_LIST_INIT(srv_sys->tasks);
1031
/* Create dummy indexes for infimum and supremum records */
1035
/* Init the server concurrency restriction data structures */
1037
os_fast_mutex_init(&srv_conc_mutex);
1039
UT_LIST_INIT(srv_conc_queue);
1041
srv_conc_slots = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_conc_slot_t));
1043
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1044
conc_slot = srv_conc_slots + i;
1045
conc_slot->reserved = FALSE;
1046
conc_slot->event = os_event_create(NULL);
1047
ut_a(conc_slot->event);
1050
/* Initialize some INFORMATION SCHEMA internal structures */
1051
trx_i_s_cache_init(trx_i_s_cache);
1054
/*********************************************************************//**
1055
Frees the OS fast mutex created in srv_init(). */
1061
os_fast_mutex_free(&srv_conc_mutex);
1064
/*********************************************************************//**
1065
Initializes the synchronization primitives, memory system, and the thread
1069
srv_general_init(void)
1070
/*==================*/
1075
mem_init(srv_mem_pool_size);
1079
/*======================= InnoDB Server FIFO queue =======================*/
1081
/* Maximum allowable purge history length. <=0 means 'infinite'. */
1082
UNIV_INTERN ulong srv_max_purge_lag = 0;
1084
/*********************************************************************//**
1085
Puts an OS thread to wait if there are too many concurrent threads
1086
(>= srv_thread_concurrency) inside InnoDB. The threads wait in a FIFO queue. */
1089
srv_conc_enter_innodb(
1090
/*==================*/
1091
trx_t* trx) /*!< in: transaction object associated with the
1094
ibool has_slept = FALSE;
1095
srv_conc_slot_t* slot = NULL;
1098
if (trx->mysql_thd != NULL
1099
&& thd_is_replication_slave_thread(trx->mysql_thd)) {
1101
UT_WAIT_FOR(srv_conc_n_threads
1102
< (lint)srv_thread_concurrency,
1103
srv_replication_delay * 1000);
1108
/* If trx has 'free tickets' to enter the engine left, then use one
1111
if (trx->n_tickets_to_enter_innodb > 0) {
1112
trx->n_tickets_to_enter_innodb--;
1117
os_fast_mutex_lock(&srv_conc_mutex);
1119
if (trx->declared_to_be_inside_innodb) {
1120
ut_print_timestamp(stderr);
1121
fputs(" InnoDB: Error: trying to declare trx"
1122
" to enter InnoDB, but\n"
1123
"InnoDB: it already is declared.\n", stderr);
1124
trx_print(stderr, trx, 0);
1126
os_fast_mutex_unlock(&srv_conc_mutex);
1131
ut_ad(srv_conc_n_threads >= 0);
1133
if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
1135
srv_conc_n_threads++;
1136
trx->declared_to_be_inside_innodb = TRUE;
1137
trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
1139
os_fast_mutex_unlock(&srv_conc_mutex);
1144
/* If the transaction is not holding resources, let it sleep
1145
for SRV_THREAD_SLEEP_DELAY microseconds, and try again then */
1147
if (!has_slept && !trx->has_search_latch
1148
&& NULL == UT_LIST_GET_FIRST(trx->trx_locks)) {
1150
has_slept = TRUE; /* We let it sleep only once to avoid
1153
srv_conc_n_waiting_threads++;
1155
os_fast_mutex_unlock(&srv_conc_mutex);
1157
trx->op_info = "sleeping before joining InnoDB queue";
1159
/* Peter Zaitsev suggested that we take the sleep away
1160
altogether. But the sleep may be good in pathological
1161
situations of lots of thread switches. Simply put some
1162
threads aside for a while to reduce the number of thread
1164
if (SRV_THREAD_SLEEP_DELAY > 0) {
1165
os_thread_sleep(SRV_THREAD_SLEEP_DELAY);
1170
os_fast_mutex_lock(&srv_conc_mutex);
1172
srv_conc_n_waiting_threads--;
1177
/* Too many threads inside: put the current thread to a queue */
1179
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1180
slot = srv_conc_slots + i;
1182
if (!slot->reserved) {
1188
if (i == OS_THREAD_MAX_N) {
1189
/* Could not find a free wait slot, we must let the
1192
srv_conc_n_threads++;
1193
trx->declared_to_be_inside_innodb = TRUE;
1194
trx->n_tickets_to_enter_innodb = 0;
1196
os_fast_mutex_unlock(&srv_conc_mutex);
1201
/* Release possible search system latch this thread has */
1202
if (trx->has_search_latch) {
1203
trx_search_latch_release_if_reserved(trx);
1206
/* Add to the queue */
1207
slot->reserved = TRUE;
1208
slot->wait_ended = FALSE;
1210
UT_LIST_ADD_LAST(srv_conc_queue, srv_conc_queue, slot);
1212
os_event_reset(slot->event);
1214
srv_conc_n_waiting_threads++;
1216
os_fast_mutex_unlock(&srv_conc_mutex);
1218
/* Go to wait for the event; when a thread leaves InnoDB it will
1219
release this thread */
1221
trx->op_info = "waiting in InnoDB queue";
1223
os_event_wait(slot->event);
1227
os_fast_mutex_lock(&srv_conc_mutex);
1229
srv_conc_n_waiting_threads--;
1231
/* NOTE that the thread which released this thread already
1232
incremented the thread counter on behalf of this thread */
1234
slot->reserved = FALSE;
1236
UT_LIST_REMOVE(srv_conc_queue, srv_conc_queue, slot);
1238
trx->declared_to_be_inside_innodb = TRUE;
1239
trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
1241
os_fast_mutex_unlock(&srv_conc_mutex);
1244
/*********************************************************************//**
1245
This lets a thread enter InnoDB regardless of the number of threads inside
1246
InnoDB. This must be called when a thread ends a lock wait. */
1249
srv_conc_force_enter_innodb(
1250
/*========================*/
1251
trx_t* trx) /*!< in: transaction object associated with the
1254
if (UNIV_LIKELY(!srv_thread_concurrency)) {
1259
ut_ad(srv_conc_n_threads >= 0);
1261
os_fast_mutex_lock(&srv_conc_mutex);
1263
srv_conc_n_threads++;
1264
trx->declared_to_be_inside_innodb = TRUE;
1265
trx->n_tickets_to_enter_innodb = 1;
1267
os_fast_mutex_unlock(&srv_conc_mutex);
1270
/*********************************************************************//**
1271
This must be called when a thread exits InnoDB in a lock wait or at the
1272
end of an SQL statement. */
1275
srv_conc_force_exit_innodb(
1276
/*=======================*/
1277
trx_t* trx) /*!< in: transaction object associated with the
1280
srv_conc_slot_t* slot = NULL;
1282
if (trx->mysql_thd != NULL
1283
&& thd_is_replication_slave_thread(trx->mysql_thd)) {
1288
if (trx->declared_to_be_inside_innodb == FALSE) {
1293
os_fast_mutex_lock(&srv_conc_mutex);
1295
ut_ad(srv_conc_n_threads > 0);
1296
srv_conc_n_threads--;
1297
trx->declared_to_be_inside_innodb = FALSE;
1298
trx->n_tickets_to_enter_innodb = 0;
1300
if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
1301
/* Look for a slot where a thread is waiting and no other
1302
thread has yet released the thread */
1304
slot = UT_LIST_GET_FIRST(srv_conc_queue);
1306
while (slot && slot->wait_ended == TRUE) {
1307
slot = UT_LIST_GET_NEXT(srv_conc_queue, slot);
1311
slot->wait_ended = TRUE;
1313
/* We increment the count on behalf of the released
1316
srv_conc_n_threads++;
1320
os_fast_mutex_unlock(&srv_conc_mutex);
1323
os_event_set(slot->event);
1327
/*********************************************************************//**
1328
This must be called when a thread exits InnoDB. */
1331
srv_conc_exit_innodb(
1332
/*=================*/
1333
trx_t* trx) /*!< in: transaction object associated with the
1336
if (trx->n_tickets_to_enter_innodb > 0) {
1337
/* We will pretend the thread is still inside InnoDB though it
1338
now leaves the InnoDB engine. In this way we save
1339
a lot of semaphore operations. srv_conc_force_exit_innodb is
1340
used to declare the thread definitely outside InnoDB. It
1341
should be called when there is a lock wait or an SQL statement
1347
srv_conc_force_exit_innodb(trx);
1350
/*========================================================================*/
1352
/*********************************************************************//**
1353
Normalizes init parameter values to use units we use inside InnoDB.
1354
@return DB_SUCCESS or error code */
1357
srv_normalize_init_values(void)
1358
/*===========================*/
1363
n = srv_n_data_files;
1365
for (i = 0; i < n; i++) {
1366
srv_data_file_sizes[i] = srv_data_file_sizes[i]
1367
* ((1024 * 1024) / UNIV_PAGE_SIZE);
1370
srv_last_file_size_max = srv_last_file_size_max
1371
* ((1024 * 1024) / UNIV_PAGE_SIZE);
1373
srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;
1375
srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;
1377
srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
1382
/*********************************************************************//**
1383
Boots the InnoDB server.
1384
@return DB_SUCCESS or error code */
1392
/* Transform the init parameter values given by MySQL to
1393
use units we use inside InnoDB: */
1395
err = srv_normalize_init_values();
1397
if (err != DB_SUCCESS) {
1401
/* Initialize synchronization primitives, memory management, and thread
1406
/* Initialize this module */
1413
/*********************************************************************//**
1414
Reserves a slot in the thread table for the current MySQL OS thread.
1415
NOTE! The kernel mutex has to be reserved by the caller!
1416
@return reserved slot */
1419
srv_table_reserve_slot_for_mysql(void)
1420
/*==================================*/
1425
ut_ad(mutex_own(&kernel_mutex));
1428
slot = srv_mysql_table + i;
1430
while (slot->in_use) {
1433
if (i >= OS_THREAD_MAX_N) {
1435
ut_print_timestamp(stderr);
1438
" InnoDB: There appear to be %lu MySQL"
1439
" threads currently waiting\n"
1440
"InnoDB: inside InnoDB, which is the"
1441
" upper limit. Cannot continue operation.\n"
1442
"InnoDB: We intentionally generate"
1443
" a seg fault to print a stack trace\n"
1444
"InnoDB: on Linux. But first we print"
1445
" a list of waiting threads.\n", (ulong) i);
1447
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1449
slot = srv_mysql_table + i;
1452
"Slot %lu: thread id %lu, type %lu,"
1453
" in use %lu, susp %lu, time %lu\n",
1455
(ulong) os_thread_pf(slot->id),
1457
(ulong) slot->in_use,
1458
(ulong) slot->suspended,
1459
(ulong) difftime(ut_time(),
1460
slot->suspend_time));
1466
slot = srv_mysql_table + i;
1469
ut_a(slot->in_use == FALSE);
1471
slot->in_use = TRUE;
1472
slot->id = os_thread_get_curr_id();
1473
slot->handle = os_thread_get_curr();
1478
/***************************************************************//**
1479
Puts a MySQL OS thread to wait for a lock to be released. If an error
1480
occurs during the wait trx->error_state associated with thr is
1481
!= DB_SUCCESS when we return. DB_LOCK_WAIT_TIMEOUT and DB_DEADLOCK
1482
are possible errors. DB_DEADLOCK is returned if selective deadlock
1483
resolution chose this transaction as a victim. */
1486
srv_suspend_mysql_thread(
1487
/*=====================*/
1488
que_thr_t* thr) /*!< in: query thread associated with the MySQL
1495
ulint had_dict_lock;
1496
ibool was_declared_inside_innodb = FALSE;
1497
ib_int64_t start_time = 0;
1498
ib_int64_t finish_time;
1502
ulong lock_wait_timeout;
1504
ut_ad(!mutex_own(&kernel_mutex));
1506
trx = thr_get_trx(thr);
1508
os_event_set(srv_lock_timeout_thread_event);
1510
mutex_enter(&kernel_mutex);
1512
trx->error_state = DB_SUCCESS;
1514
if (thr->state == QUE_THR_RUNNING) {
1516
ut_ad(thr->is_active == TRUE);
1518
/* The lock has already been released or this transaction
1519
was chosen as a deadlock victim: no need to suspend */
1521
if (trx->was_chosen_as_deadlock_victim) {
1523
trx->error_state = DB_DEADLOCK;
1524
trx->was_chosen_as_deadlock_victim = FALSE;
1527
mutex_exit(&kernel_mutex);
1532
ut_ad(thr->is_active == FALSE);
1534
slot = srv_table_reserve_slot_for_mysql();
1536
event = slot->event;
1540
os_event_reset(event);
1542
slot->suspend_time = ut_time();
1544
if (thr->lock_state == QUE_THR_LOCK_ROW) {
1545
srv_n_lock_wait_count++;
1546
srv_n_lock_wait_current_count++;
1548
if (ut_usectime(&sec, &ms) == -1) {
1551
start_time = (ib_int64_t) sec * 1000000 + ms;
1554
/* Wake the lock timeout monitor thread, if it is suspended */
1556
os_event_set(srv_lock_timeout_thread_event);
1558
mutex_exit(&kernel_mutex);
1560
if (trx->declared_to_be_inside_innodb) {
1562
was_declared_inside_innodb = TRUE;
1564
/* We must declare this OS thread to exit InnoDB, since a
1565
possible other thread holding a lock which this thread waits
1566
for must be allowed to enter, sooner or later */
1568
srv_conc_force_exit_innodb(trx);
1571
had_dict_lock = trx->dict_operation_lock_mode;
1573
switch (had_dict_lock) {
1575
/* Release foreign key check latch */
1576
row_mysql_unfreeze_data_dictionary(trx);
1579
/* Release fast index creation latch */
1580
row_mysql_unlock_data_dictionary(trx);
1584
ut_a(trx->dict_operation_lock_mode == 0);
1586
/* Suspend this thread and wait for the event. */
1588
os_event_wait(event);
1590
/* After resuming, reacquire the data dictionary latch if
1593
switch (had_dict_lock) {
1595
row_mysql_freeze_data_dictionary(trx);
1598
row_mysql_lock_data_dictionary(trx);
1602
if (was_declared_inside_innodb) {
1604
/* Return back inside InnoDB */
1606
srv_conc_force_enter_innodb(trx);
1609
mutex_enter(&kernel_mutex);
1611
/* Release the slot for others to use */
1613
slot->in_use = FALSE;
1615
wait_time = ut_difftime(ut_time(), slot->suspend_time);
1617
if (thr->lock_state == QUE_THR_LOCK_ROW) {
1618
if (ut_usectime(&sec, &ms) == -1) {
1621
finish_time = (ib_int64_t) sec * 1000000 + ms;
1624
diff_time = (ulint) (finish_time - start_time);
1626
srv_n_lock_wait_current_count--;
1627
srv_n_lock_wait_time = srv_n_lock_wait_time + diff_time;
1628
if (diff_time > srv_n_lock_max_wait_time &&
1629
/* only update the variable if we successfully
1630
retrieved the start and finish times. See Bug#36819. */
1631
start_time != -1 && finish_time != -1) {
1632
srv_n_lock_max_wait_time = diff_time;
1636
if (trx->was_chosen_as_deadlock_victim) {
1638
trx->error_state = DB_DEADLOCK;
1639
trx->was_chosen_as_deadlock_victim = FALSE;
1642
mutex_exit(&kernel_mutex);
1644
/* InnoDB system transactions (such as the purge, and
1645
incomplete transactions that are being rolled back after crash
1646
recovery) will use the global value of
1647
innodb_lock_wait_timeout, because trx->mysql_thd == NULL. */
1648
lock_wait_timeout = thd_lock_wait_timeout(trx->mysql_thd);
1650
if (lock_wait_timeout < 100000000
1651
&& wait_time > (double) lock_wait_timeout) {
1653
trx->error_state = DB_LOCK_WAIT_TIMEOUT;
1657
/********************************************************************//**
1658
Releases a MySQL OS thread waiting for a lock to be released, if the
1659
thread is already suspended. */
1662
srv_release_mysql_thread_if_suspended(
1663
/*==================================*/
1664
que_thr_t* thr) /*!< in: query thread associated with the
1670
ut_ad(mutex_own(&kernel_mutex));
1672
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1674
slot = srv_mysql_table + i;
1676
if (slot->in_use && slot->thr == thr) {
1679
os_event_set(slot->event);
1688
/******************************************************************//**
1689
Refreshes the values used to calculate per-second averages. */
1692
srv_refresh_innodb_monitor_stats(void)
1693
/*==================================*/
1695
mutex_enter(&srv_innodb_monitor_mutex);
1697
srv_last_monitor_time = time(NULL);
1699
os_aio_refresh_stats();
1701
btr_cur_n_sea_old = btr_cur_n_sea;
1702
btr_cur_n_non_sea_old = btr_cur_n_non_sea;
1704
log_refresh_stats();
1706
buf_refresh_io_stats();
1708
srv_n_rows_inserted_old = srv_n_rows_inserted;
1709
srv_n_rows_updated_old = srv_n_rows_updated;
1710
srv_n_rows_deleted_old = srv_n_rows_deleted;
1711
srv_n_rows_read_old = srv_n_rows_read;
1713
mutex_exit(&srv_innodb_monitor_mutex);
1716
/******************************************************************//**
1717
Outputs to a file the output of the InnoDB Monitor. */
1720
srv_printf_innodb_monitor(
1721
/*======================*/
1722
FILE* file, /*!< in: output stream */
1723
ulint* trx_start, /*!< out: file position of the start of
1724
the list of active transactions */
1725
ulint* trx_end) /*!< out: file position of the end of
1726
the list of active transactions */
1728
double time_elapsed;
1729
time_t current_time;
1732
mutex_enter(&srv_innodb_monitor_mutex);
1734
current_time = time(NULL);
1736
/* We add 0.001 seconds to time_elapsed to prevent division
1737
by zero if two users happen to call SHOW INNODB STATUS at the same
1740
time_elapsed = difftime(current_time, srv_last_monitor_time)
1743
srv_last_monitor_time = time(NULL);
1745
fputs("\n=====================================\n", file);
1747
ut_print_timestamp(file);
1749
" INNODB MONITOR OUTPUT\n"
1750
"=====================================\n"
1751
"Per second averages calculated from the last %lu seconds\n",
1752
(ulong)time_elapsed);
1754
fputs("----------\n"
1755
"BACKGROUND THREAD\n"
1756
"----------\n", file);
1757
srv_print_master_thread_info(file);
1759
fputs("----------\n"
1761
"----------\n", file);
1764
/* Conceptually, srv_innodb_monitor_mutex has a very high latching
1765
order level in sync0sync.h, while dict_foreign_err_mutex has a very
1766
low level 135. Therefore we can reserve the latter mutex here without
1767
a danger of a deadlock of threads. */
1769
mutex_enter(&dict_foreign_err_mutex);
1771
if (ftell(dict_foreign_err_file) != 0L) {
1772
fputs("------------------------\n"
1773
"LATEST FOREIGN KEY ERROR\n"
1774
"------------------------\n", file);
1775
ut_copy_file(file, dict_foreign_err_file);
1778
mutex_exit(&dict_foreign_err_mutex);
1780
lock_print_info_summary(file);
1782
long t = ftell(file);
1784
*trx_start = ULINT_UNDEFINED;
1786
*trx_start = (ulint) t;
1789
lock_print_info_all_transactions(file);
1791
long t = ftell(file);
1793
*trx_end = ULINT_UNDEFINED;
1795
*trx_end = (ulint) t;
1800
"--------\n", file);
1803
fputs("-------------------------------------\n"
1804
"INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
1805
"-------------------------------------\n", file);
1808
ha_print_info(file, btr_search_sys->hash_index);
1811
"%.2f hash searches/s, %.2f non-hash searches/s\n",
1812
(btr_cur_n_sea - btr_cur_n_sea_old)
1814
(btr_cur_n_non_sea - btr_cur_n_non_sea_old)
1816
btr_cur_n_sea_old = btr_cur_n_sea;
1817
btr_cur_n_non_sea_old = btr_cur_n_non_sea;
1824
fputs("----------------------\n"
1825
"BUFFER POOL AND MEMORY\n"
1826
"----------------------\n", file);
1828
"Total memory allocated " ULINTPF
1829
"; in additional pool allocated " ULINTPF "\n",
1830
ut_total_allocated_memory,
1831
mem_pool_get_reserved(mem_comm_pool));
1832
fprintf(file, "Dictionary memory allocated " ULINTPF "\n",
1837
fputs("--------------\n"
1839
"--------------\n", file);
1840
fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n",
1841
(long) srv_conc_n_threads,
1842
(ulong) srv_conc_n_waiting_threads);
1844
fprintf(file, "%lu read views open inside InnoDB\n",
1845
UT_LIST_GET_LEN(trx_sys->view_list));
1847
n_reserved = fil_space_get_n_reserved_extents(0);
1848
if (n_reserved > 0) {
1850
"%lu tablespace extents now reserved for"
1851
" B-tree split operations\n",
1852
(ulong) n_reserved);
1856
fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n",
1857
(ulong) srv_main_thread_process_no,
1858
(ulong) srv_main_thread_id,
1859
srv_main_thread_op_info);
1861
fprintf(file, "Main thread id %lu, state: %s\n",
1862
(ulong) srv_main_thread_id,
1863
srv_main_thread_op_info);
1866
"Number of rows inserted " ULINTPF
1867
", updated " ULINTPF ", deleted " ULINTPF
1868
", read " ULINTPF "\n",
1869
srv_n_rows_inserted,
1874
"%.2f inserts/s, %.2f updates/s,"
1875
" %.2f deletes/s, %.2f reads/s\n",
1876
(srv_n_rows_inserted - srv_n_rows_inserted_old)
1878
(srv_n_rows_updated - srv_n_rows_updated_old)
1880
(srv_n_rows_deleted - srv_n_rows_deleted_old)
1882
(srv_n_rows_read - srv_n_rows_read_old)
1885
srv_n_rows_inserted_old = srv_n_rows_inserted;
1886
srv_n_rows_updated_old = srv_n_rows_updated;
1887
srv_n_rows_deleted_old = srv_n_rows_deleted;
1888
srv_n_rows_read_old = srv_n_rows_read;
1890
fputs("----------------------------\n"
1891
"END OF INNODB MONITOR OUTPUT\n"
1892
"============================\n", file);
1893
mutex_exit(&srv_innodb_monitor_mutex);
1897
/******************************************************************//**
1898
Function to pass InnoDB status variables to MySQL */
1901
srv_export_innodb_status(void)
1902
/*==========================*/
1904
mutex_enter(&srv_innodb_monitor_mutex);
1906
export_vars.innodb_data_pending_reads
1907
= os_n_pending_reads;
1908
export_vars.innodb_data_pending_writes
1909
= os_n_pending_writes;
1910
export_vars.innodb_data_pending_fsyncs
1911
= fil_n_pending_log_flushes
1912
+ fil_n_pending_tablespace_flushes;
1913
export_vars.innodb_data_fsyncs = os_n_fsyncs;
1914
export_vars.innodb_data_read = srv_data_read;
1915
export_vars.innodb_data_reads = os_n_file_reads;
1916
export_vars.innodb_data_writes = os_n_file_writes;
1917
export_vars.innodb_data_written = srv_data_written;
1918
export_vars.innodb_buffer_pool_read_requests = buf_pool->n_page_gets;
1919
export_vars.innodb_buffer_pool_write_requests
1920
= srv_buf_pool_write_requests;
1921
export_vars.innodb_buffer_pool_wait_free = srv_buf_pool_wait_free;
1922
export_vars.innodb_buffer_pool_pages_flushed = srv_buf_pool_flushed;
1923
export_vars.innodb_buffer_pool_reads = srv_buf_pool_reads;
1924
export_vars.innodb_buffer_pool_read_ahead_rnd = srv_read_ahead_rnd;
1925
export_vars.innodb_buffer_pool_read_ahead_seq = srv_read_ahead_seq;
1926
export_vars.innodb_buffer_pool_pages_data
1927
= UT_LIST_GET_LEN(buf_pool->LRU);
1928
export_vars.innodb_buffer_pool_pages_dirty
1929
= UT_LIST_GET_LEN(buf_pool->flush_list);
1930
export_vars.innodb_buffer_pool_pages_free
1931
= UT_LIST_GET_LEN(buf_pool->free);
1933
export_vars.innodb_buffer_pool_pages_latched
1934
= buf_get_latched_pages_number();
1935
#endif /* UNIV_DEBUG */
1936
export_vars.innodb_buffer_pool_pages_total = buf_pool->curr_size;
1938
export_vars.innodb_buffer_pool_pages_misc = buf_pool->curr_size
1939
- UT_LIST_GET_LEN(buf_pool->LRU)
1940
- UT_LIST_GET_LEN(buf_pool->free);
1941
#ifdef HAVE_ATOMIC_BUILTINS
1942
export_vars.innodb_have_atomic_builtins = 1;
1944
export_vars.innodb_have_atomic_builtins = 0;
1946
export_vars.innodb_page_size = UNIV_PAGE_SIZE;
1947
export_vars.innodb_log_waits = srv_log_waits;
1948
export_vars.innodb_os_log_written = srv_os_log_written;
1949
export_vars.innodb_os_log_fsyncs = fil_n_log_flushes;
1950
export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes;
1951
export_vars.innodb_os_log_pending_writes = srv_os_log_pending_writes;
1952
export_vars.innodb_log_write_requests = srv_log_write_requests;
1953
export_vars.innodb_log_writes = srv_log_writes;
1954
export_vars.innodb_dblwr_pages_written = srv_dblwr_pages_written;
1955
export_vars.innodb_dblwr_writes = srv_dblwr_writes;
1956
export_vars.innodb_pages_created = buf_pool->n_pages_created;
1957
export_vars.innodb_pages_read = buf_pool->n_pages_read;
1958
export_vars.innodb_pages_written = buf_pool->n_pages_written;
1959
export_vars.innodb_row_lock_waits = srv_n_lock_wait_count;
1960
export_vars.innodb_row_lock_current_waits
1961
= srv_n_lock_wait_current_count;
1962
export_vars.innodb_row_lock_time = srv_n_lock_wait_time / 1000;
1963
if (srv_n_lock_wait_count > 0) {
1964
export_vars.innodb_row_lock_time_avg = (ulint)
1965
(srv_n_lock_wait_time / 1000 / srv_n_lock_wait_count);
1967
export_vars.innodb_row_lock_time_avg = 0;
1969
export_vars.innodb_row_lock_time_max
1970
= srv_n_lock_max_wait_time / 1000;
1971
export_vars.innodb_rows_read = srv_n_rows_read;
1972
export_vars.innodb_rows_inserted = srv_n_rows_inserted;
1973
export_vars.innodb_rows_updated = srv_n_rows_updated;
1974
export_vars.innodb_rows_deleted = srv_n_rows_deleted;
1976
mutex_exit(&srv_innodb_monitor_mutex);
1979
/*********************************************************************//**
1980
A thread which wakes up threads whose lock wait may have lasted too long.
1981
This also prints the info output by various InnoDB monitors.
1982
@return a dummy parameter */
1985
srv_lock_timeout_and_monitor_thread(
1986
/*================================*/
1987
void* arg __attribute__((unused)))
1988
/*!< in: a dummy parameter required by
1992
double time_elapsed;
1993
time_t current_time;
1994
time_t last_table_monitor_time;
1995
time_t last_tablespace_monitor_time;
1996
time_t last_monitor_time;
2001
#ifdef UNIV_DEBUG_THREAD_CREATION
2002
fprintf(stderr, "Lock timeout thread starts, id %lu\n",
2003
os_thread_pf(os_thread_get_curr_id()));
2006
srv_last_monitor_time = time(NULL);
2007
last_table_monitor_time = time(NULL);
2008
last_tablespace_monitor_time = time(NULL);
2009
last_monitor_time = time(NULL);
2011
srv_lock_timeout_and_monitor_active = TRUE;
2013
/* When someone is waiting for a lock, we wake up every second
2014
and check if a timeout has passed for a lock wait */
2016
os_thread_sleep(1000000);
2018
current_time = time(NULL);
2020
time_elapsed = difftime(current_time, last_monitor_time);
2022
if (time_elapsed > 15) {
2023
last_monitor_time = time(NULL);
2025
if (srv_print_innodb_monitor) {
2026
srv_printf_innodb_monitor(stderr, NULL, NULL);
2029
if (srv_innodb_status) {
2030
mutex_enter(&srv_monitor_file_mutex);
2031
rewind(srv_monitor_file);
2032
srv_printf_innodb_monitor(srv_monitor_file, NULL,
2034
os_file_set_eof(srv_monitor_file);
2035
mutex_exit(&srv_monitor_file_mutex);
2038
if (srv_print_innodb_tablespace_monitor
2039
&& difftime(current_time,
2040
last_tablespace_monitor_time) > 60) {
2041
last_tablespace_monitor_time = time(NULL);
2043
fputs("========================"
2044
"========================\n",
2047
ut_print_timestamp(stderr);
2049
fputs(" INNODB TABLESPACE MONITOR OUTPUT\n"
2050
"========================"
2051
"========================\n",
2055
fputs("Validating tablespace\n", stderr);
2057
fputs("Validation ok\n"
2058
"---------------------------------------\n"
2059
"END OF INNODB TABLESPACE MONITOR OUTPUT\n"
2060
"=======================================\n",
2064
if (srv_print_innodb_table_monitor
2065
&& difftime(current_time, last_table_monitor_time) > 60) {
2067
last_table_monitor_time = time(NULL);
2069
fputs("===========================================\n",
2072
ut_print_timestamp(stderr);
2074
fputs(" INNODB TABLE MONITOR OUTPUT\n"
2075
"===========================================\n",
2079
fputs("-----------------------------------\n"
2080
"END OF INNODB TABLE MONITOR OUTPUT\n"
2081
"==================================\n",
2086
mutex_enter(&kernel_mutex);
2090
/* Check of all slots if a thread is waiting there, and if it
2091
has exceeded the time limit */
2093
for (i = 0; i < OS_THREAD_MAX_N; i++) {
2095
slot = srv_mysql_table + i;
2099
ulong lock_wait_timeout;
2103
wait_time = ut_difftime(ut_time(), slot->suspend_time);
2105
trx = thr_get_trx(slot->thr);
2106
lock_wait_timeout = thd_lock_wait_timeout(
2109
if (lock_wait_timeout < 100000000
2110
&& (wait_time > (double) lock_wait_timeout
2111
|| wait_time < 0)) {
2113
/* Timeout exceeded or a wrap-around in system
2114
time counter: cancel the lock request queued
2115
by the transaction and release possible
2116
other transactions waiting behind; it is
2117
possible that the lock has already been
2118
granted: in that case do nothing */
2120
if (trx->wait_lock) {
2121
lock_cancel_waiting_and_release(
2128
os_event_reset(srv_lock_timeout_thread_event);
2130
mutex_exit(&kernel_mutex);
2132
if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
2136
if (some_waits || srv_print_innodb_monitor
2137
|| srv_print_innodb_lock_monitor
2138
|| srv_print_innodb_tablespace_monitor
2139
|| srv_print_innodb_table_monitor) {
2143
/* No one was waiting for a lock and no monitor was active:
2144
suspend this thread */
2146
srv_lock_timeout_and_monitor_active = FALSE;
2149
/* The following synchronisation is disabled, since
2150
the InnoDB monitor output is to be updated every 15 seconds. */
2151
os_event_wait(srv_lock_timeout_thread_event);
2156
srv_lock_timeout_and_monitor_active = FALSE;
2158
/* We count the number of threads in os_thread_exit(). A created
2159
thread should always use that to exit and not use return() to exit. */
2161
os_thread_exit(NULL);
2163
OS_THREAD_DUMMY_RETURN;
2166
/*********************************************************************//**
2167
A thread which prints warnings about semaphore waits which have lasted
2168
too long. These can be used to track bugs which cause hangs.
2169
@return a dummy parameter */
2172
srv_error_monitor_thread(
2173
/*=====================*/
2174
void* arg __attribute__((unused)))
2175
/*!< in: a dummy parameter required by
2178
/* number of successive fatal timeouts observed */
2179
ulint fatal_cnt = 0;
2180
ib_uint64_t old_lsn;
2181
ib_uint64_t new_lsn;
2183
old_lsn = srv_start_lsn;
2185
#ifdef UNIV_DEBUG_THREAD_CREATION
2186
fprintf(stderr, "Error monitor thread starts, id %lu\n",
2187
os_thread_pf(os_thread_get_curr_id()));
2190
srv_error_monitor_active = TRUE;
2192
/* Try to track a strange bug reported by Harald Fuchs and others,
2193
where the lsn seems to decrease at times */
2195
new_lsn = log_get_lsn();
2197
if (new_lsn < old_lsn) {
2198
ut_print_timestamp(stderr);
2200
" InnoDB: Error: old log sequence number %"PRIu64""
2202
"InnoDB: than the new log sequence number %"PRIu64"!\n"
2203
"InnoDB: Please submit a bug report"
2204
" to http://bugs.mysql.com\n",
2210
if (difftime(time(NULL), srv_last_monitor_time) > 60) {
2211
/* We referesh InnoDB Monitor values so that averages are
2212
printed from at most 60 last seconds */
2214
srv_refresh_innodb_monitor_stats();
2217
/* Update the statistics collected for deciding LRU
2219
buf_LRU_stat_update();
2221
/* Update the statistics collected for flush rate policy. */
2222
buf_flush_stat_update();
2224
/* In case mutex_exit is not a memory barrier, it is
2225
theoretically possible some threads are left waiting though
2226
the semaphore is already released. Wake up those threads: */
2228
sync_arr_wake_threads_if_sema_free();
2230
if (sync_array_print_long_waits()) {
2232
if (fatal_cnt > 10) {
2235
"InnoDB: Error: semaphore wait has lasted"
2237
"InnoDB: We intentionally crash the server,"
2238
" because it appears to be hung.\n",
2239
(ulong) srv_fatal_semaphore_wait_threshold);
2247
/* Flush stderr so that a database user gets the output
2248
to possible MySQL error file */
2252
os_thread_sleep(1000000);
2254
if (srv_shutdown_state < SRV_SHUTDOWN_CLEANUP) {
2259
srv_error_monitor_active = FALSE;
2261
/* We count the number of threads in os_thread_exit(). A created
2262
thread should always use that to exit and not use return() to exit. */
2264
os_thread_exit(NULL);
2266
OS_THREAD_DUMMY_RETURN;
2269
/*******************************************************************//**
2270
Tells the InnoDB server that there has been activity in the database
2271
and wakes up the master thread if it is suspended (not sleeping). Used
2272
in the MySQL interface. Note that there is a small chance that the master
2273
thread stays suspended (we do not protect our operation with the kernel
2274
mutex, for performace reasons). */
2277
srv_active_wake_master_thread(void)
2278
/*===============================*/
2280
srv_activity_count++;
2282
if (srv_n_threads_active[SRV_MASTER] == 0) {
2284
mutex_enter(&kernel_mutex);
2286
srv_release_threads(SRV_MASTER, 1);
2288
mutex_exit(&kernel_mutex);
2292
/*******************************************************************//**
2293
Wakes up the master thread if it is suspended or being suspended. */
2296
srv_wake_master_thread(void)
2297
/*========================*/
2299
srv_activity_count++;
2301
mutex_enter(&kernel_mutex);
2303
srv_release_threads(SRV_MASTER, 1);
2305
mutex_exit(&kernel_mutex);
2308
/**********************************************************************
2309
The master thread is tasked to ensure that flush of log file happens
2310
once every second in the background. This is to ensure that not more
2311
than one second of trxs are lost in case of crash when
2312
innodb_flush_logs_at_trx_commit != 1 */
2315
srv_sync_log_buffer_in_background(void)
2316
/*===================================*/
2318
time_t current_time = time(NULL);
2320
srv_main_thread_op_info = "flushing log";
2321
if (difftime(current_time, srv_last_log_flush_time) >= 1) {
2322
log_buffer_sync_in_background(TRUE);
2323
srv_last_log_flush_time = current_time;
2324
srv_log_writes_and_flush++;
2326
/* Actually we don't need to write logs here.
2327
We are just being extra safe here by forcing
2328
the log buffer to log file. */
2329
log_buffer_sync_in_background(FALSE);
2330
srv_log_buffer_writes++;
2334
/*********************************************************************//**
2335
The master thread controlling the server.
2336
@return a dummy parameter */
2341
void* arg __attribute__((unused)))
2342
/*!< in: a dummy parameter required by
2346
ulint old_activity_count;
2347
ulint n_pages_purged = 0;
2348
ulint n_bytes_merged;
2349
ulint n_pages_flushed;
2350
ulint n_bytes_archived;
2351
ulint n_tables_to_drop;
2354
ulint n_ios_very_old;
2356
ibool skip_sleep = FALSE;
2359
#ifdef UNIV_DEBUG_THREAD_CREATION
2360
fprintf(stderr, "Master thread starts, id %lu\n",
2361
os_thread_pf(os_thread_get_curr_id()));
2363
srv_main_thread_process_no = os_proc_get_number();
2364
srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());
2366
srv_table_reserve_slot(SRV_MASTER);
2368
mutex_enter(&kernel_mutex);
2370
srv_n_threads_active[SRV_MASTER]++;
2372
mutex_exit(&kernel_mutex);
2375
/*****************************************************************/
2376
/* ---- When there is database activity by users, we cycle in this
2379
srv_main_thread_op_info = "reserving kernel mutex";
2381
n_ios_very_old = log_sys->n_log_ios + buf_pool->n_pages_read
2382
+ buf_pool->n_pages_written;
2383
mutex_enter(&kernel_mutex);
2385
/* Store the user activity counter at the start of this loop */
2386
old_activity_count = srv_activity_count;
2388
mutex_exit(&kernel_mutex);
2390
if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
2392
goto suspend_thread;
2395
/* ---- We run the following loop approximately once per second
2396
when there is database activity */
2398
srv_last_log_flush_time = time(NULL);
2401
for (i = 0; i < 10; i++) {
2402
n_ios_old = log_sys->n_log_ios + buf_pool->n_pages_read
2403
+ buf_pool->n_pages_written;
2404
srv_main_thread_op_info = "sleeping";
2405
srv_main_1_second_loops++;
2409
os_thread_sleep(1000000);
2415
/* ALTER TABLE in MySQL requires on Unix that the table handler
2416
can drop tables lazily after there no longer are SELECT
2419
srv_main_thread_op_info = "doing background drop tables";
2421
row_drop_tables_for_mysql_in_background();
2423
srv_main_thread_op_info = "";
2425
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2427
goto background_loop;
2430
/* Flush logs if needed */
2431
srv_sync_log_buffer_in_background();
2433
srv_main_thread_op_info = "making checkpoint";
2436
/* If i/os during one second sleep were less than 5% of
2437
capacity, we assume that there is free disk i/o capacity
2438
available, and it makes sense to do an insert buffer merge. */
2440
n_pend_ios = buf_get_n_pending_ios()
2441
+ log_sys->n_pending_writes;
2442
n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
2443
+ buf_pool->n_pages_written;
2444
if (n_pend_ios < SRV_PEND_IO_THRESHOLD
2445
&& (n_ios - n_ios_old < SRV_RECENT_IO_ACTIVITY)) {
2446
srv_main_thread_op_info = "doing insert buffer merge";
2447
ibuf_contract_for_n_pages(FALSE, PCT_IO(5));
2449
/* Flush logs if needed */
2450
srv_sync_log_buffer_in_background();
2453
if (UNIV_UNLIKELY(buf_get_modified_ratio_pct()
2454
> srv_max_buf_pool_modified_pct)) {
2456
/* Try to keep the number of modified pages in the
2457
buffer pool under the limit wished by the user */
2459
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2463
/* If we had to do the flush, it may have taken
2464
even more than 1 second, and also, there may be more
2465
to flush. Do not sleep 1 second during the next
2466
iteration of this loop. */
2469
} else if (srv_adaptive_flushing) {
2471
/* Try to keep the rate of flushing of dirty
2472
pages such that redo log generation does not
2473
produce bursts of IO at checkpoint time. */
2474
ulint n_flush = buf_flush_get_desired_flush_rate();
2477
n_flush = ut_min(PCT_IO(100), n_flush);
2487
if (srv_activity_count == old_activity_count) {
2489
/* There is no user activity at the moment, go to
2490
the background loop */
2492
goto background_loop;
2496
/* ---- We perform the following code approximately once per
2497
10 seconds when there is database activity */
2499
#ifdef MEM_PERIODIC_CHECK
2500
/* Check magic numbers of every allocated mem block once in 10
2502
mem_validate_all_blocks();
2504
/* If i/os during the 10 second period were less than 200% of
2505
capacity, we assume that there is free disk i/o capacity
2506
available, and it makes sense to flush srv_io_capacity pages.
2508
Note that this is done regardless of the fraction of dirty
2509
pages relative to the max requested by the user. The one second
2510
loop above requests writes for that case. The writes done here
2511
are not required, and may be disabled. */
2513
n_pend_ios = buf_get_n_pending_ios() + log_sys->n_pending_writes;
2514
n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
2515
+ buf_pool->n_pages_written;
2517
srv_main_10_second_loops++;
2518
if (n_pend_ios < SRV_PEND_IO_THRESHOLD
2519
&& (n_ios - n_ios_very_old < SRV_PAST_IO_ACTIVITY)) {
2521
srv_main_thread_op_info = "flushing buffer pool pages";
2522
buf_flush_batch(BUF_FLUSH_LIST, PCT_IO(100),
2525
/* Flush logs if needed */
2526
srv_sync_log_buffer_in_background();
2529
/* We run a batch of insert buffer merge every 10 seconds,
2530
even if the server were active */
2532
srv_main_thread_op_info = "doing insert buffer merge";
2533
ibuf_contract_for_n_pages(FALSE, PCT_IO(5));
2535
/* Flush logs if needed */
2536
srv_sync_log_buffer_in_background();
2538
/* We run a full purge every 10 seconds, even if the server
2542
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2544
goto background_loop;
2547
srv_main_thread_op_info = "purging";
2548
n_pages_purged = trx_purge();
2550
/* Flush logs if needed */
2551
srv_sync_log_buffer_in_background();
2553
} while (n_pages_purged);
2555
srv_main_thread_op_info = "flushing buffer pool pages";
2557
/* Flush a few oldest pages to make a new checkpoint younger */
2559
if (buf_get_modified_ratio_pct() > 70) {
2561
/* If there are lots of modified pages in the buffer pool
2562
(> 70 %), we assume we can afford reserving the disk(s) for
2563
the time it requires to flush 100 pages */
2565
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2569
/* Otherwise, we only flush a small number of pages so that
2570
we do not unnecessarily use much disk i/o capacity from
2573
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2578
srv_main_thread_op_info = "making checkpoint";
2580
/* Make a new checkpoint about once in 10 seconds */
2582
log_checkpoint(TRUE, FALSE);
2584
srv_main_thread_op_info = "reserving kernel mutex";
2586
mutex_enter(&kernel_mutex);
2588
/* ---- When there is database activity, we jump from here back to
2589
the start of loop */
2591
if (srv_activity_count != old_activity_count) {
2592
mutex_exit(&kernel_mutex);
2596
mutex_exit(&kernel_mutex);
2598
/* If the database is quiet, we enter the background loop */
2600
/*****************************************************************/
2602
/* ---- In this loop we run background operations when the server
2603
is quiet from user activity. Also in the case of a shutdown, we
2604
loop here, flushing the buffer pool to the data files. */
2606
/* The server has been quiet for a while: start running background
2608
srv_main_background_loops++;
2609
srv_main_thread_op_info = "doing background drop tables";
2611
n_tables_to_drop = row_drop_tables_for_mysql_in_background();
2613
if (n_tables_to_drop > 0) {
2614
/* Do not monopolize the CPU even if there are tables waiting
2615
in the background drop queue. (It is essentially a bug if
2616
MySQL tries to drop a table while there are still open handles
2617
to it and we had to put it to the background drop queue.) */
2619
os_thread_sleep(100000);
2622
srv_main_thread_op_info = "purging";
2624
/* Run a full purge */
2626
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2631
srv_main_thread_op_info = "purging";
2632
n_pages_purged = trx_purge();
2634
/* Flush logs if needed */
2635
srv_sync_log_buffer_in_background();
2637
} while (n_pages_purged);
2639
srv_main_thread_op_info = "reserving kernel mutex";
2641
mutex_enter(&kernel_mutex);
2642
if (srv_activity_count != old_activity_count) {
2643
mutex_exit(&kernel_mutex);
2646
mutex_exit(&kernel_mutex);
2648
srv_main_thread_op_info = "doing insert buffer merge";
2650
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2653
/* This should do an amount of IO similar to the number of
2654
dirty pages that will be flushed in the call to
2655
buf_flush_batch below. Otherwise, the system favors
2656
clean pages over cleanup throughput. */
2657
n_bytes_merged = ibuf_contract_for_n_pages(FALSE,
2661
srv_main_thread_op_info = "reserving kernel mutex";
2663
mutex_enter(&kernel_mutex);
2664
if (srv_activity_count != old_activity_count) {
2665
mutex_exit(&kernel_mutex);
2668
mutex_exit(&kernel_mutex);
2671
srv_main_thread_op_info = "flushing buffer pool pages";
2672
srv_main_flush_loops++;
2673
if (srv_fast_shutdown < 2) {
2674
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2678
/* In the fastest shutdown we do not flush the buffer pool
2679
to data files: we set n_pages_flushed to 0 artificially. */
2681
n_pages_flushed = 0;
2684
srv_main_thread_op_info = "reserving kernel mutex";
2686
mutex_enter(&kernel_mutex);
2687
if (srv_activity_count != old_activity_count) {
2688
mutex_exit(&kernel_mutex);
2691
mutex_exit(&kernel_mutex);
2693
srv_main_thread_op_info = "waiting for buffer pool flush to end";
2694
buf_flush_wait_batch_end(BUF_FLUSH_LIST);
2696
/* Flush logs if needed */
2697
srv_sync_log_buffer_in_background();
2699
srv_main_thread_op_info = "making checkpoint";
2701
log_checkpoint(TRUE, FALSE);
2703
if (buf_get_modified_ratio_pct() > srv_max_buf_pool_modified_pct) {
2705
/* Try to keep the number of modified pages in the
2706
buffer pool under the limit wished by the user */
2711
srv_main_thread_op_info = "reserving kernel mutex";
2713
mutex_enter(&kernel_mutex);
2714
if (srv_activity_count != old_activity_count) {
2715
mutex_exit(&kernel_mutex);
2718
mutex_exit(&kernel_mutex);
2720
srv_main_thread_op_info = "archiving log (if log archive is on)";
2722
log_archive_do(FALSE, &n_bytes_archived);
2724
n_bytes_archived = 0;
2726
/* Keep looping in the background loop if still work to do */
2728
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2729
if (n_tables_to_drop + n_pages_flushed
2730
+ n_bytes_archived != 0) {
2732
/* If we are doing a fast shutdown (= the default)
2733
we do not do purge or insert buffer merge. But we
2734
flush the buffer pool completely to disk.
2735
In a 'very fast' shutdown we do not flush the buffer
2736
pool to data files: we have set n_pages_flushed to
2739
goto background_loop;
2741
} else if (n_tables_to_drop
2742
+ n_pages_purged + n_bytes_merged + n_pages_flushed
2743
+ n_bytes_archived != 0) {
2744
/* In a 'slow' shutdown we run purge and the insert buffer
2745
merge to completion */
2747
goto background_loop;
2750
/* There is no work for background operations either: suspend
2751
master thread to wait for more server activity */
2754
srv_main_thread_op_info = "suspending";
2756
mutex_enter(&kernel_mutex);
2758
if (row_get_background_drop_list_len_low() > 0) {
2759
mutex_exit(&kernel_mutex);
2764
event = srv_suspend_thread();
2766
mutex_exit(&kernel_mutex);
2768
/* DO NOT CHANGE THIS STRING. innobase_start_or_create_for_mysql()
2769
waits for database activity to die down when converting < 4.1.x
2770
databases, and relies on this string being exactly as it is. InnoDB
2771
manual also mentions this string in several places. */
2772
srv_main_thread_op_info = "waiting for server activity";
2774
os_event_wait(event);
2776
if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
2777
/* This is only extra safety, the thread should exit
2778
already when the event wait ends */
2780
os_thread_exit(NULL);
2783
/* When there is user activity, InnoDB will set the event and the
2784
main thread goes back to loop. */
2789
#if (!defined(__SUNPRO_C) && !defined(__SUNPRO_CC))
2790
OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */