srv0srv.c 92.6 KB
Newer Older
1 2
/*****************************************************************************

3
Copyright (c) 1995, 2010, Innobase Oy. All Rights Reserved.
4
Copyright (c) 2008, 2009 Google Inc.
5
Copyright (c) 2009, Percona Inc.
6 7 8 9 10 11 12

Portions of this file contain modifications contributed and copyrighted by
Google, Inc. Those modifications are gratefully acknowledged and are described
briefly in the InnoDB documentation. The contributions by Google are
incorporated with their permission, and subject to the conditions contained in
the file COPYING.Google.

13 14 15 16 17 18 19
Portions of this file contain modifications contributed and copyrighted
by Percona Inc.. Those modifications are
gratefully acknowledged and are described briefly in the InnoDB
documentation. The contributions by Percona Inc. are incorporated with
their permission, and subject to the conditions contained in the file
COPYING.Percona.

20 21 22 23 24 25 26 27 28 29 30 31 32 33
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA

*****************************************************************************/

34 35
/**************************************************//**
@file srv/srv0srv.c
osku's avatar
osku committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
The database server main program

NOTE: SQL Server 7 uses something which the documentation
calls user mode scheduled threads (UMS threads). One such
thread is usually allocated per processor. Win32
documentation does not know any UMS threads, which suggests
that the concept is internal to SQL Server 7. It may mean that
SQL Server 7 does all the scheduling of threads itself, even
in i/o waits. We should maybe modify InnoDB to use the same
technique, because thread switches within NT may be too slow.

SQL Server 7 also mentions fibers, which are cooperatively
scheduled threads. They can boost performance by 5 %,
according to the Delaney and Soukup's book.

Windows 2000 will have something called thread pooling
(see msdn website), which we could possibly use.

Another possibility could be to use some very fast user space
thread library. This might confuse NT though.

Created 10/8/1995 Heikki Tuuri
*******************************************************/
59

osku's avatar
osku committed
60 61 62 63
/* Dummy comment */
#include "srv0srv.h"

#include "ut0mem.h"
64
#include "ut0ut.h"
osku's avatar
osku committed
65 66 67 68 69 70 71 72 73 74 75 76 77
#include "os0proc.h"
#include "mem0mem.h"
#include "mem0pool.h"
#include "sync0sync.h"
#include "thr0loc.h"
#include "que0que.h"
#include "log0recv.h"
#include "pars0pars.h"
#include "usr0sess.h"
#include "lock0lock.h"
#include "trx0purge.h"
#include "ibuf0ibuf.h"
#include "buf0flu.h"
78
#include "buf0lru.h"
osku's avatar
osku committed
79 80 81 82 83
#include "btr0sea.h"
#include "dict0load.h"
#include "dict0boot.h"
#include "srv0start.h"
#include "row0mysql.h"
84
#include "ha_prototypes.h"
85
#include "trx0i_s.h"
86
#include "os0sync.h" /* for HAVE_ATOMIC_BUILTINS */
osku's avatar
osku committed
87 88 89

/* This is set to TRUE if the MySQL user has set it in MySQL; currently
affects only FOREIGN KEY definition parsing */
90
UNIV_INTERN ibool	srv_lower_case_table_names	= FALSE;
osku's avatar
osku committed
91 92

/* The following is the maximum allowed duration of a lock wait. */
93
UNIV_INTERN ulint	srv_fatal_semaphore_wait_threshold = 600;
osku's avatar
osku committed
94 95 96

/* How much data manipulation language (DML) statements need to be delayed,
in microseconds, in order to reduce the lagging of the purge thread. */
97
UNIV_INTERN ulint	srv_dml_needed_delay = 0;
osku's avatar
osku committed
98

99 100
UNIV_INTERN ibool	srv_lock_timeout_active = FALSE;
UNIV_INTERN ibool	srv_monitor_active = FALSE;
101
UNIV_INTERN ibool	srv_error_monitor_active = FALSE;
osku's avatar
osku committed
102

103
UNIV_INTERN const char*	srv_main_thread_op_info = "";
osku's avatar
osku committed
104

105
/** Prefix used by MySQL to indicate pre-5.1 table name encoding */
106
UNIV_INTERN const char	srv_mysql50_table_name_prefix[9] = "#mysql50#";
107

osku's avatar
osku committed
108 109 110 111 112
/* Server parameters which are read from the initfile */

/* The following three are dir paths which are catenated before file
names, where the file name itself may also contain a path */

113
UNIV_INTERN char*	srv_data_home	= NULL;
osku's avatar
osku committed
114
#ifdef UNIV_LOG_ARCHIVE
115
UNIV_INTERN char*	srv_arch_dir	= NULL;
osku's avatar
osku committed
116 117
#endif /* UNIV_LOG_ARCHIVE */

118
/** store to its own file each table created by an user; data
119
dictionary tables are in the system tablespace 0 */
120
UNIV_INTERN my_bool	srv_file_per_table;
121
/** The file format to use on new *.ibd files. */
122
UNIV_INTERN ulint	srv_file_format = 0;
123
/** Whether to check file format during startup.  A value of
124 125 126 127 128 129 130
DICT_TF_FORMAT_MAX + 1 means no checking ie. FALSE.  The default is to
set it to the highest format we support. */
UNIV_INTERN ulint	srv_check_file_format_at_startup = DICT_TF_FORMAT_MAX;

#if DICT_TF_FORMAT_51
# error "DICT_TF_FORMAT_51 must be 0!"
#endif
131
/** Place locks to records only i.e. do not use next-key locking except
132 133
on duplicate key checking and foreign key checking */
UNIV_INTERN ibool	srv_locks_unsafe_for_binlog = FALSE;
134

inaam's avatar
inaam committed
135 136 137 138 139 140
/* If this flag is TRUE, then we will use the native aio of the
OS (provided we compiled Innobase with it in), otherwise we will
use simulated aio we build below with threads.
Currently we support native aio on windows and linux */
UNIV_INTERN my_bool	srv_use_native_aio = TRUE;

141 142 143 144 145 146 147 148 149 150 151 152 153 154
UNIV_INTERN ulint	srv_n_data_files = 0;
UNIV_INTERN char**	srv_data_file_names = NULL;
/* size in database pages */
UNIV_INTERN ulint*	srv_data_file_sizes = NULL;

/* if TRUE, then we auto-extend the last data file */
UNIV_INTERN ibool	srv_auto_extend_last_data_file	= FALSE;
/* if != 0, this tells the max size auto-extending may increase the
last data file size */
UNIV_INTERN ulint	srv_last_file_size_max	= 0;
/* If the last data file is auto-extended, we add this
many pages to it at a time */
UNIV_INTERN ulong	srv_auto_extend_increment = 8;
UNIV_INTERN ulint*	srv_data_file_is_raw_partition = NULL;
osku's avatar
osku committed
155 156 157 158

/* If the following is TRUE we do not allow inserts etc. This protects
the user from forgetting the 'newraw' keyword to my.cnf */

159 160 161 162 163 164 165
UNIV_INTERN ibool	srv_created_new_raw	= FALSE;

UNIV_INTERN char**	srv_log_group_home_dirs = NULL;

UNIV_INTERN ulint	srv_n_log_groups	= ULINT_MAX;
UNIV_INTERN ulint	srv_n_log_files		= ULINT_MAX;
/* size in database pages */
inaam's avatar
inaam committed
166
UNIV_INTERN ulint	srv_log_file_size	= ULINT_MAX;
167 168 169 170
/* size in database pages */
UNIV_INTERN ulint	srv_log_buffer_size	= ULINT_MAX;
UNIV_INTERN ulong	srv_flush_log_at_trx_commit = 1;

171 172 173 174
/* Try to flush dirty pages so as to avoid IO bursts at
the checkpoints. */
UNIV_INTERN char	srv_adaptive_flushing	= TRUE;

175 176 177 178 179 180 181 182 183 184 185
/** Maximum number of times allowed to conditionally acquire
mutex before switching to blocking wait on the mutex */
#define MAX_MUTEX_NOWAIT	20

/** Check whether the number of failed nonblocking mutex
acquisition attempts exceeds maximum allowed value. If so,
srv_printf_innodb_monitor() will request mutex acquisition
with mutex_enter(), which will wait until it gets the mutex. */
#define MUTEX_NOWAIT(mutex_skipped)	((mutex_skipped) < MAX_MUTEX_NOWAIT)

/** The sort order table of the MySQL latin1_swedish_ci character set
186 187
collation */
UNIV_INTERN const byte*	srv_latin1_ordering;
188

189
/* use os/external memory allocator */
190
UNIV_INTERN my_bool	srv_use_sys_malloc	= TRUE;
191
/* requested size in kilobytes */
192
UNIV_INTERN ulint	srv_buf_pool_size	= ULINT_MAX;
irana's avatar
irana committed
193 194
/* requested number of buffer pool instances */
UNIV_INTERN ulint       srv_buf_pool_instances  = 1;
195
/* previously requested size */
196
UNIV_INTERN ulint	srv_buf_pool_old_size;
197
/* current size in kilobytes */
198
UNIV_INTERN ulint	srv_buf_pool_curr_size	= 0;
199 200 201
/* size in bytes */
UNIV_INTERN ulint	srv_mem_pool_size	= ULINT_MAX;
UNIV_INTERN ulint	srv_lock_table_size	= ULINT_MAX;
osku's avatar
osku committed
202

203 204
/* This parameter is deprecated. Use srv_n_io_[read|write]_threads
instead. */
205
UNIV_INTERN ulint	srv_n_file_io_threads	= ULINT_MAX;
206 207 208 209 210 211 212
UNIV_INTERN ulint	srv_n_read_io_threads	= ULINT_MAX;
UNIV_INTERN ulint	srv_n_write_io_threads	= ULINT_MAX;

/* User settable value of the number of pages that must be present
in the buffer cache and accessed sequentially for InnoDB to trigger a
readahead request. */
UNIV_INTERN ulong	srv_read_ahead_threshold	= 56;
osku's avatar
osku committed
213 214

#ifdef UNIV_LOG_ARCHIVE
215 216 217
UNIV_INTERN ibool		srv_log_archive_on	= FALSE;
UNIV_INTERN ibool		srv_archive_recovery	= 0;
UNIV_INTERN ib_uint64_t	srv_archive_recovery_limit_lsn;
osku's avatar
osku committed
218 219
#endif /* UNIV_LOG_ARCHIVE */

220 221 222 223 224 225 226 227
/* This parameter is used to throttle the number of insert buffers that are
merged in a batch. By increasing this parameter on a faster disk you can
possibly reduce the number of I/O operations performed to complete the
merge operation. The value of this parameter is used as is by the
background loop when the system is idle (low load), on a busy system
the parameter is scaled down by a factor of 4, this is to avoid putting
a heavier load on the I/O sub system. */

228
UNIV_INTERN ulong	srv_insert_buffer_batch_size = 20;
229

230
UNIV_INTERN char*	srv_file_flush_method_str = NULL;
231
UNIV_INTERN ulint	srv_unix_file_flush_method = SRV_UNIX_FSYNC;
232
UNIV_INTERN ulint	srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;
osku's avatar
osku committed
233

234
UNIV_INTERN ulint	srv_max_n_open_files	  = 300;
osku's avatar
osku committed
235

236 237 238
/* Number of IO operations per second the server can do */
UNIV_INTERN ulong	srv_io_capacity         = 200;

osku's avatar
osku committed
239 240 241 242 243
/* The InnoDB main thread tries to keep the ratio of modified pages
in the buffer pool to all database pages in the buffer pool smaller than
the following number. But it is not guaranteed that the value stays below
that during a time of heavy update/insert activity. */

244
UNIV_INTERN ulong	srv_max_buf_pool_modified_pct	= 75;
osku's avatar
osku committed
245

246 247 248 249 250 251
/* the number of purge threads to use from the worker pool (currently 0 or 1).*/
UNIV_INTERN ulint srv_n_purge_threads = 0;

/* the number of records to purge in one batch */
UNIV_INTERN ulint srv_purge_batch_size = 20;

osku's avatar
osku committed
252
/* variable counts amount of data read in total (in bytes) */
253
UNIV_INTERN ulint srv_data_read = 0;
osku's avatar
osku committed
254 255

/* here we count the amount of data written in total (in bytes) */
256
UNIV_INTERN ulint srv_data_written = 0;
osku's avatar
osku committed
257 258

/* the number of the log write requests done */
259
UNIV_INTERN ulint srv_log_write_requests = 0;
osku's avatar
osku committed
260 261

/* the number of physical writes to the log performed */
262
UNIV_INTERN ulint srv_log_writes = 0;
osku's avatar
osku committed
263 264

/* amount of data written to the log files in bytes */
265
UNIV_INTERN ulint srv_os_log_written = 0;
osku's avatar
osku committed
266 267

/* amount of writes being done to the log files */
268
UNIV_INTERN ulint srv_os_log_pending_writes = 0;
osku's avatar
osku committed
269 270 271

/* we increase this counter, when there we don't have enough space in the
log buffer and have to flush it */
272
UNIV_INTERN ulint srv_log_waits = 0;
osku's avatar
osku committed
273 274 275

/* this variable counts the amount of times, when the doublewrite buffer
was flushed */
276
UNIV_INTERN ulint srv_dblwr_writes = 0;
osku's avatar
osku committed
277 278 279

/* here we store the number of pages that have been flushed to the
doublewrite buffer */
280
UNIV_INTERN ulint srv_dblwr_pages_written = 0;
osku's avatar
osku committed
281 282

/* in this variable we store the number of write requests issued */
283
UNIV_INTERN ulint srv_buf_pool_write_requests = 0;
osku's avatar
osku committed
284 285 286 287

/* here we store the number of times when we had to wait for a free page
in the buffer pool. It happens when the buffer pool is full and we need
to make a flush, in order to be able to read or create a page. */
288
UNIV_INTERN ulint srv_buf_pool_wait_free = 0;
osku's avatar
osku committed
289 290 291

/* variable to count the number of pages that were written from buffer
pool to the disk */
292
UNIV_INTERN ulint srv_buf_pool_flushed = 0;
osku's avatar
osku committed
293

294
/** Number of buffer pool reads that led to the
osku's avatar
osku committed
295
reading of a disk page */
296
UNIV_INTERN ulint srv_buf_pool_reads = 0;
osku's avatar
osku committed
297 298

/* structure to pass status variables to MySQL */
299
UNIV_INTERN export_struc export_vars;
osku's avatar
osku committed
300 301 302 303

/* If the following is != 0 we do not allow inserts etc. This protects
the user from forgetting the innodb_force_recovery keyword to my.cnf */

304
UNIV_INTERN ulint	srv_force_recovery	= 0;
osku's avatar
osku committed
305 306 307 308 309
/*-----------------------*/
/* We are prepared for a situation that we have this many threads waiting for
a semaphore inside InnoDB. innobase_start_or_create_for_mysql() sets the
value. */

310
UNIV_INTERN ulint	srv_max_n_threads	= 0;
osku's avatar
osku committed
311 312 313 314 315 316

/* The following controls how many threads we let inside InnoDB concurrently:
threads waiting for locks are not counted into the number because otherwise
we could get a deadlock. MySQL creates a thread for each user session, and
semaphore contention and convoy problems can occur withput this restriction.
Value 10 should be good if there are less than 4 processors + 4 disks in the
317 318
computer. Bigger computers need bigger values. Value 0 will disable the
concurrency check. */
osku's avatar
osku committed
319

320 321
UNIV_INTERN ulong	srv_thread_concurrency	= 0;

322 323 324 325
/* number of transactions that have declared_to_be_inside_innodb set.
It used to be a non-error for this value to drop below zero temporarily.
This is no longer true. We'll, however, keep the lint datatype to add
assertions to catch any corner cases that we may have missed. */
326
UNIV_INTERN lint	srv_conc_n_threads	= 0;
327 328 329 330

/* this mutex protects srv_conc data structures */
static os_fast_mutex_t	srv_conc_mutex;

331 332
/* number of OS threads waiting in the FIFO for a permission to enter
InnoDB */
333
static ulint	srv_conc_n_waiting_threads = 0;
osku's avatar
osku committed
334 335 336

typedef struct srv_conc_slot_struct	srv_conc_slot_t;
struct srv_conc_slot_struct{
337 338
	os_event_t			event;		/*!< event to wait */
	ibool				reserved;	/*!< TRUE if slot
osku's avatar
osku committed
339
							reserved */
340
	ibool				wait_ended;	/*!< TRUE when another
osku's avatar
osku committed
341 342 343 344 345 346
							thread has already set
							the event and the
							thread in this slot is
							free to proceed; but
							reserved may still be
							TRUE at that point */
347
	UT_LIST_NODE_T(srv_conc_slot_t)	srv_conc_queue;	/*!< queue node */
osku's avatar
osku committed
348 349
};

350
/* queue of threads waiting to get in */
351
static UT_LIST_BASE_NODE_T(srv_conc_slot_t)	srv_conc_queue;
352
/* array of wait slots */
353
static srv_conc_slot_t* srv_conc_slots;
osku's avatar
osku committed
354 355 356 357 358 359 360 361 362 363

/* Number of times a thread is allowed to enter InnoDB within the same
SQL query after it has once got the ticket at srv_conc_enter_innodb */
#define SRV_FREE_TICKETS_TO_ENTER srv_n_free_tickets_to_enter
#define SRV_THREAD_SLEEP_DELAY srv_thread_sleep_delay
/*-----------------------*/
/* If the following is set to 1 then we do not run purge and insert buffer
merge to completion before shutdown. If it is set to 2, do not even flush the
buffer pool to data files at the shutdown: we effectively 'crash'
InnoDB (but lose no committed transactions). */
364
UNIV_INTERN ulint	srv_fast_shutdown	= 0;
osku's avatar
osku committed
365 366

/* Generate a innodb_status.<pid> file */
367
UNIV_INTERN ibool	srv_innodb_status	= FALSE;
osku's avatar
osku committed
368

vasil's avatar
vasil committed
369 370
/* When estimating number of different key values in an index, sample
this many index pages */
371
UNIV_INTERN unsigned long long	srv_stats_sample_pages = 8;
vasil's avatar
vasil committed
372

373 374
UNIV_INTERN ibool	srv_use_doublewrite_buf	= TRUE;
UNIV_INTERN ibool	srv_use_checksums = TRUE;
osku's avatar
osku committed
375

376
UNIV_INTERN ulong	srv_replication_delay		= 0;
377

osku's avatar
osku committed
378
/*-------------------------------------------*/
379
UNIV_INTERN ulong	srv_n_spin_wait_rounds	= 30;
380 381
UNIV_INTERN ulong	srv_n_free_tickets_to_enter = 500;
UNIV_INTERN ulong	srv_thread_sleep_delay = 10000;
382
UNIV_INTERN ulong	srv_spin_wait_delay	= 6;
383
UNIV_INTERN ibool	srv_priority_boost	= TRUE;
osku's avatar
osku committed
384

385
#ifdef UNIV_DEBUG
386 387 388 389 390
UNIV_INTERN ibool	srv_print_thread_releases	= FALSE;
UNIV_INTERN ibool	srv_print_lock_waits		= FALSE;
UNIV_INTERN ibool	srv_print_buf_io		= FALSE;
UNIV_INTERN ibool	srv_print_log_io		= FALSE;
UNIV_INTERN ibool	srv_print_latch_waits		= FALSE;
391
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
392

393 394 395 396
UNIV_INTERN ulint		srv_n_rows_inserted		= 0;
UNIV_INTERN ulint		srv_n_rows_updated		= 0;
UNIV_INTERN ulint		srv_n_rows_deleted		= 0;
UNIV_INTERN ulint		srv_n_rows_read			= 0;
397

osku's avatar
osku committed
398 399 400 401 402
static ulint	srv_n_rows_inserted_old		= 0;
static ulint	srv_n_rows_updated_old		= 0;
static ulint	srv_n_rows_deleted_old		= 0;
static ulint	srv_n_rows_read_old		= 0;

403 404
UNIV_INTERN ulint		srv_n_lock_wait_count		= 0;
UNIV_INTERN ulint		srv_n_lock_wait_current_count	= 0;
405
UNIV_INTERN ib_int64_t	srv_n_lock_wait_time		= 0;
406
UNIV_INTERN ulint		srv_n_lock_max_wait_time	= 0;
osku's avatar
osku committed
407 408 409 410 411 412


/*
  Set the following to 0 if you want InnoDB to write messages on
  stderr on startup/shutdown
*/
413 414 415 416 417
UNIV_INTERN ibool	srv_print_verbose_log		= TRUE;
UNIV_INTERN ibool	srv_print_innodb_monitor	= FALSE;
UNIV_INTERN ibool	srv_print_innodb_lock_monitor	= FALSE;
UNIV_INTERN ibool	srv_print_innodb_tablespace_monitor = FALSE;
UNIV_INTERN ibool	srv_print_innodb_table_monitor = FALSE;
osku's avatar
osku committed
418 419 420 421

/* Array of English strings describing the current state of an
i/o handler thread */

422 423
UNIV_INTERN const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
UNIV_INTERN const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
osku's avatar
osku committed
424

425
UNIV_INTERN time_t	srv_last_monitor_time;
osku's avatar
osku committed
426

427
UNIV_INTERN mutex_t	srv_innodb_monitor_mutex;
osku's avatar
osku committed
428 429

/* Mutex for locking srv_monitor_file */
430
UNIV_INTERN mutex_t	srv_monitor_file_mutex;
431 432 433 434 435 436 437 438 439 440 441 442

#ifdef UNIV_PFS_MUTEX
/* Key to register kernel_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	kernel_mutex_key;
/* Key to register srv_innodb_monitor_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_innodb_monitor_mutex_key;
/* Key to register srv_monitor_file_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_monitor_file_mutex_key;
/* Key to register srv_dict_tmpfile_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_dict_tmpfile_mutex_key;
/* Key to register the mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_misc_tmpfile_mutex_key;
443 444
/* Key to register srv_sys_t::mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_srv_sys_mutex_key;
445 446
#endif /* UNIV_PFS_MUTEX */

osku's avatar
osku committed
447
/* Temporary file for innodb monitor output */
448
UNIV_INTERN FILE*	srv_monitor_file;
449 450 451
/* Mutex for locking srv_dict_tmpfile.
This mutex has a very high rank; threads reserving it should not
be holding any InnoDB latches. */
452
UNIV_INTERN mutex_t	srv_dict_tmpfile_mutex;
453
/* Temporary file for output from the data dictionary */
454
UNIV_INTERN FILE*	srv_dict_tmpfile;
455 456 457
/* Mutex for locking srv_misc_tmpfile.
This mutex has a very low rank; threads reserving it should not
acquire any further latches or sleep before releasing this one. */
458
UNIV_INTERN mutex_t	srv_misc_tmpfile_mutex;
459
/* Temporary file for miscellanous diagnostic output */
460
UNIV_INTERN FILE*	srv_misc_tmpfile;
osku's avatar
osku committed
461

462 463
UNIV_INTERN ulint	srv_main_thread_process_no	= 0;
UNIV_INTERN ulint	srv_main_thread_id		= 0;
osku's avatar
osku committed
464

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
/* The following count work done by srv_master_thread. */

/* Iterations by the 'once per second' loop. */
static ulint   srv_main_1_second_loops		= 0;
/* Calls to sleep by the 'once per second' loop. */
static ulint   srv_main_sleeps			= 0;
/* Iterations by the 'once per 10 seconds' loop. */
static ulint   srv_main_10_second_loops		= 0;
/* Iterations of the loop bounded by the 'background_loop' label. */
static ulint   srv_main_background_loops	= 0;
/* Iterations of the loop bounded by the 'flush_loop' label. */
static ulint   srv_main_flush_loops		= 0;
/* Log writes involving flush. */
static ulint   srv_log_writes_and_flush		= 0;

/* This is only ever touched by the master thread. It records the
time when the last flush of log file has happened. The master
thread ensures that we flush the log files at least once per
second. */
static time_t	srv_last_log_flush_time;

/* The master thread performs various tasks based on the current
state of IO activity and the level of IO utilization is past
intervals. Following macros define thresholds for these conditions. */
#define SRV_PEND_IO_THRESHOLD	(PCT_IO(3))
#define SRV_RECENT_IO_ACTIVITY	(PCT_IO(5))
#define SRV_PAST_IO_ACTIVITY	(PCT_IO(200))

493 494 495 496 497 498 499 500 501 502 503 504 505
/** Acquire the system_mutex. */
#define srv_sys_mutex_enter() do {		\
	mutex_enter(&srv_sys->mutex);		\
} while (0)

/** Test if the system mutex is owned. */
#define srv_sys_mutex_own() mutex_own(&srv_sys->mutex)

/** Release the system mutex. */
#define srv_sys_mutex_exit() do {		\
	mutex_exit(&srv_sys->mutex);		\
} while (0)

osku's avatar
osku committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
/*
	IMPLEMENTATION OF THE SERVER MAIN PROGRAM
	=========================================

There is the following analogue between this database
server and an operating system kernel:

DB concept			equivalent OS concept
----------			---------------------
transaction		--	process;

query thread		--	thread;

lock			--	semaphore;

transaction set to
the rollback state	--	kill signal delivered to a process;

kernel			--	kernel;

query thread execution:
(a) without kernel mutex
528
reserved		--	process executing in user mode;
osku's avatar
osku committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
(b) with kernel mutex reserved
			--	process executing in kernel mode;

The server is controlled by a master thread which runs at
a priority higher than normal, that is, higher than user threads.
It sleeps most of the time, and wakes up, say, every 300 milliseconds,
to check whether there is anything happening in the server which
requires intervention of the master thread. Such situations may be,
for example, when flushing of dirty blocks is needed in the buffer
pool or old version of database rows have to be cleaned away.

The threads which we call user threads serve the queries of
the clients and input from the console of the server.
They run at normal priority. The server may have several
communications endpoints. A dedicated set of user threads waits
at each of these endpoints ready to receive a client request.
Each request is taken by a single user thread, which then starts
processing and, when the result is ready, sends it to the client
and returns to wait at the same endpoint the thread started from.

So, we do not have dedicated communication threads listening at
the endpoints and dealing the jobs to dedicated worker threads.
Our architecture saves one thread swithch per request, compared
to the solution with dedicated communication threads
which amounts to 15 microseconds on 100 MHz Pentium
running NT. If the client
is communicating over a network, this saving is negligible, but
if the client resides in the same machine, maybe in an SMP machine
on a different processor from the server thread, the saving
can be important as the threads can communicate over shared
memory with an overhead of a few microseconds.

We may later implement a dedicated communication thread solution
for those endpoints which communicate over a network.

Our solution with user threads has two problems: for each endpoint
there has to be a number of listening threads. If there are many
communication endpoints, it may be difficult to set the right number
of concurrent threads in the system, as many of the threads
may always be waiting at less busy endpoints. Another problem
is queuing of the messages, as the server internally does not
offer any queue for jobs.

Another group of user threads is intended for splitting the
queries and processing them in parallel. Let us call these
parallel communication threads. These threads are waiting for
parallelized tasks, suspended on event semaphores.

A single user thread waits for input from the console,
like a command to shut the database.

Utility threads are a different group of threads which takes
care of the buffer pool flushing and other, mainly background
operations, in the server.
Some of these utility threads always run at a lower than normal
priority, so that they are always in background. Some of them
may dynamically boost their priority by the pri_adjust function,
even to higher than normal priority, if their task becomes urgent.
The running of utilities is controlled by high- and low-water marks
of urgency. The urgency may be measured by the number of dirty blocks
in the buffer pool, in the case of the flush thread, for example.
When the high-water mark is exceeded, an utility starts running, until
the urgency drops under the low-water mark. Then the utility thread
suspend itself to wait for an event. The master thread is
responsible of signaling this event when the utility thread is
again needed.

For each individual type of utility, some threads always remain
at lower than normal priority. This is because pri_adjust is implemented
so that the threads at normal or higher priority control their
share of running time by calling sleep. Thus, if the load of the
system sudenly drops, these threads cannot necessarily utilize
the system fully. The background priority threads make up for this,
starting to run when the load drops.

When there is no activity in the system, also the master thread
suspends itself to wait for an event making
the server totally silent. The responsibility to signal this
event is on the user thread which again receives a message
from a client.

There is still one complication in our server design. If a
background utility thread obtains a resource (e.g., mutex) needed by a user
thread, and there is also some other user activity in the system,
the user thread may have to wait indefinitely long for the
resource, as the OS does not schedule a background thread if
there is some other runnable user thread. This problem is called
priority inversion in real-time programming.

One solution to the priority inversion problem would be to
keep record of which thread owns which resource and
in the above case boost the priority of the background thread
so that it will be scheduled and it can release the resource.
This solution is called priority inheritance in real-time programming.
623
A drawback of this solution is that the overhead of acquiring a mutex
osku's avatar
osku committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
increases slightly, maybe 0.2 microseconds on a 100 MHz Pentium, because
the thread has to call os_thread_get_curr_id.
This may be compared to 0.5 microsecond overhead for a mutex lock-unlock
pair. Note that the thread
cannot store the information in the resource, say mutex, itself,
because competing threads could wipe out the information if it is
stored before acquiring the mutex, and if it stored afterwards,
the information is outdated for the time of one machine instruction,
at least. (To be precise, the information could be stored to
lock_word in mutex if the machine supports atomic swap.)

The above solution with priority inheritance may become actual in the
future, but at the moment we plan to implement a more coarse solution,
which could be called a global priority inheritance. If a thread
has to wait for a long time, say 300 milliseconds, for a resource,
we just guess that it may be waiting for a resource owned by a background
640
thread, and boost the priority of all runnable background threads
osku's avatar
osku committed
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
to the normal level. The background threads then themselves adjust
their fixed priority back to background after releasing all resources
they had (or, at some fixed points in their program code).

What is the performance of the global priority inheritance solution?
We may weigh the length of the wait time 300 milliseconds, during
which the system processes some other thread
to the cost of boosting the priority of each runnable background
thread, rescheduling it, and lowering the priority again.
On 100 MHz Pentium + NT this overhead may be of the order 100
microseconds per thread. So, if the number of runnable background
threads is not very big, say < 100, the cost is tolerable.
Utility threads probably will access resources used by
user threads not very often, so collisions of user threads
to preempted utility threads should not happen very often.

The thread table contains
information of the current status of each thread existing in the system,
and also the event semaphores used in suspending the master thread
and utility and parallel communication threads when they have nothing to do.
The thread table can be seen as an analogue to the process table
in a traditional Unix implementation.

The thread table is also used in the global priority inheritance
scheme. This brings in one additional complication: threads accessing
the thread table must have at least normal fixed priority,
because the priority inheritance solution does not work if a background
thread is preempted while possessing the mutex protecting the thread table.
So, if a thread accesses the thread table, its priority has to be
boosted at least to normal. This priority requirement can be seen similar to
the privileged mode used when processing the kernel calls in traditional
Unix.*/

674
/** Thread slot in the thread table.  */
osku's avatar
osku committed
675
struct srv_slot_struct{
676 677 678 679 680
	os_thread_id_t	id;		/*!< thread id */
	os_thread_t	handle;		/*!< thread handle */
	unsigned	type:3;		/*!< thread type: user, utility etc. */
	unsigned	in_use:1;	/*!< TRUE if this slot is in use */
	unsigned	suspended:1;	/*!< TRUE if the thread is waiting
osku's avatar
osku committed
681
					for the event of this slot */
682
	ib_time_t	suspend_time;	/*!< time when the thread was
osku's avatar
osku committed
683
					suspended */
684
	os_event_t	event;		/*!< event used in suspending the
osku's avatar
osku committed
685
					thread when it has nothing to do */
686
	que_thr_t*	thr;		/*!< suspended query thread (only
osku's avatar
osku committed
687 688 689
					used for MySQL threads) */
};

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
/** Thread slot in the thread table */
typedef struct srv_slot_struct	srv_slot_t;

/** Thread table is an array of slots */
typedef srv_slot_t	srv_table_t;

/** The server system */
typedef struct srv_sys_struct	srv_sys_t;

/** The server system struct */
struct srv_sys_struct{
	mutex_t		mutex;			/*!< variable protecting the
						fields in this structure. */
	srv_table_t*	sys_threads;		/*!< server thread table */

	UT_LIST_BASE_NODE_T(que_thr_t)
			tasks;			/*!< task queue */

	ulint		n_threads[SRV_MASTER + 1];
						/*!< number of system threads
						in a thread class */

	ulint		n_threads_active[SRV_MASTER + 1];
						/*!< number of threads active
						in a thread class */

	srv_slot_t*	waiting_threads;	/*!< Array  of user threads
						suspended while waiting for
					       	locks within InnoDB */
	srv_slot_t*	last_slot;		/*!< highest slot ever used
						in the waiting_threads array */
	ulint		activity_count;		/*!< For tracking server
						activity */
723 724 725 726 727 728 729 730
	unsigned	lock_wait_timeout;	/*!< TRUE if the lock monitor
						thread is rolling back a
					       	transaction that has waited
					       	for too long for the lock a
						be granted. We use this flag
					       	to track whether the
					       	srv_sys->mutex needs to be
					       	acquired or not */
731
};
osku's avatar
osku committed
732

733
UNIV_INTERN os_event_t	srv_lock_timeout_thread_event;
osku's avatar
osku committed
734 735


736 737 738 739 740 741 742 743
/* padding to prevent other memory update hotspots from residing on
the same memory cache line */
UNIV_INTERN byte	srv_pad1[64];
/* mutex protecting the server, trx structs, query threads, and lock table */
UNIV_INTERN mutex_t*	kernel_mutex_temp;
/* padding to prevent other memory update hotspots from residing on
the same memory cache line */
UNIV_INTERN byte	srv_pad2[64];
osku's avatar
osku committed
744

745 746
static srv_sys_t*	srv_sys	= NULL;

747
#if 0
osku's avatar
osku committed
748 749 750 751 752 753
/* The following three values measure the urgency of the jobs of
buffer, version, and insert threads. They may vary from 0 - 1000.
The server mutex protects all these variables. The low-water values
tell that the server can acquiesce the utility when the value
drops below this low-water mark. */

754 755 756 757 758
static ulint	srv_meter[SRV_MASTER + 1];
static ulint	srv_meter_low_water[SRV_MASTER + 1];
static ulint	srv_meter_high_water[SRV_MASTER + 1];
static ulint	srv_meter_high_water2[SRV_MASTER + 1];
static ulint	srv_meter_foreground[SRV_MASTER + 1];
759
#endif
osku's avatar
osku committed
760

761 762 763 764 765 766 767 768 769 770
/*********************************************************************//**
Asynchronous purge thread.
@return	a dummy parameter */
UNIV_INTERN
os_thread_ret_t
srv_purge_thread(
/*=============*/
	void*	arg __attribute__((unused))); /*!< in: a dummy parameter
					      required by os_thread_create */

771 772 773 774 775 776 777 778 779 780 781 782 783
/***********************************************************************
Prints counters for work done by srv_master_thread. */
static
void
srv_print_master_thread_info(
/*=========================*/
	FILE  *file)    /* in: output stream */
{
	fprintf(file, "srv_master_thread loops: %lu 1_second, %lu sleeps, "
		"%lu 10_second, %lu background, %lu flush\n",
		srv_main_1_second_loops, srv_main_sleeps,
		srv_main_10_second_loops, srv_main_background_loops,
		srv_main_flush_loops);
784 785
	fprintf(file, "srv_master_thread log flush and writes: %lu\n",
		      srv_log_writes_and_flush);
786 787
}

788
/*********************************************************************//**
osku's avatar
osku committed
789
Sets the info describing an i/o thread current state. */
790
UNIV_INTERN
osku's avatar
osku committed
791 792 793
void
srv_set_io_thread_op_info(
/*======================*/
794 795
	ulint		i,	/*!< in: the 'segment' of the i/o thread */
	const char*	str)	/*!< in: constant char string describing the
osku's avatar
osku committed
796 797 798 799 800 801 802
				state */
{
	ut_a(i < SRV_MAX_N_IO_THREADS);

	srv_io_thread_op_info[i] = str;
}

803
/*********************************************************************//**
osku's avatar
osku committed
804
Accessor function to get pointer to n'th slot in the server thread
805 806
table.
@return	pointer to the slot */
osku's avatar
osku committed
807 808 809 810
static
srv_slot_t*
srv_table_get_nth_slot(
/*===================*/
811
	ulint	index)		/*!< in: index of the slot */
osku's avatar
osku committed
812
{
813
	ut_ad(srv_sys_mutex_own());
osku's avatar
osku committed
814 815
	ut_a(index < OS_THREAD_MAX_N);

816
	return(srv_sys->sys_threads + index);
osku's avatar
osku committed
817 818
}

819
/*********************************************************************//**
820
Gets the number of threads in the system.
821
@return	sum of srv_sys_t::n_threads[] */
822
UNIV_INTERN
osku's avatar
osku committed
823 824 825 826 827 828 829
ulint
srv_get_n_threads(void)
/*===================*/
{
	ulint	i;
	ulint	n_threads	= 0;

830
	srv_sys_mutex_enter();
osku's avatar
osku committed
831 832

	for (i = SRV_COM; i < SRV_MASTER + 1; i++) {
833

834
		n_threads += srv_sys->n_threads[i];
osku's avatar
osku committed
835 836
	}

837
	srv_sys_mutex_exit();
osku's avatar
osku committed
838 839 840 841

	return(n_threads);
}

842
/*********************************************************************//**
osku's avatar
osku committed
843 844
Reserves a slot in the thread table for the current thread. Also creates the
thread local storage struct for the current thread. NOTE! The server mutex
845 846
has to be reserved by the caller!
@return	reserved slot index */
osku's avatar
osku committed
847 848 849 850
static
ulint
srv_table_reserve_slot(
/*===================*/
851
	enum srv_thread_type	type)	/*!< in: type of the thread */
osku's avatar
osku committed
852 853 854
{
	srv_slot_t*	slot;
	ulint		i;
855

856 857
	ut_ad(srv_sys_mutex_own());

osku's avatar
osku committed
858 859 860 861 862 863 864 865 866 867 868 869
	ut_a(type > 0);
	ut_a(type <= SRV_MASTER);

	i = 0;
	slot = srv_table_get_nth_slot(i);

	while (slot->in_use) {
		i++;
		slot = srv_table_get_nth_slot(i);
	}

	ut_a(slot->in_use == FALSE);
870

osku's avatar
osku committed
871 872
	slot->in_use = TRUE;
	slot->suspended = FALSE;
873
	slot->type = type;
osku's avatar
osku committed
874 875 876 877 878 879 880 881 882 883
	slot->id = os_thread_get_curr_id();
	slot->handle = os_thread_get_curr();

	thr_local_create();

	thr_local_set_slot_no(os_thread_get_curr_id(), i);

	return(i);
}

884
/*********************************************************************//**
osku's avatar
osku committed
885
Suspends the calling thread to wait for the event in its thread slot.
886 887
NOTE! The server mutex has to be reserved by the caller!
@return	event for the calling thread to wait */
osku's avatar
osku committed
888 889 890 891 892
static
os_event_t
srv_suspend_thread(void)
/*====================*/
{
893 894 895 896
	srv_slot_t*		slot;
	os_event_t		event;
	ulint			slot_no;
	enum srv_thread_type	type;
osku's avatar
osku committed
897

898
	srv_sys_mutex_enter();
899

osku's avatar
osku committed
900 901 902 903
	slot_no = thr_local_get_slot_no(os_thread_get_curr_id());

	if (srv_print_thread_releases) {
		fprintf(stderr,
904 905
			"Suspending thread %lu to slot %lu\n",
			(ulong) os_thread_get_curr_id(), (ulong) slot_no);
osku's avatar
osku committed
906 907 908 909 910 911 912 913 914 915
	}

	slot = srv_table_get_nth_slot(slot_no);

	type = slot->type;

	ut_ad(type >= SRV_WORKER);
	ut_ad(type <= SRV_MASTER);

	event = slot->event;
916

osku's avatar
osku committed
917 918
	slot->suspended = TRUE;

919
	ut_ad(srv_sys->n_threads_active[type] > 0);
osku's avatar
osku committed
920

921
	srv_sys->n_threads_active[type]--;
osku's avatar
osku committed
922 923 924

	os_event_reset(event);

925 926
	srv_sys_mutex_exit();

osku's avatar
osku committed
927 928 929
	return(event);
}

930
/*********************************************************************//**
osku's avatar
osku committed
931
Releases threads of the type given from suspension in the thread table.
932
NOTE! The server mutex has to be reserved by the caller!
933 934
@return number of threads released: this may be less than n if not
enough threads were suspended at the moment */
935
static
osku's avatar
osku committed
936 937 938
ulint
srv_release_threads(
/*================*/
939 940
	enum srv_thread_type	type,	/*!< in: thread type */
	ulint			n)	/*!< in: number of threads to release */
osku's avatar
osku committed
941 942 943 944 945 946 947
{
	ulint		i;
	ulint		count	= 0;

	ut_ad(type >= SRV_WORKER);
	ut_ad(type <= SRV_MASTER);
	ut_ad(n > 0);
948 949

	srv_sys_mutex_enter();
950

osku's avatar
osku committed
951
	for (i = 0; i < OS_THREAD_MAX_N; i++) {
952
		srv_slot_t*	slot;
953

osku's avatar
osku committed
954 955 956
		slot = srv_table_get_nth_slot(i);

		if (slot->in_use && slot->type == type && slot->suspended) {
957

osku's avatar
osku committed
958 959
			slot->suspended = FALSE;

960
			srv_sys->n_threads_active[type]++;
osku's avatar
osku committed
961 962 963 964 965

			os_event_set(slot->event);

			if (srv_print_thread_releases) {
				fprintf(stderr,
966
					"Releasing thread %lu type %lu"
967
					" from slot %lu\n",
968
					(ulong) slot->id, (ulong) type,
969
					(ulong) i);
osku's avatar
osku committed
970 971 972 973 974 975 976 977 978 979
			}

			count++;

			if (count == n) {
				break;
			}
		}
	}

980 981
	srv_sys_mutex_exit();

osku's avatar
osku committed
982 983 984
	return(count);
}

985
/*********************************************************************//**
986 987
Returns the calling thread type.
@return	SRV_COM, ... */
988
UNIV_INTERN
989
enum srv_thread_type
osku's avatar
osku committed
990 991 992
srv_get_thread_type(void)
/*=====================*/
{
993 994 995
	ulint			slot_no;
	srv_slot_t*		slot;
	enum srv_thread_type	type;
osku's avatar
osku committed
996

997
	srv_sys_mutex_enter();
998

osku's avatar
osku committed
999 1000 1001 1002 1003 1004 1005 1006 1007
	slot_no = thr_local_get_slot_no(os_thread_get_curr_id());

	slot = srv_table_get_nth_slot(slot_no);

	type = slot->type;

	ut_ad(type >= SRV_WORKER);
	ut_ad(type <= SRV_MASTER);

1008
	srv_sys_mutex_exit();
osku's avatar
osku committed
1009 1010 1011 1012

	return(type);
}

1013
/*********************************************************************//**
osku's avatar
osku committed
1014
Initializes the server. */
1015
UNIV_INTERN
osku's avatar
osku committed
1016 1017 1018 1019 1020
void
srv_init(void)
/*==========*/
{
	ulint			i;
1021 1022
	srv_conc_slot_t*	conc_slot;
	ulint			srv_sys_sz;
osku's avatar
osku committed
1023

1024 1025 1026 1027
	srv_sys_sz = sizeof(*srv_sys)
	       	   + (OS_THREAD_MAX_N * sizeof(srv_slot_t) * 2);

	srv_sys = mem_zalloc(srv_sys_sz);
osku's avatar
osku committed
1028 1029

	kernel_mutex_temp = mem_alloc(sizeof(mutex_t));
1030
	mutex_create(kernel_mutex_key, &kernel_mutex, SYNC_KERNEL);
osku's avatar
osku committed
1031

1032 1033
	mutex_create(srv_innodb_monitor_mutex_key,
		     &srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
1034

1035
	mutex_create(srv_srv_sys_mutex_key, &srv_sys->mutex, SYNC_THREADS);
osku's avatar
osku committed
1036

1037
	srv_sys_mutex_enter();
osku's avatar
osku committed
1038

1039 1040 1041
	srv_sys->sys_threads = (srv_slot_t*) &srv_sys[1];
	srv_sys->waiting_threads = srv_sys->sys_threads + OS_THREAD_MAX_N;
	srv_sys->last_slot = srv_sys->waiting_threads;
osku's avatar
osku committed
1042 1043

	for (i = 0; i < OS_THREAD_MAX_N; i++) {
1044 1045 1046 1047
		srv_slot_t*	slot;

		slot = srv_table_get_nth_slot(i);

osku's avatar
osku committed
1048
		slot->event = os_event_create(NULL);
1049

osku's avatar
osku committed
1050 1051 1052 1053
		ut_a(slot->event);
	}

	srv_lock_timeout_thread_event = os_event_create(NULL);
1054

osku's avatar
osku committed
1055 1056
	UT_LIST_INIT(srv_sys->tasks);

1057 1058
	srv_sys_mutex_exit();

1059 1060 1061
	/* Create dummy indexes for infimum and supremum records */

	dict_ind_init();
osku's avatar
osku committed
1062 1063 1064 1065

	/* Init the server concurrency restriction data structures */

	os_fast_mutex_init(&srv_conc_mutex);
1066

osku's avatar
osku committed
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
	UT_LIST_INIT(srv_conc_queue);

	srv_conc_slots = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_conc_slot_t));

	for (i = 0; i < OS_THREAD_MAX_N; i++) {
		conc_slot = srv_conc_slots + i;
		conc_slot->reserved = FALSE;
		conc_slot->event = os_event_create(NULL);
		ut_a(conc_slot->event);
	}
1077 1078 1079

	/* Initialize some INFORMATION SCHEMA internal structures */
	trx_i_s_cache_init(trx_i_s_cache);
1080
}
osku's avatar
osku committed
1081

1082
/*********************************************************************//**
1083
Frees the data structures created in srv_init(). */
1084
UNIV_INTERN
osku's avatar
osku committed
1085 1086 1087 1088 1089
void
srv_free(void)
/*==========*/
{
	os_fast_mutex_free(&srv_conc_mutex);
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
	mem_free(srv_conc_slots);
	srv_conc_slots = NULL;

	mem_free(srv_sys);
	srv_sys = NULL;

	mem_free(kernel_mutex_temp);
	kernel_mutex_temp = NULL;

	trx_i_s_cache_free(trx_i_s_cache);
osku's avatar
osku committed
1100 1101
}

1102
/*********************************************************************//**
osku's avatar
osku committed
1103 1104
Initializes the synchronization primitives, memory system, and the thread
local storage. */
1105
UNIV_INTERN
osku's avatar
osku committed
1106 1107 1108 1109
void
srv_general_init(void)
/*==================*/
{
1110
	ut_mem_init();
1111 1112
	/* Reset the system variables in the recovery module. */
	recv_sys_var_init();
osku's avatar
osku committed
1113 1114 1115 1116 1117 1118 1119 1120 1121
	os_sync_init();
	sync_init();
	mem_init(srv_mem_pool_size);
	thr_local_init();
}

/*======================= InnoDB Server FIFO queue =======================*/

/* Maximum allowable purge history length.  <=0 means 'infinite'. */
1122
UNIV_INTERN ulong	srv_max_purge_lag		= 0;
osku's avatar
osku committed
1123

1124
/*********************************************************************//**
osku's avatar
osku committed
1125 1126
Puts an OS thread to wait if there are too many concurrent threads
(>= srv_thread_concurrency) inside InnoDB. The threads wait in a FIFO queue. */
1127
UNIV_INTERN
osku's avatar
osku committed
1128 1129 1130
void
srv_conc_enter_innodb(
/*==================*/
1131
	trx_t*	trx)	/*!< in: transaction object associated with the
osku's avatar
osku committed
1132 1133 1134 1135 1136 1137
			thread */
{
	ibool			has_slept = FALSE;
	srv_conc_slot_t*	slot	  = NULL;
	ulint			i;

1138 1139 1140
	if (trx->mysql_thd != NULL
	    && thd_is_replication_slave_thread(trx->mysql_thd)) {

1141 1142 1143 1144
		UT_WAIT_FOR(srv_conc_n_threads
			    < (lint)srv_thread_concurrency,
			    srv_replication_delay * 1000);

1145 1146 1147
		return;
	}

osku's avatar
osku committed
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	/* If trx has 'free tickets' to enter the engine left, then use one
	such ticket */

	if (trx->n_tickets_to_enter_innodb > 0) {
		trx->n_tickets_to_enter_innodb--;

		return;
	}

	os_fast_mutex_lock(&srv_conc_mutex);
retry:
	if (trx->declared_to_be_inside_innodb) {
1160
		ut_print_timestamp(stderr);
1161 1162 1163
		fputs("  InnoDB: Error: trying to declare trx"
		      " to enter InnoDB, but\n"
		      "InnoDB: it already is declared.\n", stderr);
osku's avatar
osku committed
1164 1165 1166 1167 1168 1169 1170
		trx_print(stderr, trx, 0);
		putc('\n', stderr);
		os_fast_mutex_unlock(&srv_conc_mutex);

		return;
	}

1171 1172
	ut_ad(srv_conc_n_threads >= 0);

osku's avatar
osku committed
1173 1174 1175 1176 1177
	if (srv_conc_n_threads < (lint)srv_thread_concurrency) {

		srv_conc_n_threads++;
		trx->declared_to_be_inside_innodb = TRUE;
		trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
1178

osku's avatar
osku committed
1179 1180 1181 1182 1183
		os_fast_mutex_unlock(&srv_conc_mutex);

		return;
	}

1184 1185
	/* If the transaction is not holding resources, let it sleep
	for SRV_THREAD_SLEEP_DELAY microseconds, and try again then */
1186

osku's avatar
osku committed
1187
	if (!has_slept && !trx->has_search_latch
1188
	    && NULL == UT_LIST_GET_FIRST(trx->trx_locks)) {
osku's avatar
osku committed
1189

1190
		has_slept = TRUE; /* We let it sleep only once to avoid
osku's avatar
osku committed
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
				  starvation */

		srv_conc_n_waiting_threads++;

		os_fast_mutex_unlock(&srv_conc_mutex);

		trx->op_info = "sleeping before joining InnoDB queue";

		/* Peter Zaitsev suggested that we take the sleep away
		altogether. But the sleep may be good in pathological
		situations of lots of thread switches. Simply put some
		threads aside for a while to reduce the number of thread
		switches. */
1204 1205 1206
		if (SRV_THREAD_SLEEP_DELAY > 0) {
			os_thread_sleep(SRV_THREAD_SLEEP_DELAY);
		}
osku's avatar
osku committed
1207 1208 1209 1210 1211 1212 1213 1214

		trx->op_info = "";

		os_fast_mutex_lock(&srv_conc_mutex);

		srv_conc_n_waiting_threads--;

		goto retry;
1215
	}
osku's avatar
osku committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

	/* Too many threads inside: put the current thread to a queue */

	for (i = 0; i < OS_THREAD_MAX_N; i++) {
		slot = srv_conc_slots + i;

		if (!slot->reserved) {

			break;
		}
	}

	if (i == OS_THREAD_MAX_N) {
		/* Could not find a free wait slot, we must let the
		thread enter */

		srv_conc_n_threads++;
		trx->declared_to_be_inside_innodb = TRUE;
		trx->n_tickets_to_enter_innodb = 0;

		os_fast_mutex_unlock(&srv_conc_mutex);

		return;
	}

	/* Release possible search system latch this thread has */
	if (trx->has_search_latch) {
		trx_search_latch_release_if_reserved(trx);
	}

	/* Add to the queue */
	slot->reserved = TRUE;
	slot->wait_ended = FALSE;
1249

osku's avatar
osku committed
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
	UT_LIST_ADD_LAST(srv_conc_queue, srv_conc_queue, slot);

	os_event_reset(slot->event);

	srv_conc_n_waiting_threads++;

	os_fast_mutex_unlock(&srv_conc_mutex);

	/* Go to wait for the event; when a thread leaves InnoDB it will
	release this thread */

	trx->op_info = "waiting in InnoDB queue";

	os_event_wait(slot->event);

	trx->op_info = "";

	os_fast_mutex_lock(&srv_conc_mutex);

	srv_conc_n_waiting_threads--;

	/* NOTE that the thread which released this thread already
	incremented the thread counter on behalf of this thread */

	slot->reserved = FALSE;

	UT_LIST_REMOVE(srv_conc_queue, srv_conc_queue, slot);

	trx->declared_to_be_inside_innodb = TRUE;
	trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;

	os_fast_mutex_unlock(&srv_conc_mutex);
}

1284
/*********************************************************************//**
osku's avatar
osku committed
1285 1286
This lets a thread enter InnoDB regardless of the number of threads inside
InnoDB. This must be called when a thread ends a lock wait. */
1287
UNIV_INTERN
osku's avatar
osku committed
1288 1289 1290
void
srv_conc_force_enter_innodb(
/*========================*/
1291
	trx_t*	trx)	/*!< in: transaction object associated with the
osku's avatar
osku committed
1292 1293
			thread */
{
1294
	if (UNIV_LIKELY(!srv_thread_concurrency)) {
1295

osku's avatar
osku committed
1296 1297 1298
		return;
	}

1299 1300
	ut_ad(srv_conc_n_threads >= 0);

osku's avatar
osku committed
1301 1302 1303 1304
	os_fast_mutex_lock(&srv_conc_mutex);

	srv_conc_n_threads++;
	trx->declared_to_be_inside_innodb = TRUE;
1305
	trx->n_tickets_to_enter_innodb = 1;
osku's avatar
osku committed
1306 1307 1308 1309

	os_fast_mutex_unlock(&srv_conc_mutex);
}

1310
/*********************************************************************//**
osku's avatar
osku committed
1311 1312
This must be called when a thread exits InnoDB in a lock wait or at the
end of an SQL statement. */
1313
UNIV_INTERN
osku's avatar
osku committed
1314 1315 1316
void
srv_conc_force_exit_innodb(
/*=======================*/
1317
	trx_t*	trx)	/*!< in: transaction object associated with the
osku's avatar
osku committed
1318 1319 1320 1321
			thread */
{
	srv_conc_slot_t*	slot	= NULL;

1322 1323 1324 1325 1326 1327
	if (trx->mysql_thd != NULL
	    && thd_is_replication_slave_thread(trx->mysql_thd)) {

		return;
	}

osku's avatar
osku committed
1328
	if (trx->declared_to_be_inside_innodb == FALSE) {
1329

osku's avatar
osku committed
1330 1331 1332 1333 1334
		return;
	}

	os_fast_mutex_lock(&srv_conc_mutex);

1335
	ut_ad(srv_conc_n_threads > 0);
osku's avatar
osku committed
1336 1337 1338 1339 1340 1341 1342
	srv_conc_n_threads--;
	trx->declared_to_be_inside_innodb = FALSE;
	trx->n_tickets_to_enter_innodb = 0;

	if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
		/* Look for a slot where a thread is waiting and no other
		thread has yet released the thread */
1343

osku's avatar
osku committed
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
		slot = UT_LIST_GET_FIRST(srv_conc_queue);

		while (slot && slot->wait_ended == TRUE) {
			slot = UT_LIST_GET_NEXT(srv_conc_queue, slot);
		}

		if (slot != NULL) {
			slot->wait_ended = TRUE;

			/* We increment the count on behalf of the released
			thread */

			srv_conc_n_threads++;
		}
	}

	os_fast_mutex_unlock(&srv_conc_mutex);

	if (slot != NULL) {
		os_event_set(slot->event);
	}
}

1367
/*********************************************************************//**
osku's avatar
osku committed
1368
This must be called when a thread exits InnoDB. */
1369
UNIV_INTERN
osku's avatar
osku committed
1370 1371 1372
void
srv_conc_exit_innodb(
/*=================*/
1373
	trx_t*	trx)	/*!< in: transaction object associated with the
osku's avatar
osku committed
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
			thread */
{
	if (trx->n_tickets_to_enter_innodb > 0) {
		/* We will pretend the thread is still inside InnoDB though it
		now leaves the InnoDB engine. In this way we save
		a lot of semaphore operations. srv_conc_force_exit_innodb is
		used to declare the thread definitely outside InnoDB. It
		should be called when there is a lock wait or an SQL statement
		ends. */

		return;
	}

	srv_conc_force_exit_innodb(trx);
}

/*========================================================================*/

1392
/*********************************************************************//**
1393 1394
Normalizes init parameter values to use units we use inside InnoDB.
@return	DB_SUCCESS or error code */
osku's avatar
osku committed
1395 1396 1397 1398 1399 1400 1401 1402 1403
static
ulint
srv_normalize_init_values(void)
/*===========================*/
{
	ulint	n;
	ulint	i;

	n = srv_n_data_files;
1404

osku's avatar
osku committed
1405 1406
	for (i = 0; i < n; i++) {
		srv_data_file_sizes[i] = srv_data_file_sizes[i]
1407
			* ((1024 * 1024) / UNIV_PAGE_SIZE);
1408
	}
osku's avatar
osku committed
1409 1410

	srv_last_file_size_max = srv_last_file_size_max
1411
		* ((1024 * 1024) / UNIV_PAGE_SIZE);
1412

osku's avatar
osku committed
1413 1414 1415 1416
	srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;

	srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;

1417
	srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
osku's avatar
osku committed
1418 1419 1420 1421

	return(DB_SUCCESS);
}

1422
/*********************************************************************//**
1423 1424
Boots the InnoDB server.
@return	DB_SUCCESS or error code */
1425
UNIV_INTERN
osku's avatar
osku committed
1426 1427 1428 1429 1430 1431 1432 1433
ulint
srv_boot(void)
/*==========*/
{
	ulint	err;

	/* Transform the init parameter values given by MySQL to
	use units we use inside InnoDB: */
1434

osku's avatar
osku committed
1435 1436 1437 1438 1439
	err = srv_normalize_init_values();

	if (err != DB_SUCCESS) {
		return(err);
	}
1440

osku's avatar
osku committed
1441 1442
	/* Initialize synchronization primitives, memory management, and thread
	local storage */
1443

osku's avatar
osku committed
1444 1445 1446 1447 1448 1449 1450 1451 1452
	srv_general_init();

	/* Initialize this module */

	srv_init();

	return(DB_SUCCESS);
}

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
/*********************************************************************//**
Print the contents of the srv_sys_t::waiting_threads array. */
static
void
srv_print_mysql_threads(void)
/*=========================*/
{
	ulint	i;

	for (i = 0; i < OS_THREAD_MAX_N; i++) {
		srv_slot_t*	slot;

		slot = srv_sys->waiting_threads + i;

		fprintf(stderr,
			"Slot %lu: thread id %lu, type %lu,"
			" in use %lu, susp %lu, time %lu\n",
			(ulong) i,
			(ulong) os_thread_pf(slot->id),
			(ulong) slot->type,
			(ulong) slot->in_use,
			(ulong) slot->suspended,
			(ulong) difftime(ut_time(), slot->suspend_time));
	}
}

/*********************************************************************//**
Release a slot in the srv_sys_t::waiting_threads. Adjust the array last pointer
if there are empty slots towards the end of the table. */
static
void
srv_table_release_slot_for_mysql(
/*=============================*/
	srv_slot_t*	slot)		/*!< in: slot to release */
{
#ifdef UNIV_DEBUG
	srv_slot_t*	upper = srv_sys->waiting_threads + OS_THREAD_MAX_N;
#endif /* UNIV_DEBUG */

	srv_sys_mutex_enter();

	ut_a(slot->in_use);
	ut_a(slot->thr != NULL);
	ut_a(slot->thr->slot != NULL);
	ut_a(slot->thr->slot == slot);

	/* Must be within the array boundaries. */
	ut_ad(slot >= srv_sys->waiting_threads);
	ut_ad(slot < upper);

	slot->thr->slot = NULL;
	slot->thr = NULL;
	slot->in_use = FALSE;

	/* Scan backwards and adjust the last free slot pointer. */
	for (slot = srv_sys->last_slot;
	     slot > srv_sys->waiting_threads && !slot->in_use;
	     --slot) {
		/* No op */
	}

	/* Either the array is empty or the last scanned slot is in use. */
	ut_ad(slot->in_use || slot == srv_sys->waiting_threads);

	srv_sys->last_slot = slot + 1;

	/* The last slot is either outside of the array boundry or it's
	on an empty slot. */
	ut_ad(srv_sys->last_slot == upper || !srv_sys->last_slot->in_use);

	ut_ad(srv_sys->last_slot >= srv_sys->waiting_threads);
	ut_ad(srv_sys->last_slot <= upper);

	srv_sys_mutex_exit();
}

1529
/*********************************************************************//**
osku's avatar
osku committed
1530
Reserves a slot in the thread table for the current MySQL OS thread.
1531
@return	reserved slot */
osku's avatar
osku committed
1532 1533
static
srv_slot_t*
1534 1535 1536 1537
srv_table_reserve_slot_for_mysql(
/*=============================*/
	que_thr_t*	thr)		/*!< in: query thread associated
					with the MySQL OS thread */
osku's avatar
osku committed
1538 1539
{
	ulint		i;
1540
	srv_slot_t*	slot;
osku's avatar
osku committed
1541

1542
	srv_sys_mutex_enter();
osku's avatar
osku committed
1543

1544
	slot = srv_sys->waiting_threads;
osku's avatar
osku committed
1545

1546 1547 1548 1549 1550
	for (i = 0; i < OS_THREAD_MAX_N; ++i, ++slot) {
		if (!slot->in_use) {
			break;
		}
	}
osku's avatar
osku committed
1551

1552 1553
	/* Check if we have run out of slots. */
	if (slot == srv_sys->waiting_threads+ OS_THREAD_MAX_N) {
osku's avatar
osku committed
1554

1555
		ut_print_timestamp(stderr);
osku's avatar
osku committed
1556

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
		fprintf(stderr,
			"  InnoDB: There appear to be %lu MySQL"
			" threads currently waiting\n"
			"InnoDB: inside InnoDB, which is the"
			" upper limit. Cannot continue operation.\n"
			"InnoDB: We intentionally generate"
			" a seg fault to print a stack trace\n"
			"InnoDB: on Linux. But first we print"
			" a list of waiting threads.\n", (ulong) i);

		srv_print_mysql_threads();

		ut_error;
	} else {
osku's avatar
osku committed
1571

1572
		ut_a(slot->in_use == FALSE);
osku's avatar
osku committed
1573

1574 1575 1576 1577 1578
		slot->in_use = TRUE;
		slot->thr = thr;
		slot->thr->slot = slot;
		slot->id = os_thread_get_curr_id();
		slot->handle = os_thread_get_curr();
osku's avatar
osku committed
1579

1580 1581 1582
		if (slot->event == NULL) {
			slot->event = os_event_create(NULL);
			ut_a(slot->event);
osku's avatar
osku committed
1583
		}
1584

1585 1586 1587
		os_event_reset(slot->event);
		slot->suspended = TRUE;
		slot->suspend_time = ut_time();
osku's avatar
osku committed
1588 1589
	}

1590 1591 1592
	if (slot == srv_sys->last_slot) {
		++srv_sys->last_slot;
	}
1593

1594 1595 1596
	ut_ad(srv_sys->last_slot <= srv_sys->waiting_threads+ OS_THREAD_MAX_N);

	srv_sys_mutex_exit();
osku's avatar
osku committed
1597 1598 1599 1600

	return(slot);
}

1601
/***************************************************************//**
osku's avatar
osku committed
1602 1603 1604 1605 1606
Puts a MySQL OS thread to wait for a lock to be released. If an error
occurs during the wait trx->error_state associated with thr is
!= DB_SUCCESS when we return. DB_LOCK_WAIT_TIMEOUT and DB_DEADLOCK
are possible errors. DB_DEADLOCK is returned if selective deadlock
resolution chose this transaction as a victim. */
1607
UNIV_INTERN
osku's avatar
osku committed
1608 1609 1610
void
srv_suspend_mysql_thread(
/*=====================*/
1611
	que_thr_t*	thr)	/*!< in: query thread associated with the MySQL
osku's avatar
osku committed
1612 1613 1614 1615 1616
				OS thread */
{
	srv_slot_t*	slot;
	double		wait_time;
	trx_t*		trx;
1617
	ulint		had_dict_lock;
osku's avatar
osku committed
1618
	ibool		was_declared_inside_innodb	= FALSE;
1619 1620
	ib_int64_t	start_time			= 0;
	ib_int64_t	finish_time;
osku's avatar
osku committed
1621 1622 1623
	ulint		diff_time;
	ulint		sec;
	ulint		ms;
1624
	ulong		lock_wait_timeout;
osku's avatar
osku committed
1625 1626 1627 1628

	ut_ad(!mutex_own(&kernel_mutex));

	trx = thr_get_trx(thr);
1629

osku's avatar
osku committed
1630 1631 1632 1633 1634 1635 1636 1637 1638
	os_event_set(srv_lock_timeout_thread_event);

	mutex_enter(&kernel_mutex);

	trx->error_state = DB_SUCCESS;

	if (thr->state == QUE_THR_RUNNING) {

		ut_ad(thr->is_active == TRUE);
1639

osku's avatar
osku committed
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
		/* The lock has already been released or this transaction
		was chosen as a deadlock victim: no need to suspend */

		if (trx->was_chosen_as_deadlock_victim) {

			trx->error_state = DB_DEADLOCK;
			trx->was_chosen_as_deadlock_victim = FALSE;
		}

		mutex_exit(&kernel_mutex);

		return;
	}
1653

osku's avatar
osku committed
1654 1655
	ut_ad(thr->is_active == FALSE);

1656
	slot = srv_table_reserve_slot_for_mysql(thr);
osku's avatar
osku committed
1657 1658 1659 1660 1661

	if (thr->lock_state == QUE_THR_LOCK_ROW) {
		srv_n_lock_wait_count++;
		srv_n_lock_wait_current_count++;

1662 1663 1664 1665 1666
		if (ut_usectime(&sec, &ms) == -1) {
			start_time = -1;
		} else {
			start_time = (ib_int64_t) sec * 1000000 + ms;
		}
osku's avatar
osku committed
1667 1668 1669 1670
	}
	/* Wake the lock timeout monitor thread, if it is suspended */

	os_event_set(srv_lock_timeout_thread_event);
1671

osku's avatar
osku committed
1672 1673 1674 1675 1676
	mutex_exit(&kernel_mutex);

	if (trx->declared_to_be_inside_innodb) {

		was_declared_inside_innodb = TRUE;
1677

osku's avatar
osku committed
1678 1679 1680
		/* We must declare this OS thread to exit InnoDB, since a
		possible other thread holding a lock which this thread waits
		for must be allowed to enter, sooner or later */
1681

osku's avatar
osku committed
1682 1683 1684
		srv_conc_force_exit_innodb(trx);
	}

1685
	had_dict_lock = trx->dict_operation_lock_mode;
osku's avatar
osku committed
1686

1687 1688 1689
	switch (had_dict_lock) {
	case RW_S_LATCH:
		/* Release foreign key check latch */
osku's avatar
osku committed
1690
		row_mysql_unfreeze_data_dictionary(trx);
1691 1692 1693 1694 1695
		break;
	case RW_X_LATCH:
		/* Release fast index creation latch */
		row_mysql_unlock_data_dictionary(trx);
		break;
osku's avatar
osku committed
1696 1697 1698 1699
	}

	ut_a(trx->dict_operation_lock_mode == 0);

1700
	/* Suspend this thread and wait for the event. */
1701

1702
	os_event_wait(slot->event);
osku's avatar
osku committed
1703

1704 1705 1706
	/* After resuming, reacquire the data dictionary latch if
	necessary. */

1707 1708
	switch (had_dict_lock) {
	case RW_S_LATCH:
osku's avatar
osku committed
1709
		row_mysql_freeze_data_dictionary(trx);
1710 1711 1712 1713
		break;
	case RW_X_LATCH:
		row_mysql_lock_data_dictionary(trx);
		break;
osku's avatar
osku committed
1714 1715 1716 1717 1718
	}

	if (was_declared_inside_innodb) {

		/* Return back inside InnoDB */
1719

osku's avatar
osku committed
1720 1721 1722
		srv_conc_force_enter_innodb(trx);
	}

1723 1724
	wait_time = ut_difftime(ut_time(), slot->suspend_time);

osku's avatar
osku committed
1725 1726 1727
	mutex_enter(&kernel_mutex);

	/* Release the slot for others to use */
1728

1729
	srv_table_release_slot_for_mysql(slot);
osku's avatar
osku committed
1730 1731

	if (thr->lock_state == QUE_THR_LOCK_ROW) {
1732 1733 1734 1735 1736
		if (ut_usectime(&sec, &ms) == -1) {
			finish_time = -1;
		} else {
			finish_time = (ib_int64_t) sec * 1000000 + ms;
		}
osku's avatar
osku committed
1737 1738

		diff_time = (ulint) (finish_time - start_time);
1739

osku's avatar
osku committed
1740 1741
		srv_n_lock_wait_current_count--;
		srv_n_lock_wait_time = srv_n_lock_wait_time + diff_time;
1742 1743 1744 1745
		if (diff_time > srv_n_lock_max_wait_time &&
		    /* only update the variable if we successfully
		    retrieved the start and finish times. See Bug#36819. */
		    start_time != -1 && finish_time != -1) {
osku's avatar
osku committed
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
			srv_n_lock_max_wait_time = diff_time;
		}
	}

	if (trx->was_chosen_as_deadlock_victim) {

		trx->error_state = DB_DEADLOCK;
		trx->was_chosen_as_deadlock_victim = FALSE;
	}

	mutex_exit(&kernel_mutex);

1758 1759 1760 1761 1762 1763
	/* InnoDB system transactions (such as the purge, and
	incomplete transactions that are being rolled back after crash
	recovery) will use the global value of
	innodb_lock_wait_timeout, because trx->mysql_thd == NULL. */
	lock_wait_timeout = thd_lock_wait_timeout(trx->mysql_thd);

1764 1765 1766
	if (trx_is_interrupted(trx)
	    || (lock_wait_timeout < 100000000
		&& wait_time > (double) lock_wait_timeout)) {
osku's avatar
osku committed
1767

1768
		trx->error_state = DB_LOCK_WAIT_TIMEOUT;
osku's avatar
osku committed
1769 1770 1771
	}
}

1772
/********************************************************************//**
osku's avatar
osku committed
1773 1774
Releases a MySQL OS thread waiting for a lock to be released, if the
thread is already suspended. */
1775
UNIV_INTERN
osku's avatar
osku committed
1776 1777 1778
void
srv_release_mysql_thread_if_suspended(
/*==================================*/
1779
	que_thr_t*	thr)	/*!< in: query thread associated with the
1780
				MySQL OS thread	 */
osku's avatar
osku committed
1781 1782 1783
{
	ut_ad(mutex_own(&kernel_mutex));

1784
	if (!srv_sys->lock_wait_timeout) {
1785
		srv_sys_mutex_enter();
1786 1787
	} else {
		ut_ad(srv_sys_mutex_own());
1788 1789 1790
	}

	if (thr->slot != NULL && thr->slot->in_use && thr->slot->thr == thr) {
osku's avatar
osku committed
1791

1792
		os_event_set(thr->slot->event);
osku's avatar
osku committed
1793
	}
1794

1795
	if (!srv_sys->lock_wait_timeout) {
1796 1797
		srv_sys_mutex_exit();
	}
osku's avatar
osku committed
1798 1799
}

1800
/******************************************************************//**
osku's avatar
osku committed
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
Refreshes the values used to calculate per-second averages. */
static
void
srv_refresh_innodb_monitor_stats(void)
/*==================================*/
{
	mutex_enter(&srv_innodb_monitor_mutex);

	srv_last_monitor_time = time(NULL);

	os_aio_refresh_stats();

	btr_cur_n_sea_old = btr_cur_n_sea;
	btr_cur_n_non_sea_old = btr_cur_n_non_sea;

	log_refresh_stats();
1817

irana's avatar
irana committed
1818
	buf_refresh_io_stats_all();
osku's avatar
osku committed
1819 1820 1821 1822 1823 1824 1825 1826 1827

	srv_n_rows_inserted_old = srv_n_rows_inserted;
	srv_n_rows_updated_old = srv_n_rows_updated;
	srv_n_rows_deleted_old = srv_n_rows_deleted;
	srv_n_rows_read_old = srv_n_rows_read;

	mutex_exit(&srv_innodb_monitor_mutex);
}

1828
/******************************************************************//**
1829 1830 1831
Outputs to a file the output of the InnoDB Monitor.
@return FALSE if not all information printed
due to failure to obtain necessary mutex */
1832
UNIV_INTERN
1833
ibool
osku's avatar
osku committed
1834 1835
srv_printf_innodb_monitor(
/*======================*/
1836
	FILE*	file,		/*!< in: output stream */
1837
	ibool	nowait,		/*!< in: whether to wait for kernel mutex */
1838
	ulint*	trx_start,	/*!< out: file position of the start of
osku's avatar
osku committed
1839
				the list of active transactions */
1840
	ulint*	trx_end)	/*!< out: file position of the end of
osku's avatar
osku committed
1841 1842 1843 1844
				the list of active transactions */
{
	double	time_elapsed;
	time_t	current_time;
1845
	ulint	n_reserved;
1846
	ibool	ret;
osku's avatar
osku committed
1847 1848 1849 1850 1851 1852 1853 1854

	mutex_enter(&srv_innodb_monitor_mutex);

	current_time = time(NULL);

	/* We add 0.001 seconds to time_elapsed to prevent division
	by zero if two users happen to call SHOW INNODB STATUS at the same
	time */
1855

osku's avatar
osku committed
1856
	time_elapsed = difftime(current_time, srv_last_monitor_time)
1857
		+ 0.001;
osku's avatar
osku committed
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869

	srv_last_monitor_time = time(NULL);

	fputs("\n=====================================\n", file);

	ut_print_timestamp(file);
	fprintf(file,
		" INNODB MONITOR OUTPUT\n"
		"=====================================\n"
		"Per second averages calculated from the last %lu seconds\n",
		(ulong)time_elapsed);

1870 1871 1872
	fputs("-----------------\n"
	      "BACKGROUND THREAD\n"
	      "-----------------\n", file);
1873 1874
	srv_print_master_thread_info(file);

osku's avatar
osku committed
1875
	fputs("----------\n"
1876 1877
	      "SEMAPHORES\n"
	      "----------\n", file);
osku's avatar
osku committed
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
	sync_print(file);

	/* Conceptually, srv_innodb_monitor_mutex has a very high latching
	order level in sync0sync.h, while dict_foreign_err_mutex has a very
	low level 135. Therefore we can reserve the latter mutex here without
	a danger of a deadlock of threads. */

	mutex_enter(&dict_foreign_err_mutex);

	if (ftell(dict_foreign_err_file) != 0L) {
		fputs("------------------------\n"
1889 1890
		      "LATEST FOREIGN KEY ERROR\n"
		      "------------------------\n", file);
osku's avatar
osku committed
1891 1892 1893 1894 1895
		ut_copy_file(file, dict_foreign_err_file);
	}

	mutex_exit(&dict_foreign_err_mutex);

1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
	/* Only if lock_print_info_summary proceeds correctly,
	before we call the lock_print_info_all_transactions
	to print all the lock information. */
	ret = lock_print_info_summary(file, nowait);

	if (ret) {
		if (trx_start) {
			long	t = ftell(file);
			if (t < 0) {
				*trx_start = ULINT_UNDEFINED;
			} else {
				*trx_start = (ulint) t;
			}
osku's avatar
osku committed
1909
		}
1910 1911 1912 1913 1914 1915 1916 1917
		lock_print_info_all_transactions(file);
		if (trx_end) {
			long	t = ftell(file);
			if (t < 0) {
				*trx_end = ULINT_UNDEFINED;
			} else {
				*trx_end = (ulint) t;
			}
osku's avatar
osku committed
1918 1919
		}
	}
1920

osku's avatar
osku committed
1921
	fputs("--------\n"
1922 1923
	      "FILE I/O\n"
	      "--------\n", file);
osku's avatar
osku committed
1924 1925 1926
	os_aio_print(file);

	fputs("-------------------------------------\n"
1927 1928
	      "INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
	      "-------------------------------------\n", file);
osku's avatar
osku committed
1929 1930 1931 1932 1933 1934
	ibuf_print(file);

	ha_print_info(file, btr_search_sys->hash_index);

	fprintf(file,
		"%.2f hash searches/s, %.2f non-hash searches/s\n",
1935 1936 1937 1938
		(btr_cur_n_sea - btr_cur_n_sea_old)
		/ time_elapsed,
		(btr_cur_n_non_sea - btr_cur_n_non_sea_old)
		/ time_elapsed);
osku's avatar
osku committed
1939 1940 1941 1942
	btr_cur_n_sea_old = btr_cur_n_sea;
	btr_cur_n_non_sea_old = btr_cur_n_non_sea;

	fputs("---\n"
1943 1944
	      "LOG\n"
	      "---\n", file);
osku's avatar
osku committed
1945 1946 1947
	log_print(file);

	fputs("----------------------\n"
1948 1949
	      "BUFFER POOL AND MEMORY\n"
	      "----------------------\n", file);
osku's avatar
osku committed
1950
	fprintf(file,
1951 1952 1953 1954
		"Total memory allocated " ULINTPF
		"; in additional pool allocated " ULINTPF "\n",
		ut_total_allocated_memory,
		mem_pool_get_reserved(mem_comm_pool));
1955 1956
	fprintf(file, "Dictionary memory allocated " ULINTPF "\n",
		dict_sys->size);
osku's avatar
osku committed
1957 1958 1959 1960

	buf_print_io(file);

	fputs("--------------\n"
1961 1962
	      "ROW OPERATIONS\n"
	      "--------------\n", file);
osku's avatar
osku committed
1963
	fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n",
1964 1965
		(long) srv_conc_n_threads,
		(ulong) srv_conc_n_waiting_threads);
osku's avatar
osku committed
1966 1967

	fprintf(file, "%lu read views open inside InnoDB\n",
1968
		UT_LIST_GET_LEN(trx_sys->view_list));
osku's avatar
osku committed
1969

1970 1971 1972
	n_reserved = fil_space_get_n_reserved_extents(0);
	if (n_reserved > 0) {
		fprintf(file,
1973 1974
			"%lu tablespace extents now reserved for"
			" B-tree split operations\n",
1975 1976
			(ulong) n_reserved);
	}
osku's avatar
osku committed
1977 1978 1979

#ifdef UNIV_LINUX
	fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n",
1980 1981 1982
		(ulong) srv_main_thread_process_no,
		(ulong) srv_main_thread_id,
		srv_main_thread_op_info);
osku's avatar
osku committed
1983 1984
#else
	fprintf(file, "Main thread id %lu, state: %s\n",
1985 1986
		(ulong) srv_main_thread_id,
		srv_main_thread_op_info);
osku's avatar
osku committed
1987 1988
#endif
	fprintf(file,
1989 1990 1991 1992 1993 1994 1995
		"Number of rows inserted " ULINTPF
		", updated " ULINTPF ", deleted " ULINTPF
		", read " ULINTPF "\n",
		srv_n_rows_inserted,
		srv_n_rows_updated,
		srv_n_rows_deleted,
		srv_n_rows_read);
osku's avatar
osku committed
1996
	fprintf(file,
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
		"%.2f inserts/s, %.2f updates/s,"
		" %.2f deletes/s, %.2f reads/s\n",
		(srv_n_rows_inserted - srv_n_rows_inserted_old)
		/ time_elapsed,
		(srv_n_rows_updated - srv_n_rows_updated_old)
		/ time_elapsed,
		(srv_n_rows_deleted - srv_n_rows_deleted_old)
		/ time_elapsed,
		(srv_n_rows_read - srv_n_rows_read_old)
		/ time_elapsed);

	srv_n_rows_inserted_old = srv_n_rows_inserted;
osku's avatar
osku committed
2009 2010 2011 2012
	srv_n_rows_updated_old = srv_n_rows_updated;
	srv_n_rows_deleted_old = srv_n_rows_deleted;
	srv_n_rows_read_old = srv_n_rows_read;

2013 2014 2015
	fputs("----------------------------\n"
	      "END OF INNODB MONITOR OUTPUT\n"
	      "============================\n", file);
osku's avatar
osku committed
2016 2017
	mutex_exit(&srv_innodb_monitor_mutex);
	fflush(file);
2018 2019

	return(ret);
osku's avatar
osku committed
2020 2021
}

2022
/******************************************************************//**
osku's avatar
osku committed
2023
Function to pass InnoDB status variables to MySQL */
2024
UNIV_INTERN
osku's avatar
osku committed
2025 2026
void
srv_export_innodb_status(void)
2027
/*==========================*/
osku's avatar
osku committed
2028
{
irana's avatar
irana committed
2029 2030 2031 2032 2033 2034 2035 2036
	buf_pool_stat_t	stat;
	ulint		LRU_len;
	ulint		free_len;
	ulint		flush_list_len;

	buf_get_total_stat(&stat);
	buf_get_total_list_len(&LRU_len, &free_len, &flush_list_len);

2037
	mutex_enter(&srv_innodb_monitor_mutex);
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050

	export_vars.innodb_data_pending_reads
		= os_n_pending_reads;
	export_vars.innodb_data_pending_writes
		= os_n_pending_writes;
	export_vars.innodb_data_pending_fsyncs
		= fil_n_pending_log_flushes
		+ fil_n_pending_tablespace_flushes;
	export_vars.innodb_data_fsyncs = os_n_fsyncs;
	export_vars.innodb_data_read = srv_data_read;
	export_vars.innodb_data_reads = os_n_file_reads;
	export_vars.innodb_data_writes = os_n_file_writes;
	export_vars.innodb_data_written = srv_data_written;
irana's avatar
irana committed
2051
	export_vars.innodb_buffer_pool_read_requests = stat.n_page_gets;
2052 2053 2054 2055 2056
	export_vars.innodb_buffer_pool_write_requests
		= srv_buf_pool_write_requests;
	export_vars.innodb_buffer_pool_wait_free = srv_buf_pool_wait_free;
	export_vars.innodb_buffer_pool_pages_flushed = srv_buf_pool_flushed;
	export_vars.innodb_buffer_pool_reads = srv_buf_pool_reads;
2057
	export_vars.innodb_buffer_pool_read_ahead
irana's avatar
irana committed
2058
		= stat.n_ra_pages_read;
2059
	export_vars.innodb_buffer_pool_read_ahead_evicted
irana's avatar
irana committed
2060 2061 2062 2063
		= stat.n_ra_pages_evicted;
	export_vars.innodb_buffer_pool_pages_data = LRU_len;
	export_vars.innodb_buffer_pool_pages_dirty = flush_list_len;
	export_vars.innodb_buffer_pool_pages_free = free_len;
2064
#ifdef UNIV_DEBUG
2065 2066
	export_vars.innodb_buffer_pool_pages_latched
		= buf_get_latched_pages_number();
2067
#endif /* UNIV_DEBUG */
irana's avatar
irana committed
2068
	export_vars.innodb_buffer_pool_pages_total = buf_pool_get_curr_size();
2069

irana's avatar
irana committed
2070
	export_vars.innodb_buffer_pool_pages_misc = buf_pool_get_curr_size();
2071
#ifdef HAVE_ATOMIC_BUILTINS
2072 2073 2074 2075
	export_vars.innodb_have_atomic_builtins = 1;
#else
	export_vars.innodb_have_atomic_builtins = 0;
#endif
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
	export_vars.innodb_page_size = UNIV_PAGE_SIZE;
	export_vars.innodb_log_waits = srv_log_waits;
	export_vars.innodb_os_log_written = srv_os_log_written;
	export_vars.innodb_os_log_fsyncs = fil_n_log_flushes;
	export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes;
	export_vars.innodb_os_log_pending_writes = srv_os_log_pending_writes;
	export_vars.innodb_log_write_requests = srv_log_write_requests;
	export_vars.innodb_log_writes = srv_log_writes;
	export_vars.innodb_dblwr_pages_written = srv_dblwr_pages_written;
	export_vars.innodb_dblwr_writes = srv_dblwr_writes;
irana's avatar
irana committed
2086 2087 2088
	export_vars.innodb_pages_created = stat.n_pages_created;
	export_vars.innodb_pages_read = stat.n_pages_read;
	export_vars.innodb_pages_written = stat.n_pages_written;
2089 2090 2091
	export_vars.innodb_row_lock_waits = srv_n_lock_wait_count;
	export_vars.innodb_row_lock_current_waits
		= srv_n_lock_wait_current_count;
2092
	export_vars.innodb_row_lock_time = srv_n_lock_wait_time / 1000;
osku's avatar
osku committed
2093 2094
	if (srv_n_lock_wait_count > 0) {
		export_vars.innodb_row_lock_time_avg = (ulint)
2095
			(srv_n_lock_wait_time / 1000 / srv_n_lock_wait_count);
osku's avatar
osku committed
2096 2097 2098
	} else {
		export_vars.innodb_row_lock_time_avg = 0;
	}
2099
	export_vars.innodb_row_lock_time_max
2100
		= srv_n_lock_max_wait_time / 1000;
2101 2102 2103 2104
	export_vars.innodb_rows_read = srv_n_rows_read;
	export_vars.innodb_rows_inserted = srv_n_rows_inserted;
	export_vars.innodb_rows_updated = srv_n_rows_updated;
	export_vars.innodb_rows_deleted = srv_n_rows_deleted;
osku's avatar
osku committed
2105

2106
	mutex_exit(&srv_innodb_monitor_mutex);
osku's avatar
osku committed
2107 2108
}

2109
/*********************************************************************//**
2110
A thread which prints the info output by various InnoDB monitors.
2111
@return	a dummy parameter */
2112
UNIV_INTERN
2113
os_thread_ret_t
2114 2115
srv_monitor_thread(
/*===============*/
osku's avatar
osku committed
2116
	void*	arg __attribute__((unused)))
2117
			/*!< in: a dummy parameter required by
osku's avatar
osku committed
2118 2119 2120
			os_thread_create */
{
	double		time_elapsed;
2121
	time_t		current_time;
osku's avatar
osku committed
2122
	time_t		last_table_monitor_time;
2123
	time_t		last_tablespace_monitor_time;
osku's avatar
osku committed
2124
	time_t		last_monitor_time;
2125 2126
	ulint		mutex_skipped;
	ibool		last_srv_print_monitor;
osku's avatar
osku committed
2127 2128 2129

#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Lock timeout thread starts, id %lu\n",
2130
		os_thread_pf(os_thread_get_curr_id()));
osku's avatar
osku committed
2131
#endif
2132 2133 2134 2135 2136

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_monitor_thread_key);
#endif

osku's avatar
osku committed
2137 2138 2139
	UT_NOT_USED(arg);
	srv_last_monitor_time = time(NULL);
	last_table_monitor_time = time(NULL);
2140
	last_tablespace_monitor_time = time(NULL);
osku's avatar
osku committed
2141
	last_monitor_time = time(NULL);
2142 2143
	mutex_skipped = 0;
	last_srv_print_monitor = srv_print_innodb_monitor;
osku's avatar
osku committed
2144
loop:
2145
	srv_monitor_active = TRUE;
osku's avatar
osku committed
2146

2147 2148
	/* Wake up every 5 seconds to see if we need to print
	monitor information. */
osku's avatar
osku committed
2149

2150
	os_thread_sleep(5000000);
osku's avatar
osku committed
2151 2152 2153 2154

	current_time = time(NULL);

	time_elapsed = difftime(current_time, last_monitor_time);
2155

osku's avatar
osku committed
2156
	if (time_elapsed > 15) {
2157
		last_monitor_time = time(NULL);
osku's avatar
osku committed
2158

2159
		if (srv_print_innodb_monitor) {
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
			/* Reset mutex_skipped counter everytime
			srv_print_innodb_monitor changes. This is to
			ensure we will not be blocked by kernel_mutex
			for short duration information printing,
			such as requested by sync_array_print_long_waits() */
			if (!last_srv_print_monitor) {
				mutex_skipped = 0;
				last_srv_print_monitor = TRUE;
			}

			if (!srv_printf_innodb_monitor(stderr,
						MUTEX_NOWAIT(mutex_skipped),
						NULL, NULL)) {
				mutex_skipped++;
			} else {
				/* Reset the counter */
				mutex_skipped = 0;
			}
		} else {
			last_srv_print_monitor = FALSE;
2180
		}
osku's avatar
osku committed
2181

2182

2183 2184 2185
		if (srv_innodb_status) {
			mutex_enter(&srv_monitor_file_mutex);
			rewind(srv_monitor_file);
2186 2187 2188 2189 2190 2191 2192 2193
			if (!srv_printf_innodb_monitor(srv_monitor_file,
						MUTEX_NOWAIT(mutex_skipped),
						NULL, NULL)) {
				mutex_skipped++;
			} else {
				mutex_skipped = 0;
			}

2194 2195 2196
			os_file_set_eof(srv_monitor_file);
			mutex_exit(&srv_monitor_file_mutex);
		}
osku's avatar
osku committed
2197

2198
		if (srv_print_innodb_tablespace_monitor
2199 2200 2201
		    && difftime(current_time,
				last_tablespace_monitor_time) > 60) {
			last_tablespace_monitor_time = time(NULL);
osku's avatar
osku committed
2202

2203 2204 2205
			fputs("========================"
			      "========================\n",
			      stderr);
osku's avatar
osku committed
2206

2207
			ut_print_timestamp(stderr);
osku's avatar
osku committed
2208

2209
			fputs(" INNODB TABLESPACE MONITOR OUTPUT\n"
2210 2211 2212
			      "========================"
			      "========================\n",
			      stderr);
osku's avatar
osku committed
2213

2214 2215 2216 2217
			fsp_print(0);
			fputs("Validating tablespace\n", stderr);
			fsp_validate(0);
			fputs("Validation ok\n"
2218 2219 2220 2221
			      "---------------------------------------\n"
			      "END OF INNODB TABLESPACE MONITOR OUTPUT\n"
			      "=======================================\n",
			      stderr);
2222
		}
osku's avatar
osku committed
2223

2224
		if (srv_print_innodb_table_monitor
2225
		    && difftime(current_time, last_table_monitor_time) > 60) {
osku's avatar
osku committed
2226

2227
			last_table_monitor_time = time(NULL);
osku's avatar
osku committed
2228

2229 2230
			fputs("===========================================\n",
			      stderr);
2231 2232

			ut_print_timestamp(stderr);
osku's avatar
osku committed
2233

2234
			fputs(" INNODB TABLE MONITOR OUTPUT\n"
2235 2236
			      "===========================================\n",
			      stderr);
2237
			dict_print();
osku's avatar
osku committed
2238

2239
			fputs("-----------------------------------\n"
2240 2241 2242
			      "END OF INNODB TABLE MONITOR OUTPUT\n"
			      "==================================\n",
			      stderr);
2243
		}
osku's avatar
osku committed
2244 2245
	}

2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
	if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
		goto exit_func;
	}

	if (srv_print_innodb_monitor
	    || srv_print_innodb_lock_monitor
	    || srv_print_innodb_tablespace_monitor
	    || srv_print_innodb_table_monitor) {
		goto loop;
	}

	srv_monitor_active = FALSE;

	goto loop;

exit_func:
	srv_monitor_active = FALSE;

	/* We count the number of threads in os_thread_exit(). A created
	thread should always use that to exit and not use return() to exit. */

	os_thread_exit(NULL);

	OS_THREAD_DUMMY_RETURN;
}

2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283
/*********************************************************************//**
Check if the thread lock wait has timed out. Release its locks if the
wait has actually timed out. */
UNIV_INTERN
void
srv_lock_check_wait(
/*================*/
	srv_slot_t*	slot)
{
	trx_t*		trx;
	double		wait_time;
	ulong		lock_wait_timeout;
2284
	ib_time_t	suspend_time = slot->suspend_time;
2285 2286 2287

	ut_ad(srv_sys_mutex_own());

2288
	wait_time = ut_difftime(ut_time(), suspend_time);
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327

	trx = thr_get_trx(slot->thr);

	lock_wait_timeout = thd_lock_wait_timeout(trx->mysql_thd);

	if (trx_is_interrupted(trx)
	    || (lock_wait_timeout < 100000000
		&& (wait_time > (double) lock_wait_timeout
		   || wait_time < 0))) {

		/* Timeout exceeded or a wrap-around in system
		time counter: cancel the lock request queued
		by the transaction and release possible
		other transactions waiting behind; it is
		possible that the lock has already been
		granted: in that case do nothing */

		if (trx->wait_lock) {
			trx_t*	slot_trx;

			/* Release the srv_sys_t->mutex to preserve the
			latch order only. */
			srv_sys_mutex_exit();

			/* It is possible that the thread has already
			freed its slot and released its locks and another
			thread is now using this slot. We need to
			check whether the slot is still in use by the
			same thread before cancelling the wait and releasing
		       	the locks. */

			mutex_enter(&kernel_mutex);

			srv_sys_mutex_enter();

			slot_trx = thr_get_trx(slot->thr);

			/* We can't compare the pointers here because the
			memory can be recycled. Transaction ids are not
2328 2329 2330 2331 2332
			recyled and therefore safe to use. We also check if
			the transaction suspend time is the same that we
			used for calculating the wait earlier. If the
		       	transaction has already released its locks there
		       	is nothing more we can do. */
2333
			if (slot->in_use
2334
			    && suspend_time == slot->suspend_time
2335 2336 2337
			    && ut_dulint_cmp(trx->id, slot_trx->id) == 0
			    && trx->wait_lock != NULL) {

2338
				ut_a(!srv_sys->lock_wait_timeout);
2339 2340
				ut_a(trx->que_state == TRX_QUE_LOCK_WAIT);

2341
				srv_sys->lock_wait_timeout = TRUE;
2342 2343 2344

				lock_cancel_waiting_and_release(trx->wait_lock);

2345
				srv_sys->lock_wait_timeout = FALSE;
2346 2347 2348 2349 2350 2351 2352
			}

			mutex_exit(&kernel_mutex);
		}
	}
}

2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
/*********************************************************************//**
A thread which wakes up threads whose lock wait may have lasted too long.
@return	a dummy parameter */
UNIV_INTERN
os_thread_ret_t
srv_lock_timeout_thread(
/*====================*/
	void*	arg __attribute__((unused)))
			/* in: a dummy parameter required by
			os_thread_create */
{
	srv_slot_t*	slot;
	ibool		some_waits;

2367 2368 2369 2370
#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_lock_timeout_thread_key);
#endif

2371 2372 2373 2374 2375 2376 2377 2378
loop:
	/* When someone is waiting for a lock, we wake up every second
	and check if a timeout has passed for a lock wait */

	os_thread_sleep(1000000);

	srv_lock_timeout_active = TRUE;

2379
	srv_sys_mutex_enter();
osku's avatar
osku committed
2380 2381 2382

	some_waits = FALSE;

2383 2384
	/* Check all slots for user threads that are waiting on locks, and
	if they have exceeded the time limit. */
osku's avatar
osku committed
2385

2386 2387 2388
	for (slot = srv_sys->waiting_threads;
	     slot < srv_sys->last_slot;
	     ++slot) {
osku's avatar
osku committed
2389 2390 2391

		if (slot->in_use) {
			some_waits = TRUE;
2392
			srv_lock_check_wait(slot);
osku's avatar
osku committed
2393 2394 2395 2396 2397
		}
	}

	os_event_reset(srv_lock_timeout_thread_event);

2398
	srv_sys_mutex_exit();
osku's avatar
osku committed
2399 2400 2401 2402 2403

	if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
		goto exit_func;
	}

2404
	if (some_waits) {
osku's avatar
osku committed
2405 2406 2407
		goto loop;
	}

2408
	srv_lock_timeout_active = FALSE;
osku's avatar
osku committed
2409 2410 2411 2412 2413 2414 2415 2416 2417

#if 0
	/* The following synchronisation is disabled, since
	the InnoDB monitor output is to be updated every 15 seconds. */
	os_event_wait(srv_lock_timeout_thread_event);
#endif
	goto loop;

exit_func:
2418
	srv_lock_timeout_active = FALSE;
osku's avatar
osku committed
2419 2420 2421 2422 2423

	/* We count the number of threads in os_thread_exit(). A created
	thread should always use that to exit and not use return() to exit. */

	os_thread_exit(NULL);
2424 2425

	OS_THREAD_DUMMY_RETURN;
osku's avatar
osku committed
2426 2427
}

2428
/*********************************************************************//**
osku's avatar
osku committed
2429
A thread which prints warnings about semaphore waits which have lasted
2430 2431
too long. These can be used to track bugs which cause hangs.
@return	a dummy parameter */
2432
UNIV_INTERN
2433
os_thread_ret_t
osku's avatar
osku committed
2434 2435 2436
srv_error_monitor_thread(
/*=====================*/
	void*	arg __attribute__((unused)))
2437
			/*!< in: a dummy parameter required by
osku's avatar
osku committed
2438 2439 2440
			os_thread_create */
{
	/* number of successive fatal timeouts observed */
2441
	ulint		fatal_cnt	= 0;
2442 2443
	ib_uint64_t	old_lsn;
	ib_uint64_t	new_lsn;
osku's avatar
osku committed
2444 2445 2446 2447 2448

	old_lsn = srv_start_lsn;

#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Error monitor thread starts, id %lu\n",
2449
		os_thread_pf(os_thread_get_curr_id()));
osku's avatar
osku committed
2450
#endif
2451 2452

#ifdef UNIV_PFS_THREAD
irana's avatar
irana committed
2453
	pfs_register_thread(srv_error_monitor_thread_key);
2454 2455
#endif

osku's avatar
osku committed
2456 2457 2458 2459 2460 2461 2462 2463
loop:
	srv_error_monitor_active = TRUE;

	/* Try to track a strange bug reported by Harald Fuchs and others,
	where the lsn seems to decrease at times */

	new_lsn = log_get_lsn();

2464
	if (new_lsn < old_lsn) {
osku's avatar
osku committed
2465 2466
		ut_print_timestamp(stderr);
		fprintf(stderr,
2467
			"  InnoDB: Error: old log sequence number %llu"
2468
			" was greater\n"
2469
			"InnoDB: than the new log sequence number %llu!\n"
2470 2471
			"InnoDB: Please submit a bug report"
			" to http://bugs.mysql.com\n",
2472
			old_lsn, new_lsn);
osku's avatar
osku committed
2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483
	}

	old_lsn = new_lsn;

	if (difftime(time(NULL), srv_last_monitor_time) > 60) {
		/* We referesh InnoDB Monitor values so that averages are
		printed from at most 60 last seconds */

		srv_refresh_innodb_monitor_stats();
	}

2484
	/* Update the statistics collected for deciding LRU
2485
	eviction policy. */
2486 2487
	buf_LRU_stat_update();

2488 2489 2490
	/* Update the statistics collected for flush rate policy. */
	buf_flush_stat_update();

2491 2492 2493
	/* In case mutex_exit is not a memory barrier, it is
	theoretically possible some threads are left waiting though
	the semaphore is already released. Wake up those threads: */
2494

2495 2496
	sync_arr_wake_threads_if_sema_free();

osku's avatar
osku committed
2497 2498
	if (sync_array_print_long_waits()) {
		fatal_cnt++;
2499
		if (fatal_cnt > 10) {
osku's avatar
osku committed
2500 2501

			fprintf(stderr,
2502 2503 2504 2505 2506
				"InnoDB: Error: semaphore wait has lasted"
				" > %lu seconds\n"
				"InnoDB: We intentionally crash the server,"
				" because it appears to be hung.\n",
				(ulong) srv_fatal_semaphore_wait_threshold);
osku's avatar
osku committed
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518

			ut_error;
		}
	} else {
		fatal_cnt = 0;
	}

	/* Flush stderr so that a database user gets the output
	to possible MySQL error file */

	fflush(stderr);

2519
	os_thread_sleep(1000000);
osku's avatar
osku committed
2520

2521
	if (srv_shutdown_state < SRV_SHUTDOWN_CLEANUP) {
osku's avatar
osku committed
2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532

		goto loop;
	}

	srv_error_monitor_active = FALSE;

	/* We count the number of threads in os_thread_exit(). A created
	thread should always use that to exit and not use return() to exit. */

	os_thread_exit(NULL);

2533
	OS_THREAD_DUMMY_RETURN;
osku's avatar
osku committed
2534 2535
}

2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
/******************************************************************//**
Increment the server activity count. */
UNIV_INLINE
void
srv_inc_activity_count_low(void)
/*============================*/
{
	srv_sys_mutex_enter();

	++srv_sys->activity_count;

	srv_sys_mutex_exit();
}

/******************************************************************//**
Increment the server activity count. */
UNIV_INTERN
void
srv_inc_activity_count(void)
/*========================*/
{
	srv_inc_activity_count_low();
}

/**********************************************************************//**
Check whether the master thread is active.
@return FALSE is it is not active. */
UNIV_INTERN
ibool
srv_is_master_thread_active(void)
/*=============================*/
{
	ibool	ret;

	srv_sys_mutex_enter();

	ret = srv_sys->n_threads_active[SRV_MASTER] != 0;

	srv_sys_mutex_exit();

	return(ret);
}

2579
/*******************************************************************//**
osku's avatar
osku committed
2580 2581 2582
Tells the InnoDB server that there has been activity in the database
and wakes up the master thread if it is suspended (not sleeping). Used
in the MySQL interface. Note that there is a small chance that the master
2583 2584
thread stays suspended (we do not protect our operation with the
srv_sys_t->mutex, for performance reasons). */
2585
UNIV_INTERN
osku's avatar
osku committed
2586 2587 2588 2589
void
srv_active_wake_master_thread(void)
/*===============================*/
{
2590 2591
	ut_ad(!mutex_own(&kernel_mutex));
	ut_ad(!srv_sys_mutex_own());
2592

2593
	srv_inc_activity_count_low();
osku's avatar
osku committed
2594

2595
	if (srv_sys->n_threads_active[SRV_MASTER] == 0) {
osku's avatar
osku committed
2596 2597 2598 2599 2600

		srv_release_threads(SRV_MASTER, 1);
	}
}

2601 2602 2603 2604
/*******************************************************************//**
Tells the purge thread that there has been activity in the database
and wakes up the purge thread if it is suspended (not sleeping).  Note
that there is a small chance that the purge thread stays suspended
2605 2606
(we do not protect our operation with the srv_sys_t:mutex, for
performance reasons). */
2607 2608 2609 2610 2611 2612
UNIV_INTERN
void
srv_wake_purge_thread_if_not_active(void)
/*=====================================*/
{
	ut_ad(!mutex_own(&kernel_mutex));
2613
	ut_ad(!srv_sys_mutex_own());
2614 2615

	if (srv_n_purge_threads > 0
2616
	    && srv_sys->n_threads_active[SRV_WORKER] == 0) {
2617 2618 2619 2620 2621

		srv_release_threads(SRV_WORKER, 1);
	}
}

2622
/*******************************************************************//**
osku's avatar
osku committed
2623
Wakes up the master thread if it is suspended or being suspended. */
2624
UNIV_INTERN
osku's avatar
osku committed
2625 2626 2627 2628
void
srv_wake_master_thread(void)
/*========================*/
{
2629 2630
	ut_ad(!mutex_own(&kernel_mutex));
	ut_ad(!srv_sys_mutex_own());
2631

2632
	srv_inc_activity_count_low();
osku's avatar
osku committed
2633 2634 2635 2636

	srv_release_threads(SRV_MASTER, 1);
}

2637 2638 2639 2640 2641 2642 2643 2644
/*******************************************************************//**
Wakes up the purge thread if it's not already awake. */
UNIV_INTERN
void
srv_wake_purge_thread(void)
/*=======================*/
{
	ut_ad(!mutex_own(&kernel_mutex));
2645
	ut_ad(!srv_sys_mutex_own());
2646 2647 2648 2649 2650 2651 2652

	if (srv_n_purge_threads > 0) {

		srv_release_threads(SRV_WORKER, 1);
	}
}

2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
/*******************************************************************//**
Check if there has been any activity.
@return FALSE if no hange in activity counter. */
UNIV_INLINE
ibool
srv_check_activity(
/*===============*/
	ulint		old_activity_count)	/*!< old activity count */
{
	ibool		ret;

	srv_sys_mutex_enter();

	ret = srv_sys->activity_count != old_activity_count;

	srv_sys_mutex_exit();

	return(ret);
}

2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
/**********************************************************************
The master thread is tasked to ensure that flush of log file happens
once every second in the background. This is to ensure that not more
than one second of trxs are lost in case of crash when
innodb_flush_logs_at_trx_commit != 1 */
static
void
srv_sync_log_buffer_in_background(void)
/*===================================*/
{
	time_t	current_time = time(NULL);

	srv_main_thread_op_info = "flushing log";
	if (difftime(current_time, srv_last_log_flush_time) >= 1) {
		log_buffer_sync_in_background(TRUE);
		srv_last_log_flush_time = current_time;
		srv_log_writes_and_flush++;
	}
}

2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
/********************************************************************//**
Do a full purge, reconfigure the purge sub-system if a dynamic
change is detected. */
static
void
srv_master_do_purge(void)
/*=====================*/
{
	ulint	n_pages_purged;

	ut_ad(!mutex_own(&kernel_mutex));

	ut_a(srv_n_purge_threads == 0);

	do {
		/* Check for shutdown and change in purge config. */
		if (srv_fast_shutdown && srv_shutdown_state > 0) {
			/* Nothing to purge. */
			n_pages_purged = 0;
		} else {
			n_pages_purged = trx_purge(srv_purge_batch_size);
		}

		srv_sync_log_buffer_in_background();

	} while (n_pages_purged > 0);
}

2721
/*********************************************************************//**
2722 2723
The master thread controlling the server.
@return	a dummy parameter */
2724
UNIV_INTERN
2725
os_thread_ret_t
osku's avatar
osku committed
2726 2727 2728
srv_master_thread(
/*==============*/
	void*	arg __attribute__((unused)))
2729
			/*!< in: a dummy parameter required by
osku's avatar
osku committed
2730 2731
			os_thread_create */
{
irana's avatar
irana committed
2732
	buf_pool_stat_t buf_stat;
osku's avatar
osku committed
2733 2734
	os_event_t	event;
	ulint		old_activity_count;
2735
	ulint		n_pages_purged	= 0;
osku's avatar
osku committed
2736 2737 2738 2739 2740 2741 2742 2743
	ulint		n_bytes_merged;
	ulint		n_pages_flushed;
	ulint		n_bytes_archived;
	ulint		n_tables_to_drop;
	ulint		n_ios;
	ulint		n_ios_old;
	ulint		n_ios_very_old;
	ulint		n_pend_ios;
irana's avatar
irana committed
2744
	ulint		next_itr_time;
osku's avatar
osku committed
2745
	ulint		i;
2746

osku's avatar
osku committed
2747 2748
#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Master thread starts, id %lu\n",
2749
		os_thread_pf(os_thread_get_curr_id()));
osku's avatar
osku committed
2750
#endif
2751 2752 2753 2754 2755

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_master_thread_key);
#endif

osku's avatar
osku committed
2756 2757
	srv_main_thread_process_no = os_proc_get_number();
	srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());
2758

2759
	srv_sys_mutex_enter();
osku's avatar
osku committed
2760

2761
	srv_table_reserve_slot(SRV_MASTER);
osku's avatar
osku committed
2762

2763
	srv_sys->n_threads_active[SRV_MASTER]++;
osku's avatar
osku committed
2764

2765
	srv_sys_mutex_exit();
osku's avatar
osku committed
2766 2767 2768 2769 2770 2771 2772 2773

loop:
	/*****************************************************************/
	/* ---- When there is database activity by users, we cycle in this
	loop */

	srv_main_thread_op_info = "reserving kernel mutex";

irana's avatar
irana committed
2774 2775 2776
	buf_get_total_stat(&buf_stat);
	n_ios_very_old = log_sys->n_log_ios + buf_stat.n_pages_read
		+ buf_stat.n_pages_written;
2777 2778

	srv_sys_mutex_enter();
osku's avatar
osku committed
2779 2780

	/* Store the user activity counter at the start of this loop */
2781
	old_activity_count = srv_sys->activity_count;
osku's avatar
osku committed
2782

2783
	srv_sys_mutex_exit();
osku's avatar
osku committed
2784 2785 2786 2787 2788 2789 2790 2791 2792

	if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {

		goto suspend_thread;
	}

	/* ---- We run the following loop approximately once per second
	when there is database activity */

2793
	srv_last_log_flush_time = time(NULL);
irana's avatar
irana committed
2794
	next_itr_time = ut_time_ms();
osku's avatar
osku committed
2795 2796

	for (i = 0; i < 10; i++) {
irana's avatar
irana committed
2797
		ulint	cur_time = ut_time_ms();
irana's avatar
irana committed
2798 2799 2800 2801 2802 2803

		buf_get_total_stat(&buf_stat);

		n_ios_old = log_sys->n_log_ios + buf_stat.n_pages_read
			+ buf_stat.n_pages_written;

osku's avatar
osku committed
2804
		srv_main_thread_op_info = "sleeping";
2805
		srv_main_1_second_loops++;
2806

irana's avatar
irana committed
2807
		if (next_itr_time > cur_time) {
osku's avatar
osku committed
2808

irana's avatar
irana committed
2809 2810 2811 2812 2813 2814
			/* Get sleep interval in micro seconds. We use
			ut_min() to avoid long sleep in case of
			wrap around. */
			os_thread_sleep(ut_min(1000000,
					(next_itr_time - cur_time)
					 * 1000));
2815
			srv_main_sleeps++;
osku's avatar
osku committed
2816 2817
		}

irana's avatar
irana committed
2818 2819
		/* Each iteration should happen at 1 second interval. */
		next_itr_time = ut_time_ms() + 1000;
osku's avatar
osku committed
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835

		/* ALTER TABLE in MySQL requires on Unix that the table handler
		can drop tables lazily after there no longer are SELECT
		queries to them. */

		srv_main_thread_op_info = "doing background drop tables";

		row_drop_tables_for_mysql_in_background();

		srv_main_thread_op_info = "";

		if (srv_fast_shutdown && srv_shutdown_state > 0) {

			goto background_loop;
		}

2836 2837
		/* Flush logs if needed */
		srv_sync_log_buffer_in_background();
osku's avatar
osku committed
2838 2839 2840 2841

		srv_main_thread_op_info = "making checkpoint";
		log_free_check();

2842
		/* If i/os during one second sleep were less than 5% of
irana's avatar
irana committed
2843 2844
		capacity, we assume that there is free disk i/o capacity
		available, and it makes sense to do an insert buffer merge. */
osku's avatar
osku committed
2845

irana's avatar
irana committed
2846
		buf_get_total_stat(&buf_stat);
osku's avatar
osku committed
2847
		n_pend_ios = buf_get_n_pending_ios()
2848
			+ log_sys->n_pending_writes;
irana's avatar
irana committed
2849 2850
		n_ios = log_sys->n_log_ios + buf_stat.n_pages_read
			+ buf_stat.n_pages_written;
2851 2852
		if (n_pend_ios < SRV_PEND_IO_THRESHOLD
		    && (n_ios - n_ios_old < SRV_RECENT_IO_ACTIVITY)) {
osku's avatar
osku committed
2853
			srv_main_thread_op_info = "doing insert buffer merge";
2854
			ibuf_contract_for_n_pages(FALSE, PCT_IO(5));
osku's avatar
osku committed
2855

2856 2857
			/* Flush logs if needed */
			srv_sync_log_buffer_in_background();
osku's avatar
osku committed
2858 2859
		}

2860 2861
		if (UNIV_UNLIKELY(buf_get_modified_ratio_pct()
				  > srv_max_buf_pool_modified_pct)) {
osku's avatar
osku committed
2862 2863 2864

			/* Try to keep the number of modified pages in the
			buffer pool under the limit wished by the user */
2865

2866 2867
			srv_main_thread_op_info =
				"flushing buffer pool pages";
irana's avatar
irana committed
2868 2869
			n_pages_flushed = buf_flush_list(
				PCT_IO(100), IB_ULONGLONG_MAX);
osku's avatar
osku committed
2870

2871 2872 2873 2874 2875 2876 2877 2878
		} else if (srv_adaptive_flushing) {

			/* Try to keep the rate of flushing of dirty
			pages such that redo log generation does not
			produce bursts of IO at checkpoint time. */
			ulint n_flush = buf_flush_get_desired_flush_rate();

			if (n_flush) {
2879 2880
				srv_main_thread_op_info =
					"flushing buffer pool pages";
2881 2882
				n_flush = ut_min(PCT_IO(100), n_flush);
				n_pages_flushed =
irana's avatar
irana committed
2883
					buf_flush_list(
2884 2885 2886
						n_flush,
						IB_ULONGLONG_MAX);
			}
osku's avatar
osku committed
2887 2888
		}

2889
		if (srv_sys->activity_count == old_activity_count) {
osku's avatar
osku committed
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904

			/* There is no user activity at the moment, go to
			the background loop */

			goto background_loop;
		}
	}

	/* ---- We perform the following code approximately once per
	10 seconds when there is database activity */

#ifdef MEM_PERIODIC_CHECK
	/* Check magic numbers of every allocated mem block once in 10
	seconds */
	mem_validate_all_blocks();
2905
#endif
2906 2907 2908 2909 2910 2911 2912 2913
	/* If i/os during the 10 second period were less than 200% of
	capacity, we assume that there is free disk i/o capacity
	available, and it makes sense to flush srv_io_capacity pages.

	Note that this is done regardless of the fraction of dirty
	pages relative to the max requested by the user. The one second
	loop above requests writes for that case. The writes done here
	are not required, and may be disabled. */
osku's avatar
osku committed
2914

irana's avatar
irana committed
2915
	buf_get_total_stat(&buf_stat);
osku's avatar
osku committed
2916
	n_pend_ios = buf_get_n_pending_ios() + log_sys->n_pending_writes;
irana's avatar
irana committed
2917 2918
	n_ios = log_sys->n_log_ios + buf_stat.n_pages_read
		+ buf_stat.n_pages_written;
2919 2920 2921 2922

	srv_main_10_second_loops++;
	if (n_pend_ios < SRV_PEND_IO_THRESHOLD
	    && (n_ios - n_ios_very_old < SRV_PAST_IO_ACTIVITY)) {
osku's avatar
osku committed
2923 2924

		srv_main_thread_op_info = "flushing buffer pool pages";
irana's avatar
irana committed
2925
		buf_flush_list(PCT_IO(100), IB_ULONGLONG_MAX);
osku's avatar
osku committed
2926

2927 2928
		/* Flush logs if needed */
		srv_sync_log_buffer_in_background();
osku's avatar
osku committed
2929 2930 2931 2932 2933 2934
	}

	/* We run a batch of insert buffer merge every 10 seconds,
	even if the server were active */

	srv_main_thread_op_info = "doing insert buffer merge";
2935
	ibuf_contract_for_n_pages(FALSE, PCT_IO(5));
osku's avatar
osku committed
2936

2937 2938
	/* Flush logs if needed */
	srv_sync_log_buffer_in_background();
osku's avatar
osku committed
2939

2940 2941 2942 2943
	if (srv_n_purge_threads == 0) {
		srv_main_thread_op_info = "master purging";

		srv_master_do_purge();
osku's avatar
osku committed
2944 2945 2946 2947 2948

		if (srv_fast_shutdown && srv_shutdown_state > 0) {

			goto background_loop;
		}
2949
	}
2950

osku's avatar
osku committed
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
	srv_main_thread_op_info = "flushing buffer pool pages";

	/* Flush a few oldest pages to make a new checkpoint younger */

	if (buf_get_modified_ratio_pct() > 70) {

		/* If there are lots of modified pages in the buffer pool
		(> 70 %), we assume we can afford reserving the disk(s) for
		the time it requires to flush 100 pages */

irana's avatar
irana committed
2961 2962
		n_pages_flushed = buf_flush_list(
			PCT_IO(100), IB_ULONGLONG_MAX);
osku's avatar
osku committed
2963
	} else {
2964
		/* Otherwise, we only flush a small number of pages so that
osku's avatar
osku committed
2965 2966 2967
		we do not unnecessarily use much disk i/o capacity from
		other work */

irana's avatar
irana committed
2968 2969
		n_pages_flushed = buf_flush_list(
			  PCT_IO(10), IB_ULONGLONG_MAX);
osku's avatar
osku committed
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
	}

	srv_main_thread_op_info = "making checkpoint";

	/* Make a new checkpoint about once in 10 seconds */

	log_checkpoint(TRUE, FALSE);

	srv_main_thread_op_info = "reserving kernel mutex";

	/* ---- When there is database activity, we jump from here back to
	the start of loop */

2983
	if (srv_check_activity(old_activity_count)) {
osku's avatar
osku committed
2984 2985
		goto loop;
	}
2986

osku's avatar
osku committed
2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
	/* If the database is quiet, we enter the background loop */

	/*****************************************************************/
background_loop:
	/* ---- In this loop we run background operations when the server
	is quiet from user activity. Also in the case of a shutdown, we
	loop here, flushing the buffer pool to the data files. */

	/* The server has been quiet for a while: start running background
	operations */
2997
	srv_main_background_loops++;
osku's avatar
osku committed
2998 2999 3000 3001 3002
	srv_main_thread_op_info = "doing background drop tables";

	n_tables_to_drop = row_drop_tables_for_mysql_in_background();

	if (n_tables_to_drop > 0) {
3003
		/* Do not monopolize the CPU even if there are tables waiting
osku's avatar
osku committed
3004 3005 3006 3007 3008 3009
		in the background drop queue. (It is essentially a bug if
		MySQL tries to drop a table while there are still open handles
		to it and we had to put it to the background drop queue.) */

		os_thread_sleep(100000);
	}
3010

3011 3012
	if (srv_n_purge_threads == 0) {
		srv_main_thread_op_info = "master purging";
osku's avatar
osku committed
3013

3014 3015
		srv_master_do_purge();
	}
osku's avatar
osku committed
3016 3017 3018

	srv_main_thread_op_info = "reserving kernel mutex";

3019
	if (srv_check_activity(old_activity_count)) {
osku's avatar
osku committed
3020 3021 3022 3023 3024 3025
		goto loop;
	}

	srv_main_thread_op_info = "doing insert buffer merge";

	if (srv_fast_shutdown && srv_shutdown_state > 0) {
3026
		n_bytes_merged = 0;
osku's avatar
osku committed
3027
	} else {
3028 3029
		/* This should do an amount of IO similar to the number of
		dirty pages that will be flushed in the call to
irana's avatar
irana committed
3030
		buf_flush_list below. Otherwise, the system favors
3031 3032 3033
		clean pages over cleanup throughput. */
		n_bytes_merged = ibuf_contract_for_n_pages(FALSE,
							   PCT_IO(100));
osku's avatar
osku committed
3034 3035 3036 3037
	}

	srv_main_thread_op_info = "reserving kernel mutex";

3038
	if (srv_check_activity(old_activity_count)) {
osku's avatar
osku committed
3039 3040
		goto loop;
	}
3041

osku's avatar
osku committed
3042 3043
flush_loop:
	srv_main_thread_op_info = "flushing buffer pool pages";
3044
	srv_main_flush_loops++;
osku's avatar
osku committed
3045
	if (srv_fast_shutdown < 2) {
irana's avatar
irana committed
3046 3047
		n_pages_flushed = buf_flush_list(
			  PCT_IO(100), IB_ULONGLONG_MAX);
osku's avatar
osku committed
3048 3049 3050 3051 3052 3053 3054 3055 3056
	} else {
		/* In the fastest shutdown we do not flush the buffer pool
		to data files: we set n_pages_flushed to 0 artificially. */

		n_pages_flushed = 0;
	}

	srv_main_thread_op_info = "reserving kernel mutex";

3057
	if (srv_check_activity(old_activity_count)) {
osku's avatar
osku committed
3058 3059
		goto loop;
	}
3060

osku's avatar
osku committed
3061
	srv_main_thread_op_info = "waiting for buffer pool flush to end";
irana's avatar
irana committed
3062
	buf_flush_wait_batch_end(NULL, BUF_FLUSH_LIST);
osku's avatar
osku committed
3063

3064 3065
	/* Flush logs if needed */
	srv_sync_log_buffer_in_background();
osku's avatar
osku committed
3066 3067 3068 3069 3070 3071 3072 3073 3074

	srv_main_thread_op_info = "making checkpoint";

	log_checkpoint(TRUE, FALSE);

	if (buf_get_modified_ratio_pct() > srv_max_buf_pool_modified_pct) {

		/* Try to keep the number of modified pages in the
		buffer pool under the limit wished by the user */
3075

osku's avatar
osku committed
3076 3077 3078 3079 3080
		goto flush_loop;
	}

	srv_main_thread_op_info = "reserving kernel mutex";

3081
	if (srv_check_activity(old_activity_count)) {
osku's avatar
osku committed
3082 3083
		goto loop;
	}
3084

3085
	/*
osku's avatar
osku committed
3086
	srv_main_thread_op_info = "archiving log (if log archive is on)";
3087

osku's avatar
osku committed
3088
	log_archive_do(FALSE, &n_bytes_archived);
3089
	*/
osku's avatar
osku committed
3090 3091 3092 3093 3094 3095
	n_bytes_archived = 0;

	/* Keep looping in the background loop if still work to do */

	if (srv_fast_shutdown && srv_shutdown_state > 0) {
		if (n_tables_to_drop + n_pages_flushed
3096
		    + n_bytes_archived != 0) {
osku's avatar
osku committed
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106

			/* If we are doing a fast shutdown (= the default)
			we do not do purge or insert buffer merge. But we
			flush the buffer pool completely to disk.
			In a 'very fast' shutdown we do not flush the buffer
			pool to data files: we have set n_pages_flushed to
			0 artificially. */

			goto background_loop;
		}
3107 3108 3109
	} else if (n_tables_to_drop
		   + n_pages_purged + n_bytes_merged + n_pages_flushed
		   + n_bytes_archived != 0) {
osku's avatar
osku committed
3110 3111 3112 3113 3114
		/* In a 'slow' shutdown we run purge and the insert buffer
		merge to completion */

		goto background_loop;
	}
3115

osku's avatar
osku committed
3116 3117
	/* There is no work for background operations either: suspend
	master thread to wait for more server activity */
3118

osku's avatar
osku committed
3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131
suspend_thread:
	srv_main_thread_op_info = "suspending";

	mutex_enter(&kernel_mutex);

	if (row_get_background_drop_list_len_low() > 0) {
		mutex_exit(&kernel_mutex);

		goto loop;
	}

	mutex_exit(&kernel_mutex);

3132 3133
	event = srv_suspend_thread();

3134 3135 3136 3137
	/* DO NOT CHANGE THIS STRING. innobase_start_or_create_for_mysql()
	waits for database activity to die down when converting < 4.1.x
	databases, and relies on this string being exactly as it is. InnoDB
	manual also mentions this string in several places. */
osku's avatar
osku committed
3138 3139 3140 3141 3142
	srv_main_thread_op_info = "waiting for server activity";

	os_event_wait(event);

	if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
3143
		/* This is only extra safety, the thread should exit
osku's avatar
osku committed
3144 3145
		already when the event wait ends */

3146
		os_thread_exit(NULL);
3147

osku's avatar
osku committed
3148 3149
	}

3150 3151
	/* When there is user activity, InnoDB will set the event and the
	main thread goes back to loop. */
osku's avatar
osku committed
3152 3153

	goto loop;
3154 3155

	OS_THREAD_DUMMY_RETURN;	/* Not reached, avoid compiler warning */
osku's avatar
osku committed
3156
}
3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173

/*********************************************************************//**
Asynchronous purge thread.
@return	a dummy parameter */
UNIV_INTERN
os_thread_ret_t
srv_purge_thread(
/*=============*/
	void*	arg __attribute__((unused)))	/*!< in: a dummy parameter
						required by os_thread_create */
{
	srv_slot_t*	slot;
	ulint		slot_no = ULINT_UNDEFINED;
	ulint		n_total_purged = ULINT_UNDEFINED;

	ut_a(srv_n_purge_threads == 1);

3174 3175 3176 3177
#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_purge_thread_key);
#endif /* UNIV_PFS_THREAD */

3178 3179 3180 3181 3182
#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "InnoDB: Purge thread running, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
#endif /* UNIV_DEBUG_THREAD_CREATION */

3183
	srv_sys_mutex_enter();
3184 3185 3186

	slot_no = srv_table_reserve_slot(SRV_WORKER);

3187
	++srv_sys->n_threads_active[SRV_WORKER];
3188

3189
	srv_sys_mutex_exit();
3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234

	while (srv_shutdown_state != SRV_SHUTDOWN_EXIT_THREADS) {

		ulint	n_pages_purged;

		/* If there are very few records to purge or the last
		purge didn't purge any records then wait for activity.
	        We peek at the history len without holding any mutex
		because in the worst case we will end up waiting for
		the next purge event. */
		if (trx_sys->rseg_history_len < srv_purge_batch_size
		    || n_total_purged == 0) {

			os_event_t	event;

			event = srv_suspend_thread();

			os_event_wait(event);
		}

		/* Check for shutdown and whether we should do purge at all. */
		if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND
		    || srv_shutdown_state != 0
		    || srv_fast_shutdown) {

			break;
		}

		n_total_purged = 0;

		/* Purge until there are no more records to purge and there is
		no change in configuration or server state. */
		do {
			n_pages_purged = trx_purge(srv_purge_batch_size);

			n_total_purged += n_pages_purged;

		} while (n_pages_purged > 0 && !srv_fast_shutdown);

		srv_sync_log_buffer_in_background();
	}

	/* Free the thread local memory. */
	thr_local_free(os_thread_get_curr_id());

3235
	srv_sys_mutex_enter();
3236 3237 3238 3239 3240

	/* Free the slot for reuse. */
	slot = srv_table_get_nth_slot(slot_no);
	slot->in_use = FALSE;

3241
	srv_sys_mutex_exit();
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253

#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "InnoDB: Purge thread exiting, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
#endif /* UNIV_DEBUG_THREAD_CREATION */

	/* We count the number of threads in os_thread_exit(). A created
	thread should always use that to exit and not use return() to exit. */
	os_thread_exit(NULL);

	OS_THREAD_DUMMY_RETURN;	/* Not reached, avoid compiler warning */
}
3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274

/**********************************************************************//**
Enqueues a task to server task queue and releases a worker thread, if there
is a suspended one. */
UNIV_INTERN
void
srv_que_task_enqueue_low(
/*=====================*/
	que_thr_t*	thr)	/*!< in: query thread */
{
	ut_ad(thr);

	srv_sys_mutex_enter();

	UT_LIST_ADD_LAST(queue, srv_sys->tasks, thr);

	srv_sys_mutex_exit();

	srv_release_threads(SRV_WORKER, 1);
}