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 ibool srv_set_thread_priorities = TRUE;
419
UNIV_INTERN int srv_query_thread_priority = 0;
421
UNIV_INTERN ulong srv_replication_delay = 0;
423
/*-------------------------------------------*/
424
UNIV_INTERN ulong srv_n_spin_wait_rounds = 30;
425
UNIV_INTERN ulong srv_n_free_tickets_to_enter = 500;
426
UNIV_INTERN ulong srv_thread_sleep_delay = 10000;
427
UNIV_INTERN ulong srv_spin_wait_delay = 6;
428
UNIV_INTERN ibool srv_priority_boost = TRUE;
431
UNIV_INTERN ibool srv_print_thread_releases = FALSE;
432
UNIV_INTERN ibool srv_print_lock_waits = FALSE;
433
UNIV_INTERN ibool srv_print_buf_io = FALSE;
434
UNIV_INTERN ibool srv_print_log_io = FALSE;
435
UNIV_INTERN ibool srv_print_latch_waits = FALSE;
436
#endif /* UNIV_DEBUG */
438
UNIV_INTERN ulint srv_n_rows_inserted = 0;
439
UNIV_INTERN ulint srv_n_rows_updated = 0;
440
UNIV_INTERN ulint srv_n_rows_deleted = 0;
441
UNIV_INTERN ulint srv_n_rows_read = 0;
443
static ulint srv_n_rows_inserted_old = 0;
444
static ulint srv_n_rows_updated_old = 0;
445
static ulint srv_n_rows_deleted_old = 0;
446
static ulint srv_n_rows_read_old = 0;
448
UNIV_INTERN ulint srv_n_lock_wait_count = 0;
449
UNIV_INTERN ulint srv_n_lock_wait_current_count = 0;
450
UNIV_INTERN ib_int64_t srv_n_lock_wait_time = 0;
451
UNIV_INTERN ulint srv_n_lock_max_wait_time = 0;
455
Set the following to 0 if you want InnoDB to write messages on
456
stderr on startup/shutdown
458
UNIV_INTERN ibool srv_print_verbose_log = TRUE;
459
UNIV_INTERN ibool srv_print_innodb_monitor = FALSE;
460
UNIV_INTERN ibool srv_print_innodb_lock_monitor = FALSE;
461
UNIV_INTERN ibool srv_print_innodb_tablespace_monitor = FALSE;
462
UNIV_INTERN ibool srv_print_innodb_table_monitor = FALSE;
464
/* Array of English strings describing the current state of an
465
i/o handler thread */
467
UNIV_INTERN const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
468
UNIV_INTERN const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
470
UNIV_INTERN time_t srv_last_monitor_time;
472
UNIV_INTERN mutex_t srv_innodb_monitor_mutex;
474
/* Mutex for locking srv_monitor_file */
475
UNIV_INTERN mutex_t srv_monitor_file_mutex;
476
/* Temporary file for innodb monitor output */
477
UNIV_INTERN FILE* srv_monitor_file;
478
/* Mutex for locking srv_dict_tmpfile.
479
This mutex has a very high rank; threads reserving it should not
480
be holding any InnoDB latches. */
481
UNIV_INTERN mutex_t srv_dict_tmpfile_mutex;
482
/* Temporary file for output from the data dictionary */
483
UNIV_INTERN FILE* srv_dict_tmpfile;
484
/* Mutex for locking srv_misc_tmpfile.
485
This mutex has a very low rank; threads reserving it should not
486
acquire any further latches or sleep before releasing this one. */
487
UNIV_INTERN mutex_t srv_misc_tmpfile_mutex;
488
/* Temporary file for miscellanous diagnostic output */
489
UNIV_INTERN FILE* srv_misc_tmpfile;
491
UNIV_INTERN ulint srv_main_thread_process_no = 0;
492
UNIV_INTERN ulint srv_main_thread_id = 0;
494
/* The following count work done by srv_master_thread. */
496
/* Iterations by the 'once per second' loop. */
497
static ulint srv_main_1_second_loops = 0;
498
/* Calls to sleep by the 'once per second' loop. */
499
static ulint srv_main_sleeps = 0;
500
/* Iterations by the 'once per 10 seconds' loop. */
501
static ulint srv_main_10_second_loops = 0;
502
/* Iterations of the loop bounded by the 'background_loop' label. */
503
static ulint srv_main_background_loops = 0;
504
/* Iterations of the loop bounded by the 'flush_loop' label. */
505
static ulint srv_main_flush_loops = 0;
506
/* Log writes involving flush. */
507
static ulint srv_log_writes_and_flush = 0;
508
/* Log writes not including flush. */
509
static ulint srv_log_buffer_writes = 0;
511
/* This is only ever touched by the master thread. It records the
512
time when the last flush of log file has happened. The master
513
thread ensures that we flush the log files at least once per
515
static time_t srv_last_log_flush_time;
517
/* The master thread performs various tasks based on the current
518
state of IO activity and the level of IO utilization is past
519
intervals. Following macros define thresholds for these conditions. */
520
#define SRV_PEND_IO_THRESHOLD (PCT_IO(3))
521
#define SRV_RECENT_IO_ACTIVITY (PCT_IO(5))
522
#define SRV_PAST_IO_ACTIVITY (PCT_IO(200))
525
IMPLEMENTATION OF THE SERVER MAIN PROGRAM
526
=========================================
528
There is the following analogue between this database
529
server and an operating system kernel:
531
DB concept equivalent OS concept
532
---------- ---------------------
533
transaction -- process;
535
query thread -- thread;
540
the rollback state -- kill signal delivered to a process;
544
query thread execution:
545
(a) without kernel mutex
546
reserved -- process executing in user mode;
547
(b) with kernel mutex reserved
548
-- process executing in kernel mode;
550
The server is controlled by a master thread which runs at
551
a priority higher than normal, that is, higher than user threads.
552
It sleeps most of the time, and wakes up, say, every 300 milliseconds,
553
to check whether there is anything happening in the server which
554
requires intervention of the master thread. Such situations may be,
555
for example, when flushing of dirty blocks is needed in the buffer
556
pool or old version of database rows have to be cleaned away.
558
The threads which we call user threads serve the queries of
559
the clients and input from the console of the server.
560
They run at normal priority. The server may have several
561
communications endpoints. A dedicated set of user threads waits
562
at each of these endpoints ready to receive a client request.
563
Each request is taken by a single user thread, which then starts
564
processing and, when the result is ready, sends it to the client
565
and returns to wait at the same endpoint the thread started from.
567
So, we do not have dedicated communication threads listening at
568
the endpoints and dealing the jobs to dedicated worker threads.
569
Our architecture saves one thread swithch per request, compared
570
to the solution with dedicated communication threads
571
which amounts to 15 microseconds on 100 MHz Pentium
572
running NT. If the client
573
is communicating over a network, this saving is negligible, but
574
if the client resides in the same machine, maybe in an SMP machine
575
on a different processor from the server thread, the saving
576
can be important as the threads can communicate over shared
577
memory with an overhead of a few microseconds.
579
We may later implement a dedicated communication thread solution
580
for those endpoints which communicate over a network.
582
Our solution with user threads has two problems: for each endpoint
583
there has to be a number of listening threads. If there are many
584
communication endpoints, it may be difficult to set the right number
585
of concurrent threads in the system, as many of the threads
586
may always be waiting at less busy endpoints. Another problem
587
is queuing of the messages, as the server internally does not
588
offer any queue for jobs.
590
Another group of user threads is intended for splitting the
591
queries and processing them in parallel. Let us call these
592
parallel communication threads. These threads are waiting for
593
parallelized tasks, suspended on event semaphores.
595
A single user thread waits for input from the console,
596
like a command to shut the database.
598
Utility threads are a different group of threads which takes
599
care of the buffer pool flushing and other, mainly background
600
operations, in the server.
601
Some of these utility threads always run at a lower than normal
602
priority, so that they are always in background. Some of them
603
may dynamically boost their priority by the pri_adjust function,
604
even to higher than normal priority, if their task becomes urgent.
605
The running of utilities is controlled by high- and low-water marks
606
of urgency. The urgency may be measured by the number of dirty blocks
607
in the buffer pool, in the case of the flush thread, for example.
608
When the high-water mark is exceeded, an utility starts running, until
609
the urgency drops under the low-water mark. Then the utility thread
610
suspend itself to wait for an event. The master thread is
611
responsible of signaling this event when the utility thread is
614
For each individual type of utility, some threads always remain
615
at lower than normal priority. This is because pri_adjust is implemented
616
so that the threads at normal or higher priority control their
617
share of running time by calling sleep. Thus, if the load of the
618
system sudenly drops, these threads cannot necessarily utilize
619
the system fully. The background priority threads make up for this,
620
starting to run when the load drops.
622
When there is no activity in the system, also the master thread
623
suspends itself to wait for an event making
624
the server totally silent. The responsibility to signal this
625
event is on the user thread which again receives a message
628
There is still one complication in our server design. If a
629
background utility thread obtains a resource (e.g., mutex) needed by a user
630
thread, and there is also some other user activity in the system,
631
the user thread may have to wait indefinitely long for the
632
resource, as the OS does not schedule a background thread if
633
there is some other runnable user thread. This problem is called
634
priority inversion in real-time programming.
636
One solution to the priority inversion problem would be to
637
keep record of which thread owns which resource and
638
in the above case boost the priority of the background thread
639
so that it will be scheduled and it can release the resource.
640
This solution is called priority inheritance in real-time programming.
641
A drawback of this solution is that the overhead of acquiring a mutex
642
increases slightly, maybe 0.2 microseconds on a 100 MHz Pentium, because
643
the thread has to call os_thread_get_curr_id.
644
This may be compared to 0.5 microsecond overhead for a mutex lock-unlock
645
pair. Note that the thread
646
cannot store the information in the resource, say mutex, itself,
647
because competing threads could wipe out the information if it is
648
stored before acquiring the mutex, and if it stored afterwards,
649
the information is outdated for the time of one machine instruction,
650
at least. (To be precise, the information could be stored to
651
lock_word in mutex if the machine supports atomic swap.)
653
The above solution with priority inheritance may become actual in the
654
future, but at the moment we plan to implement a more coarse solution,
655
which could be called a global priority inheritance. If a thread
656
has to wait for a long time, say 300 milliseconds, for a resource,
657
we just guess that it may be waiting for a resource owned by a background
658
thread, and boost the the priority of all runnable background threads
659
to the normal level. The background threads then themselves adjust
660
their fixed priority back to background after releasing all resources
661
they had (or, at some fixed points in their program code).
663
What is the performance of the global priority inheritance solution?
664
We may weigh the length of the wait time 300 milliseconds, during
665
which the system processes some other thread
666
to the cost of boosting the priority of each runnable background
667
thread, rescheduling it, and lowering the priority again.
668
On 100 MHz Pentium + NT this overhead may be of the order 100
669
microseconds per thread. So, if the number of runnable background
670
threads is not very big, say < 100, the cost is tolerable.
671
Utility threads probably will access resources used by
672
user threads not very often, so collisions of user threads
673
to preempted utility threads should not happen very often.
675
The thread table contains
676
information of the current status of each thread existing in the system,
677
and also the event semaphores used in suspending the master thread
678
and utility and parallel communication threads when they have nothing to do.
679
The thread table can be seen as an analogue to the process table
680
in a traditional Unix implementation.
682
The thread table is also used in the global priority inheritance
683
scheme. This brings in one additional complication: threads accessing
684
the thread table must have at least normal fixed priority,
685
because the priority inheritance solution does not work if a background
686
thread is preempted while possessing the mutex protecting the thread table.
687
So, if a thread accesses the thread table, its priority has to be
688
boosted at least to normal. This priority requirement can be seen similar to
689
the privileged mode used when processing the kernel calls in traditional
692
/* Thread slot in the thread table */
693
struct srv_slot_struct{
694
os_thread_id_t id; /*!< thread id */
695
os_thread_t handle; /*!< thread handle */
696
unsigned type:3; /*!< thread type: user, utility etc. */
697
unsigned in_use:1; /*!< TRUE if this slot is in use */
698
unsigned suspended:1; /*!< TRUE if the thread is waiting
699
for the event of this slot */
700
ib_time_t suspend_time; /*!< time when the thread was
702
os_event_t event; /*!< event used in suspending the
703
thread when it has nothing to do */
704
que_thr_t* thr; /*!< suspended query thread (only
705
used for MySQL threads) */
708
/* Table for MySQL threads where they will be suspended to wait for locks */
709
UNIV_INTERN srv_slot_t* srv_mysql_table = NULL;
711
UNIV_INTERN os_event_t srv_lock_timeout_thread_event;
713
UNIV_INTERN srv_sys_t* srv_sys = NULL;
715
/* padding to prevent other memory update hotspots from residing on
716
the same memory cache line */
717
UNIV_INTERN byte srv_pad1[64];
718
/* mutex protecting the server, trx structs, query threads, and lock table */
719
UNIV_INTERN mutex_t* kernel_mutex_temp;
720
/* padding to prevent other memory update hotspots from residing on
721
the same memory cache line */
722
UNIV_INTERN byte srv_pad2[64];
725
/* The following three values measure the urgency of the jobs of
726
buffer, version, and insert threads. They may vary from 0 - 1000.
727
The server mutex protects all these variables. The low-water values
728
tell that the server can acquiesce the utility when the value
729
drops below this low-water mark. */
731
static ulint srv_meter[SRV_MASTER + 1];
732
static ulint srv_meter_low_water[SRV_MASTER + 1];
733
static ulint srv_meter_high_water[SRV_MASTER + 1];
734
static ulint srv_meter_high_water2[SRV_MASTER + 1];
735
static ulint srv_meter_foreground[SRV_MASTER + 1];
738
/* The following values give info about the activity going on in
739
the database. They are protected by the server mutex. The arrays
740
are indexed by the type of the thread. */
742
UNIV_INTERN ulint srv_n_threads_active[SRV_MASTER + 1];
743
UNIV_INTERN ulint srv_n_threads[SRV_MASTER + 1];
745
/***********************************************************************
746
Prints counters for work done by srv_master_thread. */
749
srv_print_master_thread_info(
750
/*=========================*/
751
FILE *file) /* in: output stream */
753
fprintf(file, "srv_master_thread loops: %lu 1_second, %lu sleeps, "
754
"%lu 10_second, %lu background, %lu flush\n",
755
srv_main_1_second_loops, srv_main_sleeps,
756
srv_main_10_second_loops, srv_main_background_loops,
757
srv_main_flush_loops);
758
fprintf(file, "srv_master_thread log flush and writes: %lu "
759
" log writes only: %lu\n",
760
srv_log_writes_and_flush, srv_log_buffer_writes);
763
/*********************************************************************//**
764
Sets the info describing an i/o thread current state. */
767
srv_set_io_thread_op_info(
768
/*======================*/
769
ulint i, /*!< in: the 'segment' of the i/o thread */
770
const char* str) /*!< in: constant char string describing the
773
ut_a(i < SRV_MAX_N_IO_THREADS);
775
srv_io_thread_op_info[i] = str;
778
/*********************************************************************//**
779
Accessor function to get pointer to n'th slot in the server thread
781
@return pointer to the slot */
784
srv_table_get_nth_slot(
785
/*===================*/
786
ulint index) /*!< in: index of the slot */
788
ut_a(index < OS_THREAD_MAX_N);
790
return(srv_sys->threads + index);
793
/*********************************************************************//**
794
Gets the number of threads in the system.
795
@return sum of srv_n_threads[] */
798
srv_get_n_threads(void)
799
/*===================*/
804
mutex_enter(&kernel_mutex);
806
for (i = SRV_COM; i < SRV_MASTER + 1; i++) {
808
n_threads += srv_n_threads[i];
811
mutex_exit(&kernel_mutex);
816
/*********************************************************************//**
817
Reserves a slot in the thread table for the current thread. Also creates the
818
thread local storage struct for the current thread. NOTE! The server mutex
819
has to be reserved by the caller!
820
@return reserved slot index */
823
srv_table_reserve_slot(
824
/*===================*/
825
enum srv_thread_type type) /*!< in: type of the thread */
831
ut_a(type <= SRV_MASTER);
834
slot = srv_table_get_nth_slot(i);
836
while (slot->in_use) {
838
slot = srv_table_get_nth_slot(i);
841
ut_a(slot->in_use == FALSE);
844
slot->suspended = FALSE;
846
slot->id = os_thread_get_curr_id();
847
slot->handle = os_thread_get_curr();
851
thr_local_set_slot_no(os_thread_get_curr_id(), i);
856
/*********************************************************************//**
857
Suspends the calling thread to wait for the event in its thread slot.
858
NOTE! The server mutex has to be reserved by the caller!
859
@return event for the calling thread to wait */
862
srv_suspend_thread(void)
863
/*====================*/
868
enum srv_thread_type type;
870
ut_ad(mutex_own(&kernel_mutex));
872
slot_no = thr_local_get_slot_no(os_thread_get_curr_id());
874
if (srv_print_thread_releases) {
876
"Suspending thread %lu to slot %lu\n",
877
(ulong) os_thread_get_curr_id(), (ulong) slot_no);
880
slot = srv_table_get_nth_slot(slot_no);
884
ut_ad(type >= SRV_WORKER);
885
ut_ad(type <= SRV_MASTER);
889
slot->suspended = TRUE;
891
ut_ad(srv_n_threads_active[type] > 0);
893
srv_n_threads_active[type]--;
895
os_event_reset(event);
900
/*********************************************************************//**
901
Releases threads of the type given from suspension in the thread table.
902
NOTE! The server mutex has to be reserved by the caller!
903
@return number of threads released: this may be less than n if not
904
enough threads were suspended at the moment */
909
enum srv_thread_type type, /*!< in: thread type */
910
ulint n) /*!< in: number of threads to release */
916
ut_ad(type >= SRV_WORKER);
917
ut_ad(type <= SRV_MASTER);
919
ut_ad(mutex_own(&kernel_mutex));
921
for (i = 0; i < OS_THREAD_MAX_N; i++) {
923
slot = srv_table_get_nth_slot(i);
925
if (slot->in_use && slot->type == type && slot->suspended) {
927
slot->suspended = FALSE;
929
srv_n_threads_active[type]++;
931
os_event_set(slot->event);
933
if (srv_print_thread_releases) {
935
"Releasing thread %lu type %lu"
937
(ulong) slot->id, (ulong) type,
952
/*********************************************************************//**
953
Returns the calling thread type.
954
@return SRV_COM, ... */
957
srv_get_thread_type(void)
958
/*=====================*/
962
enum srv_thread_type type;
964
mutex_enter(&kernel_mutex);
966
slot_no = thr_local_get_slot_no(os_thread_get_curr_id());
968
slot = srv_table_get_nth_slot(slot_no);
972
ut_ad(type >= SRV_WORKER);
973
ut_ad(type <= SRV_MASTER);
975
mutex_exit(&kernel_mutex);
980
/*********************************************************************//**
981
Initializes the server. */
987
srv_conc_slot_t* conc_slot;
991
srv_sys = mem_alloc(sizeof(srv_sys_t));
993
kernel_mutex_temp = mem_alloc(sizeof(mutex_t));
994
mutex_create(&kernel_mutex, SYNC_KERNEL);
996
mutex_create(&srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
998
srv_sys->threads = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));
1000
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1001
slot = srv_table_get_nth_slot(i);
1002
slot->in_use = FALSE;
1003
slot->type=0; /* Avoid purify errors */
1004
slot->event = os_event_create(NULL);
1008
srv_mysql_table = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));
1010
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1011
slot = srv_mysql_table + i;
1012
slot->in_use = FALSE;
1014
slot->event = os_event_create(NULL);
1018
srv_lock_timeout_thread_event = os_event_create(NULL);
1020
for (i = 0; i < SRV_MASTER + 1; i++) {
1021
srv_n_threads_active[i] = 0;
1022
srv_n_threads[i] = 0;
1025
srv_meter_low_water[i] = 50;
1026
srv_meter_high_water[i] = 100;
1027
srv_meter_high_water2[i] = 200;
1028
srv_meter_foreground[i] = 250;
1032
UT_LIST_INIT(srv_sys->tasks);
1034
/* Create dummy indexes for infimum and supremum records */
1038
/* Init the server concurrency restriction data structures */
1040
os_fast_mutex_init(&srv_conc_mutex);
1042
UT_LIST_INIT(srv_conc_queue);
1044
srv_conc_slots = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_conc_slot_t));
1046
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1047
conc_slot = srv_conc_slots + i;
1048
conc_slot->reserved = FALSE;
1049
conc_slot->event = os_event_create(NULL);
1050
ut_a(conc_slot->event);
1053
/* Initialize some INFORMATION SCHEMA internal structures */
1054
trx_i_s_cache_init(trx_i_s_cache);
1057
/*********************************************************************//**
1058
Frees the OS fast mutex created in srv_init(). */
1064
os_fast_mutex_free(&srv_conc_mutex);
1067
/*********************************************************************//**
1068
Initializes the synchronization primitives, memory system, and the thread
1072
srv_general_init(void)
1073
/*==================*/
1078
mem_init(srv_mem_pool_size);
1082
/*======================= InnoDB Server FIFO queue =======================*/
1084
/* Maximum allowable purge history length. <=0 means 'infinite'. */
1085
UNIV_INTERN ulong srv_max_purge_lag = 0;
1087
/*********************************************************************//**
1088
Puts an OS thread to wait if there are too many concurrent threads
1089
(>= srv_thread_concurrency) inside InnoDB. The threads wait in a FIFO queue. */
1092
srv_conc_enter_innodb(
1093
/*==================*/
1094
trx_t* trx) /*!< in: transaction object associated with the
1097
ibool has_slept = FALSE;
1098
srv_conc_slot_t* slot = NULL;
1101
if (trx->mysql_thd != NULL
1102
&& thd_is_replication_slave_thread(trx->mysql_thd)) {
1104
UT_WAIT_FOR(srv_conc_n_threads
1105
< (lint)srv_thread_concurrency,
1106
srv_replication_delay * 1000);
1111
/* If trx has 'free tickets' to enter the engine left, then use one
1114
if (trx->n_tickets_to_enter_innodb > 0) {
1115
trx->n_tickets_to_enter_innodb--;
1120
os_fast_mutex_lock(&srv_conc_mutex);
1122
if (trx->declared_to_be_inside_innodb) {
1123
ut_print_timestamp(stderr);
1124
fputs(" InnoDB: Error: trying to declare trx"
1125
" to enter InnoDB, but\n"
1126
"InnoDB: it already is declared.\n", stderr);
1127
trx_print(stderr, trx, 0);
1129
os_fast_mutex_unlock(&srv_conc_mutex);
1134
ut_ad(srv_conc_n_threads >= 0);
1136
if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
1138
srv_conc_n_threads++;
1139
trx->declared_to_be_inside_innodb = TRUE;
1140
trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
1142
os_fast_mutex_unlock(&srv_conc_mutex);
1147
/* If the transaction is not holding resources, let it sleep
1148
for SRV_THREAD_SLEEP_DELAY microseconds, and try again then */
1150
if (!has_slept && !trx->has_search_latch
1151
&& NULL == UT_LIST_GET_FIRST(trx->trx_locks)) {
1153
has_slept = TRUE; /* We let it sleep only once to avoid
1156
srv_conc_n_waiting_threads++;
1158
os_fast_mutex_unlock(&srv_conc_mutex);
1160
trx->op_info = "sleeping before joining InnoDB queue";
1162
/* Peter Zaitsev suggested that we take the sleep away
1163
altogether. But the sleep may be good in pathological
1164
situations of lots of thread switches. Simply put some
1165
threads aside for a while to reduce the number of thread
1167
if (SRV_THREAD_SLEEP_DELAY > 0) {
1168
os_thread_sleep(SRV_THREAD_SLEEP_DELAY);
1173
os_fast_mutex_lock(&srv_conc_mutex);
1175
srv_conc_n_waiting_threads--;
1180
/* Too many threads inside: put the current thread to a queue */
1182
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1183
slot = srv_conc_slots + i;
1185
if (!slot->reserved) {
1191
if (i == OS_THREAD_MAX_N) {
1192
/* Could not find a free wait slot, we must let the
1195
srv_conc_n_threads++;
1196
trx->declared_to_be_inside_innodb = TRUE;
1197
trx->n_tickets_to_enter_innodb = 0;
1199
os_fast_mutex_unlock(&srv_conc_mutex);
1204
/* Release possible search system latch this thread has */
1205
if (trx->has_search_latch) {
1206
trx_search_latch_release_if_reserved(trx);
1209
/* Add to the queue */
1210
slot->reserved = TRUE;
1211
slot->wait_ended = FALSE;
1213
UT_LIST_ADD_LAST(srv_conc_queue, srv_conc_queue, slot);
1215
os_event_reset(slot->event);
1217
srv_conc_n_waiting_threads++;
1219
os_fast_mutex_unlock(&srv_conc_mutex);
1221
/* Go to wait for the event; when a thread leaves InnoDB it will
1222
release this thread */
1224
trx->op_info = "waiting in InnoDB queue";
1226
os_event_wait(slot->event);
1230
os_fast_mutex_lock(&srv_conc_mutex);
1232
srv_conc_n_waiting_threads--;
1234
/* NOTE that the thread which released this thread already
1235
incremented the thread counter on behalf of this thread */
1237
slot->reserved = FALSE;
1239
UT_LIST_REMOVE(srv_conc_queue, srv_conc_queue, slot);
1241
trx->declared_to_be_inside_innodb = TRUE;
1242
trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
1244
os_fast_mutex_unlock(&srv_conc_mutex);
1247
/*********************************************************************//**
1248
This lets a thread enter InnoDB regardless of the number of threads inside
1249
InnoDB. This must be called when a thread ends a lock wait. */
1252
srv_conc_force_enter_innodb(
1253
/*========================*/
1254
trx_t* trx) /*!< in: transaction object associated with the
1257
if (UNIV_LIKELY(!srv_thread_concurrency)) {
1262
ut_ad(srv_conc_n_threads >= 0);
1264
os_fast_mutex_lock(&srv_conc_mutex);
1266
srv_conc_n_threads++;
1267
trx->declared_to_be_inside_innodb = TRUE;
1268
trx->n_tickets_to_enter_innodb = 1;
1270
os_fast_mutex_unlock(&srv_conc_mutex);
1273
/*********************************************************************//**
1274
This must be called when a thread exits InnoDB in a lock wait or at the
1275
end of an SQL statement. */
1278
srv_conc_force_exit_innodb(
1279
/*=======================*/
1280
trx_t* trx) /*!< in: transaction object associated with the
1283
srv_conc_slot_t* slot = NULL;
1285
if (trx->mysql_thd != NULL
1286
&& thd_is_replication_slave_thread(trx->mysql_thd)) {
1291
if (trx->declared_to_be_inside_innodb == FALSE) {
1296
os_fast_mutex_lock(&srv_conc_mutex);
1298
ut_ad(srv_conc_n_threads > 0);
1299
srv_conc_n_threads--;
1300
trx->declared_to_be_inside_innodb = FALSE;
1301
trx->n_tickets_to_enter_innodb = 0;
1303
if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
1304
/* Look for a slot where a thread is waiting and no other
1305
thread has yet released the thread */
1307
slot = UT_LIST_GET_FIRST(srv_conc_queue);
1309
while (slot && slot->wait_ended == TRUE) {
1310
slot = UT_LIST_GET_NEXT(srv_conc_queue, slot);
1314
slot->wait_ended = TRUE;
1316
/* We increment the count on behalf of the released
1319
srv_conc_n_threads++;
1323
os_fast_mutex_unlock(&srv_conc_mutex);
1326
os_event_set(slot->event);
1330
/*********************************************************************//**
1331
This must be called when a thread exits InnoDB. */
1334
srv_conc_exit_innodb(
1335
/*=================*/
1336
trx_t* trx) /*!< in: transaction object associated with the
1339
if (trx->n_tickets_to_enter_innodb > 0) {
1340
/* We will pretend the thread is still inside InnoDB though it
1341
now leaves the InnoDB engine. In this way we save
1342
a lot of semaphore operations. srv_conc_force_exit_innodb is
1343
used to declare the thread definitely outside InnoDB. It
1344
should be called when there is a lock wait or an SQL statement
1350
srv_conc_force_exit_innodb(trx);
1353
/*========================================================================*/
1355
/*********************************************************************//**
1356
Normalizes init parameter values to use units we use inside InnoDB.
1357
@return DB_SUCCESS or error code */
1360
srv_normalize_init_values(void)
1361
/*===========================*/
1366
n = srv_n_data_files;
1368
for (i = 0; i < n; i++) {
1369
srv_data_file_sizes[i] = srv_data_file_sizes[i]
1370
* ((1024 * 1024) / UNIV_PAGE_SIZE);
1373
srv_last_file_size_max = srv_last_file_size_max
1374
* ((1024 * 1024) / UNIV_PAGE_SIZE);
1376
srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;
1378
srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;
1380
srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
1385
/*********************************************************************//**
1386
Boots the InnoDB server.
1387
@return DB_SUCCESS or error code */
1395
/* Transform the init parameter values given by MySQL to
1396
use units we use inside InnoDB: */
1398
err = srv_normalize_init_values();
1400
if (err != DB_SUCCESS) {
1404
/* Initialize synchronization primitives, memory management, and thread
1409
/* Initialize this module */
1416
/*********************************************************************//**
1417
Reserves a slot in the thread table for the current MySQL OS thread.
1418
NOTE! The kernel mutex has to be reserved by the caller!
1419
@return reserved slot */
1422
srv_table_reserve_slot_for_mysql(void)
1423
/*==================================*/
1428
ut_ad(mutex_own(&kernel_mutex));
1431
slot = srv_mysql_table + i;
1433
while (slot->in_use) {
1436
if (i >= OS_THREAD_MAX_N) {
1438
ut_print_timestamp(stderr);
1441
" InnoDB: There appear to be %lu MySQL"
1442
" threads currently waiting\n"
1443
"InnoDB: inside InnoDB, which is the"
1444
" upper limit. Cannot continue operation.\n"
1445
"InnoDB: We intentionally generate"
1446
" a seg fault to print a stack trace\n"
1447
"InnoDB: on Linux. But first we print"
1448
" a list of waiting threads.\n", (ulong) i);
1450
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1452
slot = srv_mysql_table + i;
1455
"Slot %lu: thread id %lu, type %lu,"
1456
" in use %lu, susp %lu, time %lu\n",
1458
(ulong) os_thread_pf(slot->id),
1460
(ulong) slot->in_use,
1461
(ulong) slot->suspended,
1462
(ulong) difftime(ut_time(),
1463
slot->suspend_time));
1469
slot = srv_mysql_table + i;
1472
ut_a(slot->in_use == FALSE);
1474
slot->in_use = TRUE;
1475
slot->id = os_thread_get_curr_id();
1476
slot->handle = os_thread_get_curr();
1481
/***************************************************************//**
1482
Puts a MySQL OS thread to wait for a lock to be released. If an error
1483
occurs during the wait trx->error_state associated with thr is
1484
!= DB_SUCCESS when we return. DB_LOCK_WAIT_TIMEOUT and DB_DEADLOCK
1485
are possible errors. DB_DEADLOCK is returned if selective deadlock
1486
resolution chose this transaction as a victim. */
1489
srv_suspend_mysql_thread(
1490
/*=====================*/
1491
que_thr_t* thr) /*!< in: query thread associated with the MySQL
1498
ulint had_dict_lock;
1499
ibool was_declared_inside_innodb = FALSE;
1500
ib_int64_t start_time = 0;
1501
ib_int64_t finish_time;
1505
ulong lock_wait_timeout;
1507
ut_ad(!mutex_own(&kernel_mutex));
1509
trx = thr_get_trx(thr);
1511
os_event_set(srv_lock_timeout_thread_event);
1513
mutex_enter(&kernel_mutex);
1515
trx->error_state = DB_SUCCESS;
1517
if (thr->state == QUE_THR_RUNNING) {
1519
ut_ad(thr->is_active == TRUE);
1521
/* The lock has already been released or this transaction
1522
was chosen as a deadlock victim: no need to suspend */
1524
if (trx->was_chosen_as_deadlock_victim) {
1526
trx->error_state = DB_DEADLOCK;
1527
trx->was_chosen_as_deadlock_victim = FALSE;
1530
mutex_exit(&kernel_mutex);
1535
ut_ad(thr->is_active == FALSE);
1537
slot = srv_table_reserve_slot_for_mysql();
1539
event = slot->event;
1543
os_event_reset(event);
1545
slot->suspend_time = ut_time();
1547
if (thr->lock_state == QUE_THR_LOCK_ROW) {
1548
srv_n_lock_wait_count++;
1549
srv_n_lock_wait_current_count++;
1551
if (ut_usectime(&sec, &ms) == -1) {
1554
start_time = (ib_int64_t) sec * 1000000 + ms;
1557
/* Wake the lock timeout monitor thread, if it is suspended */
1559
os_event_set(srv_lock_timeout_thread_event);
1561
mutex_exit(&kernel_mutex);
1563
if (trx->declared_to_be_inside_innodb) {
1565
was_declared_inside_innodb = TRUE;
1567
/* We must declare this OS thread to exit InnoDB, since a
1568
possible other thread holding a lock which this thread waits
1569
for must be allowed to enter, sooner or later */
1571
srv_conc_force_exit_innodb(trx);
1574
had_dict_lock = trx->dict_operation_lock_mode;
1576
switch (had_dict_lock) {
1578
/* Release foreign key check latch */
1579
row_mysql_unfreeze_data_dictionary(trx);
1582
/* Release fast index creation latch */
1583
row_mysql_unlock_data_dictionary(trx);
1587
ut_a(trx->dict_operation_lock_mode == 0);
1589
/* Suspend this thread and wait for the event. */
1591
os_event_wait(event);
1593
/* After resuming, reacquire the data dictionary latch if
1596
switch (had_dict_lock) {
1598
row_mysql_freeze_data_dictionary(trx);
1601
row_mysql_lock_data_dictionary(trx);
1605
if (was_declared_inside_innodb) {
1607
/* Return back inside InnoDB */
1609
srv_conc_force_enter_innodb(trx);
1612
mutex_enter(&kernel_mutex);
1614
/* Release the slot for others to use */
1616
slot->in_use = FALSE;
1618
wait_time = ut_difftime(ut_time(), slot->suspend_time);
1620
if (thr->lock_state == QUE_THR_LOCK_ROW) {
1621
if (ut_usectime(&sec, &ms) == -1) {
1624
finish_time = (ib_int64_t) sec * 1000000 + ms;
1627
diff_time = (ulint) (finish_time - start_time);
1629
srv_n_lock_wait_current_count--;
1630
srv_n_lock_wait_time = srv_n_lock_wait_time + diff_time;
1631
if (diff_time > srv_n_lock_max_wait_time &&
1632
/* only update the variable if we successfully
1633
retrieved the start and finish times. See Bug#36819. */
1634
start_time != -1 && finish_time != -1) {
1635
srv_n_lock_max_wait_time = diff_time;
1639
if (trx->was_chosen_as_deadlock_victim) {
1641
trx->error_state = DB_DEADLOCK;
1642
trx->was_chosen_as_deadlock_victim = FALSE;
1645
mutex_exit(&kernel_mutex);
1647
/* InnoDB system transactions (such as the purge, and
1648
incomplete transactions that are being rolled back after crash
1649
recovery) will use the global value of
1650
innodb_lock_wait_timeout, because trx->mysql_thd == NULL. */
1651
lock_wait_timeout = thd_lock_wait_timeout(trx->mysql_thd);
1653
if (lock_wait_timeout < 100000000
1654
&& wait_time > (double) lock_wait_timeout) {
1656
trx->error_state = DB_LOCK_WAIT_TIMEOUT;
1660
/********************************************************************//**
1661
Releases a MySQL OS thread waiting for a lock to be released, if the
1662
thread is already suspended. */
1665
srv_release_mysql_thread_if_suspended(
1666
/*==================================*/
1667
que_thr_t* thr) /*!< in: query thread associated with the
1673
ut_ad(mutex_own(&kernel_mutex));
1675
for (i = 0; i < OS_THREAD_MAX_N; i++) {
1677
slot = srv_mysql_table + i;
1679
if (slot->in_use && slot->thr == thr) {
1682
os_event_set(slot->event);
1691
/******************************************************************//**
1692
Refreshes the values used to calculate per-second averages. */
1695
srv_refresh_innodb_monitor_stats(void)
1696
/*==================================*/
1698
mutex_enter(&srv_innodb_monitor_mutex);
1700
srv_last_monitor_time = time(NULL);
1702
os_aio_refresh_stats();
1704
btr_cur_n_sea_old = btr_cur_n_sea;
1705
btr_cur_n_non_sea_old = btr_cur_n_non_sea;
1707
log_refresh_stats();
1709
buf_refresh_io_stats();
1711
srv_n_rows_inserted_old = srv_n_rows_inserted;
1712
srv_n_rows_updated_old = srv_n_rows_updated;
1713
srv_n_rows_deleted_old = srv_n_rows_deleted;
1714
srv_n_rows_read_old = srv_n_rows_read;
1716
mutex_exit(&srv_innodb_monitor_mutex);
1719
/******************************************************************//**
1720
Outputs to a file the output of the InnoDB Monitor. */
1723
srv_printf_innodb_monitor(
1724
/*======================*/
1725
FILE* file, /*!< in: output stream */
1726
ulint* trx_start, /*!< out: file position of the start of
1727
the list of active transactions */
1728
ulint* trx_end) /*!< out: file position of the end of
1729
the list of active transactions */
1731
double time_elapsed;
1732
time_t current_time;
1735
mutex_enter(&srv_innodb_monitor_mutex);
1737
current_time = time(NULL);
1739
/* We add 0.001 seconds to time_elapsed to prevent division
1740
by zero if two users happen to call SHOW INNODB STATUS at the same
1743
time_elapsed = difftime(current_time, srv_last_monitor_time)
1746
srv_last_monitor_time = time(NULL);
1748
fputs("\n=====================================\n", file);
1750
ut_print_timestamp(file);
1752
" INNODB MONITOR OUTPUT\n"
1753
"=====================================\n"
1754
"Per second averages calculated from the last %lu seconds\n",
1755
(ulong)time_elapsed);
1757
fputs("----------\n"
1758
"BACKGROUND THREAD\n"
1759
"----------\n", file);
1760
srv_print_master_thread_info(file);
1762
fputs("----------\n"
1764
"----------\n", file);
1767
/* Conceptually, srv_innodb_monitor_mutex has a very high latching
1768
order level in sync0sync.h, while dict_foreign_err_mutex has a very
1769
low level 135. Therefore we can reserve the latter mutex here without
1770
a danger of a deadlock of threads. */
1772
mutex_enter(&dict_foreign_err_mutex);
1774
if (ftell(dict_foreign_err_file) != 0L) {
1775
fputs("------------------------\n"
1776
"LATEST FOREIGN KEY ERROR\n"
1777
"------------------------\n", file);
1778
ut_copy_file(file, dict_foreign_err_file);
1781
mutex_exit(&dict_foreign_err_mutex);
1783
lock_print_info_summary(file);
1785
long t = ftell(file);
1787
*trx_start = ULINT_UNDEFINED;
1789
*trx_start = (ulint) t;
1792
lock_print_info_all_transactions(file);
1794
long t = ftell(file);
1796
*trx_end = ULINT_UNDEFINED;
1798
*trx_end = (ulint) t;
1803
"--------\n", file);
1806
fputs("-------------------------------------\n"
1807
"INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
1808
"-------------------------------------\n", file);
1811
ha_print_info(file, btr_search_sys->hash_index);
1814
"%.2f hash searches/s, %.2f non-hash searches/s\n",
1815
(btr_cur_n_sea - btr_cur_n_sea_old)
1817
(btr_cur_n_non_sea - btr_cur_n_non_sea_old)
1819
btr_cur_n_sea_old = btr_cur_n_sea;
1820
btr_cur_n_non_sea_old = btr_cur_n_non_sea;
1827
fputs("----------------------\n"
1828
"BUFFER POOL AND MEMORY\n"
1829
"----------------------\n", file);
1831
"Total memory allocated " ULINTPF
1832
"; in additional pool allocated " ULINTPF "\n",
1833
ut_total_allocated_memory,
1834
mem_pool_get_reserved(mem_comm_pool));
1835
fprintf(file, "Dictionary memory allocated " ULINTPF "\n",
1840
fputs("--------------\n"
1842
"--------------\n", file);
1843
fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n",
1844
(long) srv_conc_n_threads,
1845
(ulong) srv_conc_n_waiting_threads);
1847
fprintf(file, "%lu read views open inside InnoDB\n",
1848
UT_LIST_GET_LEN(trx_sys->view_list));
1850
n_reserved = fil_space_get_n_reserved_extents(0);
1851
if (n_reserved > 0) {
1853
"%lu tablespace extents now reserved for"
1854
" B-tree split operations\n",
1855
(ulong) n_reserved);
1859
fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n",
1860
(ulong) srv_main_thread_process_no,
1861
(ulong) srv_main_thread_id,
1862
srv_main_thread_op_info);
1864
fprintf(file, "Main thread id %lu, state: %s\n",
1865
(ulong) srv_main_thread_id,
1866
srv_main_thread_op_info);
1869
"Number of rows inserted " ULINTPF
1870
", updated " ULINTPF ", deleted " ULINTPF
1871
", read " ULINTPF "\n",
1872
srv_n_rows_inserted,
1877
"%.2f inserts/s, %.2f updates/s,"
1878
" %.2f deletes/s, %.2f reads/s\n",
1879
(srv_n_rows_inserted - srv_n_rows_inserted_old)
1881
(srv_n_rows_updated - srv_n_rows_updated_old)
1883
(srv_n_rows_deleted - srv_n_rows_deleted_old)
1885
(srv_n_rows_read - srv_n_rows_read_old)
1888
srv_n_rows_inserted_old = srv_n_rows_inserted;
1889
srv_n_rows_updated_old = srv_n_rows_updated;
1890
srv_n_rows_deleted_old = srv_n_rows_deleted;
1891
srv_n_rows_read_old = srv_n_rows_read;
1893
fputs("----------------------------\n"
1894
"END OF INNODB MONITOR OUTPUT\n"
1895
"============================\n", file);
1896
mutex_exit(&srv_innodb_monitor_mutex);
1900
/******************************************************************//**
1901
Function to pass InnoDB status variables to MySQL */
1904
srv_export_innodb_status(void)
1905
/*==========================*/
1907
mutex_enter(&srv_innodb_monitor_mutex);
1909
export_vars.innodb_data_pending_reads
1910
= os_n_pending_reads;
1911
export_vars.innodb_data_pending_writes
1912
= os_n_pending_writes;
1913
export_vars.innodb_data_pending_fsyncs
1914
= fil_n_pending_log_flushes
1915
+ fil_n_pending_tablespace_flushes;
1916
export_vars.innodb_data_fsyncs = os_n_fsyncs;
1917
export_vars.innodb_data_read = srv_data_read;
1918
export_vars.innodb_data_reads = os_n_file_reads;
1919
export_vars.innodb_data_writes = os_n_file_writes;
1920
export_vars.innodb_data_written = srv_data_written;
1921
export_vars.innodb_buffer_pool_read_requests = buf_pool->n_page_gets;
1922
export_vars.innodb_buffer_pool_write_requests
1923
= srv_buf_pool_write_requests;
1924
export_vars.innodb_buffer_pool_wait_free = srv_buf_pool_wait_free;
1925
export_vars.innodb_buffer_pool_pages_flushed = srv_buf_pool_flushed;
1926
export_vars.innodb_buffer_pool_reads = srv_buf_pool_reads;
1927
export_vars.innodb_buffer_pool_read_ahead_rnd = srv_read_ahead_rnd;
1928
export_vars.innodb_buffer_pool_read_ahead_seq = srv_read_ahead_seq;
1929
export_vars.innodb_buffer_pool_pages_data
1930
= UT_LIST_GET_LEN(buf_pool->LRU);
1931
export_vars.innodb_buffer_pool_pages_dirty
1932
= UT_LIST_GET_LEN(buf_pool->flush_list);
1933
export_vars.innodb_buffer_pool_pages_free
1934
= UT_LIST_GET_LEN(buf_pool->free);
1936
export_vars.innodb_buffer_pool_pages_latched
1937
= buf_get_latched_pages_number();
1938
#endif /* UNIV_DEBUG */
1939
export_vars.innodb_buffer_pool_pages_total = buf_pool->curr_size;
1941
export_vars.innodb_buffer_pool_pages_misc = buf_pool->curr_size
1942
- UT_LIST_GET_LEN(buf_pool->LRU)
1943
- UT_LIST_GET_LEN(buf_pool->free);
1944
#ifdef HAVE_ATOMIC_BUILTINS
1945
export_vars.innodb_have_atomic_builtins = 1;
1947
export_vars.innodb_have_atomic_builtins = 0;
1949
export_vars.innodb_page_size = UNIV_PAGE_SIZE;
1950
export_vars.innodb_log_waits = srv_log_waits;
1951
export_vars.innodb_os_log_written = srv_os_log_written;
1952
export_vars.innodb_os_log_fsyncs = fil_n_log_flushes;
1953
export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes;
1954
export_vars.innodb_os_log_pending_writes = srv_os_log_pending_writes;
1955
export_vars.innodb_log_write_requests = srv_log_write_requests;
1956
export_vars.innodb_log_writes = srv_log_writes;
1957
export_vars.innodb_dblwr_pages_written = srv_dblwr_pages_written;
1958
export_vars.innodb_dblwr_writes = srv_dblwr_writes;
1959
export_vars.innodb_pages_created = buf_pool->n_pages_created;
1960
export_vars.innodb_pages_read = buf_pool->n_pages_read;
1961
export_vars.innodb_pages_written = buf_pool->n_pages_written;
1962
export_vars.innodb_row_lock_waits = srv_n_lock_wait_count;
1963
export_vars.innodb_row_lock_current_waits
1964
= srv_n_lock_wait_current_count;
1965
export_vars.innodb_row_lock_time = srv_n_lock_wait_time / 1000;
1966
if (srv_n_lock_wait_count > 0) {
1967
export_vars.innodb_row_lock_time_avg = (ulint)
1968
(srv_n_lock_wait_time / 1000 / srv_n_lock_wait_count);
1970
export_vars.innodb_row_lock_time_avg = 0;
1972
export_vars.innodb_row_lock_time_max
1973
= srv_n_lock_max_wait_time / 1000;
1974
export_vars.innodb_rows_read = srv_n_rows_read;
1975
export_vars.innodb_rows_inserted = srv_n_rows_inserted;
1976
export_vars.innodb_rows_updated = srv_n_rows_updated;
1977
export_vars.innodb_rows_deleted = srv_n_rows_deleted;
1979
mutex_exit(&srv_innodb_monitor_mutex);
1982
/*********************************************************************//**
1983
A thread which wakes up threads whose lock wait may have lasted too long.
1984
This also prints the info output by various InnoDB monitors.
1985
@return a dummy parameter */
1988
srv_lock_timeout_and_monitor_thread(
1989
/*================================*/
1990
void* arg __attribute__((unused)))
1991
/*!< in: a dummy parameter required by
1995
double time_elapsed;
1996
time_t current_time;
1997
time_t last_table_monitor_time;
1998
time_t last_tablespace_monitor_time;
1999
time_t last_monitor_time;
2004
#ifdef UNIV_DEBUG_THREAD_CREATION
2005
fprintf(stderr, "Lock timeout thread starts, id %lu\n",
2006
os_thread_pf(os_thread_get_curr_id()));
2009
srv_last_monitor_time = time(NULL);
2010
last_table_monitor_time = time(NULL);
2011
last_tablespace_monitor_time = time(NULL);
2012
last_monitor_time = time(NULL);
2014
srv_lock_timeout_and_monitor_active = TRUE;
2016
/* When someone is waiting for a lock, we wake up every second
2017
and check if a timeout has passed for a lock wait */
2019
os_thread_sleep(1000000);
2021
current_time = time(NULL);
2023
time_elapsed = difftime(current_time, last_monitor_time);
2025
if (time_elapsed > 15) {
2026
last_monitor_time = time(NULL);
2028
if (srv_print_innodb_monitor) {
2029
srv_printf_innodb_monitor(stderr, NULL, NULL);
2032
if (srv_innodb_status) {
2033
mutex_enter(&srv_monitor_file_mutex);
2034
rewind(srv_monitor_file);
2035
srv_printf_innodb_monitor(srv_monitor_file, NULL,
2037
os_file_set_eof(srv_monitor_file);
2038
mutex_exit(&srv_monitor_file_mutex);
2041
if (srv_print_innodb_tablespace_monitor
2042
&& difftime(current_time,
2043
last_tablespace_monitor_time) > 60) {
2044
last_tablespace_monitor_time = time(NULL);
2046
fputs("========================"
2047
"========================\n",
2050
ut_print_timestamp(stderr);
2052
fputs(" INNODB TABLESPACE MONITOR OUTPUT\n"
2053
"========================"
2054
"========================\n",
2058
fputs("Validating tablespace\n", stderr);
2060
fputs("Validation ok\n"
2061
"---------------------------------------\n"
2062
"END OF INNODB TABLESPACE MONITOR OUTPUT\n"
2063
"=======================================\n",
2067
if (srv_print_innodb_table_monitor
2068
&& difftime(current_time, last_table_monitor_time) > 60) {
2070
last_table_monitor_time = time(NULL);
2072
fputs("===========================================\n",
2075
ut_print_timestamp(stderr);
2077
fputs(" INNODB TABLE MONITOR OUTPUT\n"
2078
"===========================================\n",
2082
fputs("-----------------------------------\n"
2083
"END OF INNODB TABLE MONITOR OUTPUT\n"
2084
"==================================\n",
2089
mutex_enter(&kernel_mutex);
2093
/* Check of all slots if a thread is waiting there, and if it
2094
has exceeded the time limit */
2096
for (i = 0; i < OS_THREAD_MAX_N; i++) {
2098
slot = srv_mysql_table + i;
2102
ulong lock_wait_timeout;
2106
wait_time = ut_difftime(ut_time(), slot->suspend_time);
2108
trx = thr_get_trx(slot->thr);
2109
lock_wait_timeout = thd_lock_wait_timeout(
2112
if (lock_wait_timeout < 100000000
2113
&& (wait_time > (double) lock_wait_timeout
2114
|| wait_time < 0)) {
2116
/* Timeout exceeded or a wrap-around in system
2117
time counter: cancel the lock request queued
2118
by the transaction and release possible
2119
other transactions waiting behind; it is
2120
possible that the lock has already been
2121
granted: in that case do nothing */
2123
if (trx->wait_lock) {
2124
lock_cancel_waiting_and_release(
2131
os_event_reset(srv_lock_timeout_thread_event);
2133
mutex_exit(&kernel_mutex);
2135
if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
2139
if (some_waits || srv_print_innodb_monitor
2140
|| srv_print_innodb_lock_monitor
2141
|| srv_print_innodb_tablespace_monitor
2142
|| srv_print_innodb_table_monitor) {
2146
/* No one was waiting for a lock and no monitor was active:
2147
suspend this thread */
2149
srv_lock_timeout_and_monitor_active = FALSE;
2152
/* The following synchronisation is disabled, since
2153
the InnoDB monitor output is to be updated every 15 seconds. */
2154
os_event_wait(srv_lock_timeout_thread_event);
2159
srv_lock_timeout_and_monitor_active = FALSE;
2161
/* We count the number of threads in os_thread_exit(). A created
2162
thread should always use that to exit and not use return() to exit. */
2164
os_thread_exit(NULL);
2166
OS_THREAD_DUMMY_RETURN;
2169
/*********************************************************************//**
2170
A thread which prints warnings about semaphore waits which have lasted
2171
too long. These can be used to track bugs which cause hangs.
2172
@return a dummy parameter */
2175
srv_error_monitor_thread(
2176
/*=====================*/
2177
void* arg __attribute__((unused)))
2178
/*!< in: a dummy parameter required by
2181
/* number of successive fatal timeouts observed */
2182
ulint fatal_cnt = 0;
2183
ib_uint64_t old_lsn;
2184
ib_uint64_t new_lsn;
2186
old_lsn = srv_start_lsn;
2188
#ifdef UNIV_DEBUG_THREAD_CREATION
2189
fprintf(stderr, "Error monitor thread starts, id %lu\n",
2190
os_thread_pf(os_thread_get_curr_id()));
2193
srv_error_monitor_active = TRUE;
2195
/* Try to track a strange bug reported by Harald Fuchs and others,
2196
where the lsn seems to decrease at times */
2198
new_lsn = log_get_lsn();
2200
if (new_lsn < old_lsn) {
2201
ut_print_timestamp(stderr);
2203
" InnoDB: Error: old log sequence number %"PRIu64""
2205
"InnoDB: than the new log sequence number %"PRIu64"!\n"
2206
"InnoDB: Please submit a bug report"
2207
" to http://bugs.mysql.com\n",
2213
if (difftime(time(NULL), srv_last_monitor_time) > 60) {
2214
/* We referesh InnoDB Monitor values so that averages are
2215
printed from at most 60 last seconds */
2217
srv_refresh_innodb_monitor_stats();
2220
/* Update the statistics collected for deciding LRU
2222
buf_LRU_stat_update();
2224
/* Update the statistics collected for flush rate policy. */
2225
buf_flush_stat_update();
2227
/* In case mutex_exit is not a memory barrier, it is
2228
theoretically possible some threads are left waiting though
2229
the semaphore is already released. Wake up those threads: */
2231
sync_arr_wake_threads_if_sema_free();
2233
if (sync_array_print_long_waits()) {
2235
if (fatal_cnt > 10) {
2238
"InnoDB: Error: semaphore wait has lasted"
2240
"InnoDB: We intentionally crash the server,"
2241
" because it appears to be hung.\n",
2242
(ulong) srv_fatal_semaphore_wait_threshold);
2250
/* Flush stderr so that a database user gets the output
2251
to possible MySQL error file */
2255
os_thread_sleep(1000000);
2257
if (srv_shutdown_state < SRV_SHUTDOWN_CLEANUP) {
2262
srv_error_monitor_active = FALSE;
2264
/* We count the number of threads in os_thread_exit(). A created
2265
thread should always use that to exit and not use return() to exit. */
2267
os_thread_exit(NULL);
2269
OS_THREAD_DUMMY_RETURN;
2272
/*******************************************************************//**
2273
Tells the InnoDB server that there has been activity in the database
2274
and wakes up the master thread if it is suspended (not sleeping). Used
2275
in the MySQL interface. Note that there is a small chance that the master
2276
thread stays suspended (we do not protect our operation with the kernel
2277
mutex, for performace reasons). */
2280
srv_active_wake_master_thread(void)
2281
/*===============================*/
2283
srv_activity_count++;
2285
if (srv_n_threads_active[SRV_MASTER] == 0) {
2287
mutex_enter(&kernel_mutex);
2289
srv_release_threads(SRV_MASTER, 1);
2291
mutex_exit(&kernel_mutex);
2295
/*******************************************************************//**
2296
Wakes up the master thread if it is suspended or being suspended. */
2299
srv_wake_master_thread(void)
2300
/*========================*/
2302
srv_activity_count++;
2304
mutex_enter(&kernel_mutex);
2306
srv_release_threads(SRV_MASTER, 1);
2308
mutex_exit(&kernel_mutex);
2311
/**********************************************************************
2312
The master thread is tasked to ensure that flush of log file happens
2313
once every second in the background. This is to ensure that not more
2314
than one second of trxs are lost in case of crash when
2315
innodb_flush_logs_at_trx_commit != 1 */
2318
srv_sync_log_buffer_in_background(void)
2319
/*===================================*/
2321
time_t current_time = time(NULL);
2323
srv_main_thread_op_info = "flushing log";
2324
if (difftime(current_time, srv_last_log_flush_time) >= 1) {
2325
log_buffer_sync_in_background(TRUE);
2326
srv_last_log_flush_time = current_time;
2327
srv_log_writes_and_flush++;
2329
/* Actually we don't need to write logs here.
2330
We are just being extra safe here by forcing
2331
the log buffer to log file. */
2332
log_buffer_sync_in_background(FALSE);
2333
srv_log_buffer_writes++;
2337
/*********************************************************************//**
2338
The master thread controlling the server.
2339
@return a dummy parameter */
2344
void* arg __attribute__((unused)))
2345
/*!< in: a dummy parameter required by
2349
ulint old_activity_count;
2350
ulint n_pages_purged = 0;
2351
ulint n_bytes_merged;
2352
ulint n_pages_flushed;
2353
ulint n_bytes_archived;
2354
ulint n_tables_to_drop;
2357
ulint n_ios_very_old;
2359
ibool skip_sleep = FALSE;
2362
#ifdef UNIV_DEBUG_THREAD_CREATION
2363
fprintf(stderr, "Master thread starts, id %lu\n",
2364
os_thread_pf(os_thread_get_curr_id()));
2366
srv_main_thread_process_no = os_proc_get_number();
2367
srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());
2369
srv_table_reserve_slot(SRV_MASTER);
2371
mutex_enter(&kernel_mutex);
2373
srv_n_threads_active[SRV_MASTER]++;
2375
mutex_exit(&kernel_mutex);
2378
/*****************************************************************/
2379
/* ---- When there is database activity by users, we cycle in this
2382
srv_main_thread_op_info = "reserving kernel mutex";
2384
n_ios_very_old = log_sys->n_log_ios + buf_pool->n_pages_read
2385
+ buf_pool->n_pages_written;
2386
mutex_enter(&kernel_mutex);
2388
/* Store the user activity counter at the start of this loop */
2389
old_activity_count = srv_activity_count;
2391
mutex_exit(&kernel_mutex);
2393
if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
2395
goto suspend_thread;
2398
/* ---- We run the following loop approximately once per second
2399
when there is database activity */
2401
srv_last_log_flush_time = time(NULL);
2404
for (i = 0; i < 10; i++) {
2405
n_ios_old = log_sys->n_log_ios + buf_pool->n_pages_read
2406
+ buf_pool->n_pages_written;
2407
srv_main_thread_op_info = "sleeping";
2408
srv_main_1_second_loops++;
2412
os_thread_sleep(1000000);
2418
/* ALTER TABLE in MySQL requires on Unix that the table handler
2419
can drop tables lazily after there no longer are SELECT
2422
srv_main_thread_op_info = "doing background drop tables";
2424
row_drop_tables_for_mysql_in_background();
2426
srv_main_thread_op_info = "";
2428
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2430
goto background_loop;
2433
/* Flush logs if needed */
2434
srv_sync_log_buffer_in_background();
2436
srv_main_thread_op_info = "making checkpoint";
2439
/* If i/os during one second sleep were less than 5% of
2440
capacity, we assume that there is free disk i/o capacity
2441
available, and it makes sense to do an insert buffer merge. */
2443
n_pend_ios = buf_get_n_pending_ios()
2444
+ log_sys->n_pending_writes;
2445
n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
2446
+ buf_pool->n_pages_written;
2447
if (n_pend_ios < SRV_PEND_IO_THRESHOLD
2448
&& (n_ios - n_ios_old < SRV_RECENT_IO_ACTIVITY)) {
2449
srv_main_thread_op_info = "doing insert buffer merge";
2450
ibuf_contract_for_n_pages(FALSE, PCT_IO(5));
2452
/* Flush logs if needed */
2453
srv_sync_log_buffer_in_background();
2456
if (UNIV_UNLIKELY(buf_get_modified_ratio_pct()
2457
> srv_max_buf_pool_modified_pct)) {
2459
/* Try to keep the number of modified pages in the
2460
buffer pool under the limit wished by the user */
2462
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2466
/* If we had to do the flush, it may have taken
2467
even more than 1 second, and also, there may be more
2468
to flush. Do not sleep 1 second during the next
2469
iteration of this loop. */
2472
} else if (srv_adaptive_flushing) {
2474
/* Try to keep the rate of flushing of dirty
2475
pages such that redo log generation does not
2476
produce bursts of IO at checkpoint time. */
2477
ulint n_flush = buf_flush_get_desired_flush_rate();
2480
n_flush = ut_min(PCT_IO(100), n_flush);
2490
if (srv_activity_count == old_activity_count) {
2492
/* There is no user activity at the moment, go to
2493
the background loop */
2495
goto background_loop;
2499
/* ---- We perform the following code approximately once per
2500
10 seconds when there is database activity */
2502
#ifdef MEM_PERIODIC_CHECK
2503
/* Check magic numbers of every allocated mem block once in 10
2505
mem_validate_all_blocks();
2507
/* If i/os during the 10 second period were less than 200% of
2508
capacity, we assume that there is free disk i/o capacity
2509
available, and it makes sense to flush srv_io_capacity pages.
2511
Note that this is done regardless of the fraction of dirty
2512
pages relative to the max requested by the user. The one second
2513
loop above requests writes for that case. The writes done here
2514
are not required, and may be disabled. */
2516
n_pend_ios = buf_get_n_pending_ios() + log_sys->n_pending_writes;
2517
n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
2518
+ buf_pool->n_pages_written;
2520
srv_main_10_second_loops++;
2521
if (n_pend_ios < SRV_PEND_IO_THRESHOLD
2522
&& (n_ios - n_ios_very_old < SRV_PAST_IO_ACTIVITY)) {
2524
srv_main_thread_op_info = "flushing buffer pool pages";
2525
buf_flush_batch(BUF_FLUSH_LIST, PCT_IO(100),
2528
/* Flush logs if needed */
2529
srv_sync_log_buffer_in_background();
2532
/* We run a batch of insert buffer merge every 10 seconds,
2533
even if the server were active */
2535
srv_main_thread_op_info = "doing insert buffer merge";
2536
ibuf_contract_for_n_pages(FALSE, PCT_IO(5));
2538
/* Flush logs if needed */
2539
srv_sync_log_buffer_in_background();
2541
/* We run a full purge every 10 seconds, even if the server
2545
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2547
goto background_loop;
2550
srv_main_thread_op_info = "purging";
2551
n_pages_purged = trx_purge();
2553
/* Flush logs if needed */
2554
srv_sync_log_buffer_in_background();
2556
} while (n_pages_purged);
2558
srv_main_thread_op_info = "flushing buffer pool pages";
2560
/* Flush a few oldest pages to make a new checkpoint younger */
2562
if (buf_get_modified_ratio_pct() > 70) {
2564
/* If there are lots of modified pages in the buffer pool
2565
(> 70 %), we assume we can afford reserving the disk(s) for
2566
the time it requires to flush 100 pages */
2568
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2572
/* Otherwise, we only flush a small number of pages so that
2573
we do not unnecessarily use much disk i/o capacity from
2576
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2581
srv_main_thread_op_info = "making checkpoint";
2583
/* Make a new checkpoint about once in 10 seconds */
2585
log_checkpoint(TRUE, FALSE);
2587
srv_main_thread_op_info = "reserving kernel mutex";
2589
mutex_enter(&kernel_mutex);
2591
/* ---- When there is database activity, we jump from here back to
2592
the start of loop */
2594
if (srv_activity_count != old_activity_count) {
2595
mutex_exit(&kernel_mutex);
2599
mutex_exit(&kernel_mutex);
2601
/* If the database is quiet, we enter the background loop */
2603
/*****************************************************************/
2605
/* ---- In this loop we run background operations when the server
2606
is quiet from user activity. Also in the case of a shutdown, we
2607
loop here, flushing the buffer pool to the data files. */
2609
/* The server has been quiet for a while: start running background
2611
srv_main_background_loops++;
2612
srv_main_thread_op_info = "doing background drop tables";
2614
n_tables_to_drop = row_drop_tables_for_mysql_in_background();
2616
if (n_tables_to_drop > 0) {
2617
/* Do not monopolize the CPU even if there are tables waiting
2618
in the background drop queue. (It is essentially a bug if
2619
MySQL tries to drop a table while there are still open handles
2620
to it and we had to put it to the background drop queue.) */
2622
os_thread_sleep(100000);
2625
srv_main_thread_op_info = "purging";
2627
/* Run a full purge */
2629
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2634
srv_main_thread_op_info = "purging";
2635
n_pages_purged = trx_purge();
2637
/* Flush logs if needed */
2638
srv_sync_log_buffer_in_background();
2640
} while (n_pages_purged);
2642
srv_main_thread_op_info = "reserving kernel mutex";
2644
mutex_enter(&kernel_mutex);
2645
if (srv_activity_count != old_activity_count) {
2646
mutex_exit(&kernel_mutex);
2649
mutex_exit(&kernel_mutex);
2651
srv_main_thread_op_info = "doing insert buffer merge";
2653
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2656
/* This should do an amount of IO similar to the number of
2657
dirty pages that will be flushed in the call to
2658
buf_flush_batch below. Otherwise, the system favors
2659
clean pages over cleanup throughput. */
2660
n_bytes_merged = ibuf_contract_for_n_pages(FALSE,
2664
srv_main_thread_op_info = "reserving kernel mutex";
2666
mutex_enter(&kernel_mutex);
2667
if (srv_activity_count != old_activity_count) {
2668
mutex_exit(&kernel_mutex);
2671
mutex_exit(&kernel_mutex);
2674
srv_main_thread_op_info = "flushing buffer pool pages";
2675
srv_main_flush_loops++;
2676
if (srv_fast_shutdown < 2) {
2677
n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST,
2681
/* In the fastest shutdown we do not flush the buffer pool
2682
to data files: we set n_pages_flushed to 0 artificially. */
2684
n_pages_flushed = 0;
2687
srv_main_thread_op_info = "reserving kernel mutex";
2689
mutex_enter(&kernel_mutex);
2690
if (srv_activity_count != old_activity_count) {
2691
mutex_exit(&kernel_mutex);
2694
mutex_exit(&kernel_mutex);
2696
srv_main_thread_op_info = "waiting for buffer pool flush to end";
2697
buf_flush_wait_batch_end(BUF_FLUSH_LIST);
2699
/* Flush logs if needed */
2700
srv_sync_log_buffer_in_background();
2702
srv_main_thread_op_info = "making checkpoint";
2704
log_checkpoint(TRUE, FALSE);
2706
if (buf_get_modified_ratio_pct() > srv_max_buf_pool_modified_pct) {
2708
/* Try to keep the number of modified pages in the
2709
buffer pool under the limit wished by the user */
2714
srv_main_thread_op_info = "reserving kernel mutex";
2716
mutex_enter(&kernel_mutex);
2717
if (srv_activity_count != old_activity_count) {
2718
mutex_exit(&kernel_mutex);
2721
mutex_exit(&kernel_mutex);
2723
srv_main_thread_op_info = "archiving log (if log archive is on)";
2725
log_archive_do(FALSE, &n_bytes_archived);
2727
n_bytes_archived = 0;
2729
/* Keep looping in the background loop if still work to do */
2731
if (srv_fast_shutdown && srv_shutdown_state > 0) {
2732
if (n_tables_to_drop + n_pages_flushed
2733
+ n_bytes_archived != 0) {
2735
/* If we are doing a fast shutdown (= the default)
2736
we do not do purge or insert buffer merge. But we
2737
flush the buffer pool completely to disk.
2738
In a 'very fast' shutdown we do not flush the buffer
2739
pool to data files: we have set n_pages_flushed to
2742
goto background_loop;
2744
} else if (n_tables_to_drop
2745
+ n_pages_purged + n_bytes_merged + n_pages_flushed
2746
+ n_bytes_archived != 0) {
2747
/* In a 'slow' shutdown we run purge and the insert buffer
2748
merge to completion */
2750
goto background_loop;
2753
/* There is no work for background operations either: suspend
2754
master thread to wait for more server activity */
2757
srv_main_thread_op_info = "suspending";
2759
mutex_enter(&kernel_mutex);
2761
if (row_get_background_drop_list_len_low() > 0) {
2762
mutex_exit(&kernel_mutex);
2767
event = srv_suspend_thread();
2769
mutex_exit(&kernel_mutex);
2771
/* DO NOT CHANGE THIS STRING. innobase_start_or_create_for_mysql()
2772
waits for database activity to die down when converting < 4.1.x
2773
databases, and relies on this string being exactly as it is. InnoDB
2774
manual also mentions this string in several places. */
2775
srv_main_thread_op_info = "waiting for server activity";
2777
os_event_wait(event);
2779
if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
2780
/* This is only extra safety, the thread should exit
2781
already when the event wait ends */
2783
os_thread_exit(NULL);
2786
/* When there is user activity, InnoDB will set the event and the
2787
main thread goes back to loop. */
2792
#if (!defined(__SUNPRO_C) && !defined(__SUNPRO_CC))
2793
OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */