srv0srv.cc 103 KB
Newer Older
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1 2
/*****************************************************************************

3
Copyright (c) 1995, 2013, Oracle and/or its affiliates. All Rights Reserved.
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
4
Copyright (c) 2008, 2009 Google Inc.
5
Copyright (c) 2009, Percona Inc.
6
Copyright (c) 2013, 2014, SkySQL Ab.
Vadim Tkachenko's avatar
Vadim Tkachenko committed
7 8 9 10 11 12 13

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.

14 15 16 17 18 19 20
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.

Vadim Tkachenko's avatar
Vadim Tkachenko committed
21 22 23 24 25 26 27 28 29
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
30 31
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
Vadim Tkachenko's avatar
Vadim Tkachenko committed
32 33

*****************************************************************************/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
34 35

/**************************************************//**
36
@file srv/srv0srv.cc
37 38 39 40
The database server main program

Created 10/8/1995 Heikki Tuuri
*******************************************************/
Vadim Tkachenko's avatar
Vadim Tkachenko committed
41

42 43 44 45 46 47 48 49 50 51
/* Dummy comment */
#include "srv0srv.h"

#include "ut0mem.h"
#include "ut0ut.h"
#include "os0proc.h"
#include "mem0mem.h"
#include "mem0pool.h"
#include "sync0sync.h"
#include "que0que.h"
52
#include "log0online.h"
53 54 55 56 57 58 59 60 61 62 63
#include "log0recv.h"
#include "pars0pars.h"
#include "usr0sess.h"
#include "lock0lock.h"
#include "trx0purge.h"
#include "ibuf0ibuf.h"
#include "buf0flu.h"
#include "buf0lru.h"
#include "btr0sea.h"
#include "dict0load.h"
#include "dict0boot.h"
64
#include "dict0stats_bg.h" /* dict_stats_event */
65 66 67 68
#include "srv0start.h"
#include "row0mysql.h"
#include "ha_prototypes.h"
#include "trx0i_s.h"
69
#include "os0sync.h" /* for HAVE_ATOMIC_BUILTINS */
70 71 72 73
#include "srv0mon.h"
#include "ut0crc32.h"
#include "os0file.h"

Sergei Golubchik's avatar
Sergei Golubchik committed
74 75
#include "mysql/plugin.h"
#include "mysql/service_thd_wait.h"
76
#include "fil0pagecompress.h"
77

78 79 80 81 82 83
/* prototypes of new functions added to ha_innodb.cc for kill_idle_transaction */
ibool		innobase_thd_is_idle(const void* thd);
ib_int64_t	innobase_thd_get_start_time(const void* thd);
void		innobase_thd_kill(ulong thd_id);
ulong		innobase_thd_get_thread_id(const void* thd);

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
84 85 86
/* prototypes for new functions added to ha_innodb.cc */
ibool	innobase_get_slow_log();

87 88 89
/* The following is the maximum allowed duration of a lock wait. */
UNIV_INTERN ulint	srv_fatal_semaphore_wait_threshold = 600;

90
/**/
91
UNIV_INTERN long long	srv_kill_idle_transaction = 0;
92

93 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. */
UNIV_INTERN ulint	srv_dml_needed_delay = 0;

97
UNIV_INTERN ibool	srv_monitor_active = FALSE;
98 99
UNIV_INTERN ibool	srv_error_monitor_active = FALSE;

100 101 102 103
UNIV_INTERN ibool	srv_buf_dump_thread_active = FALSE;

UNIV_INTERN ibool	srv_dict_stats_thread_active = FALSE;

104 105
UNIV_INTERN const char*	srv_main_thread_op_info = "";

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
106
/** Prefix used by MySQL to indicate pre-5.1 table name encoding */
107
const char		srv_mysql50_table_name_prefix[10] = "#mysql50#";
108 109 110 111 112 113 114

/* 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 */

UNIV_INTERN char*	srv_data_home	= NULL;
115 116 117 118 119 120 121 122 123 124 125 126 127

/** Rollback files directory, can be absolute. */
UNIV_INTERN char*	srv_undo_dir = NULL;

/** The number of tablespaces to use for rollback segments. */
UNIV_INTERN ulong	srv_undo_tablespaces = 8;

/** The number of UNDO tablespaces that are open and ready to use. */
UNIV_INTERN ulint	srv_undo_tablespaces_open = 8;

/* The number of rollback segments to use */
UNIV_INTERN ulong	srv_undo_logs = 1;

128 129
#ifdef UNIV_LOG_ARCHIVE
UNIV_INTERN char*	srv_arch_dir	= NULL;
130
UNIV_INTERN ulong	srv_log_arch_expire_sec	= 0;
131 132
#endif /* UNIV_LOG_ARCHIVE */

133 134 135 136
/** Set if InnoDB must operate in read-only mode. We don't do any
recovery and open all tables in RO mode instead of RW mode. We don't
sync the max trx id to disk either. */
UNIV_INTERN my_bool	srv_read_only_mode;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
137
/** store to its own file each table created by an user; data
138 139
dictionary tables are in the system tablespace 0 */
UNIV_INTERN my_bool	srv_file_per_table;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
140
/** The file format to use on new *.ibd files. */
141
UNIV_INTERN ulint	srv_file_format = 0;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
142
/** Whether to check file format during startup.  A value of
143
UNIV_FORMAT_MAX + 1 means no checking ie. FALSE.  The default is to
144
set it to the highest format we support. */
145
UNIV_INTERN ulint	srv_max_file_format_at_startup = UNIV_FORMAT_MAX;
146

147 148
#if UNIV_FORMAT_A
# error "UNIV_FORMAT_A must be 0!"
149
#endif
150

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
151
/** Place locks to records only i.e. do not use next-key locking except
152 153
on duplicate key checking and foreign key checking */
UNIV_INTERN ibool	srv_locks_unsafe_for_binlog = FALSE;
154 155 156 157
/** Sort buffer size in index creation */
UNIV_INTERN ulong	srv_sort_buf_size = 1048576;
/** Maximum modification log file size for online index creation */
UNIV_INTERN unsigned long long	srv_online_max_size;
158

Sergei Golubchik's avatar
Sergei Golubchik committed
159 160 161 162 163 164
/* 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;

165 166 167 168 169
/* Default compression level if page compression is used and no compression
level is set for the table*/
UNIV_INTERN long        srv_compress_zlib_level         = 6;
/* If this flag is TRUE, then we will use fallocate(PUCH_HOLE)
to the pages */
170
UNIV_INTERN my_bool     srv_use_trim                    = FALSE;
171 172 173 174 175
/* If this flag is TRUE, then we will use posix fallocate for file extentsion */
UNIV_INTERN my_bool     srv_use_posix_fallocate         = FALSE;
/* If this flag is TRUE, then we disable doublewrite buffer */
UNIV_INTERN my_bool     srv_use_atomic_writes           = FALSE;
/* If this flag IS TRUE, then we use lz4 to compress/decompress pages */
176
UNIV_INTERN ulong	innodb_compression_algorithm = PAGE_ZLIB_ALGORITHM;
177
/* Number of threads used for multi-threaded flush */
178
UNIV_INTERN long srv_mtflush_threads = MTFLUSH_DEFAULT_WORKER;
179
/* If this flag is TRUE, then we will use multi threaded flush. */
180
UNIV_INTERN my_bool	srv_use_mtflush                 = FALSE;
181

Sergei Golubchik's avatar
Sergei Golubchik committed
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
#ifdef __WIN__
/* Windows native condition variables. We use runtime loading / function
pointers, because they are not available on Windows Server 2003 and
Windows XP/2000.

We use condition for events on Windows if possible, even if os_event
resembles Windows kernel event object well API-wise. The reason is
performance, kernel objects are heavyweights and WaitForSingleObject() is a
performance killer causing calling thread to context switch. Besides, Innodb
is preallocating large number (often millions) of os_events. With kernel event
objects it takes a big chunk out of non-paged pool, which is better suited
for tasks like IO than for storing idle event objects. */
UNIV_INTERN ibool	srv_use_native_conditions = FALSE;
#endif /* __WIN__ */

197 198 199 200 201
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;

202
UNIV_INTERN my_bool	srv_track_changed_pages = FALSE;
203

204
UNIV_INTERN ulonglong	srv_max_bitmap_file_size = 100 * 1024 * 1024;
205

206
UNIV_INTERN ulonglong	srv_max_changed_pages = 0;
207

208 209 210 211
/** When TRUE, fake change transcations take S rather than X row locks.
    When FALSE, row locks are not taken at all. */
UNIV_INTERN my_bool	srv_fake_changes_locks = TRUE;

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
/* 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;

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

UNIV_INTERN ibool	srv_created_new_raw	= FALSE;

227
UNIV_INTERN char*	srv_log_group_home_dir	= NULL;
228

229
UNIV_INTERN ulong	srv_n_log_files		= SRV_N_LOG_FILES_MAX;
230
/* size in database pages */
231 232
UNIV_INTERN ib_uint64_t	srv_log_file_size	= IB_UINT64_MAX;
UNIV_INTERN ib_uint64_t	srv_log_file_size_requested;
233 234
/* size in database pages */
UNIV_INTERN ulint	srv_log_buffer_size	= ULINT_MAX;
235 236 237
UNIV_INTERN uint	srv_flush_log_at_timeout = 1;
UNIV_INTERN ulong	srv_page_size		= UNIV_PAGE_SIZE_DEF;
UNIV_INTERN ulong	srv_page_size_shift	= UNIV_PAGE_SIZE_SHIFT_DEF;
Sergei Golubchik's avatar
Sergei Golubchik committed
238
UNIV_INTERN char	srv_use_global_flush_log_at_trx_commit	= TRUE;
239

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
240 241 242 243
/* Try to flush dirty pages so as to avoid IO bursts at
the checkpoints. */
UNIV_INTERN char	srv_adaptive_flushing	= TRUE;

244 245
UNIV_INTERN ulong	srv_show_locks_held	= 10;
UNIV_INTERN ulong	srv_show_verbose_locks	= 0;
246

247 248 249
/** Maximum number of times allowed to conditionally acquire
mutex before switching to blocking wait on the mutex */
#define MAX_MUTEX_NOWAIT	20
250

251 252 253 254 255 256 257
/** 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
258 259 260
collation */
UNIV_INTERN const byte*	srv_latin1_ordering;

Vadim Tkachenko's avatar
Vadim Tkachenko committed
261 262
/* use os/external memory allocator */
UNIV_INTERN my_bool	srv_use_sys_malloc	= TRUE;
263
/* requested size in kilobytes */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
264
UNIV_INTERN ulint	srv_buf_pool_size	= ULINT_MAX;
265 266
/* force virtual page preallocation (prefault) */
UNIV_INTERN my_bool	srv_buf_pool_populate	= FALSE;
Sergei Golubchik's avatar
Sergei Golubchik committed
267 268
/* requested number of buffer pool instances */
UNIV_INTERN ulint       srv_buf_pool_instances  = 1;
269 270 271 272 273 274
/* number of locks to protect buf_pool->page_hash */
UNIV_INTERN ulong	srv_n_page_hash_locks = 16;
/** Scan depth for LRU flush batch i.e.: number of blocks scanned*/
UNIV_INTERN ulong	srv_LRU_scan_depth	= 1024;
/** whether or not to flush neighbors of a block */
UNIV_INTERN ulong	srv_flush_neighbors	= 1;
275
/* previously requested size */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
276
UNIV_INTERN ulint	srv_buf_pool_old_size;
277
/* current size in kilobytes */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
278
UNIV_INTERN ulint	srv_buf_pool_curr_size	= 0;
279 280 281 282
/* size in bytes */
UNIV_INTERN ulint	srv_mem_pool_size	= ULINT_MAX;
UNIV_INTERN ulint	srv_lock_table_size	= ULINT_MAX;

283
/** Query thread preflush algorithm */
284
UNIV_INTERN ulong	srv_foreground_preflush
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
	= SRV_FOREGROUND_PREFLUSH_EXP_BACKOFF;

/** The maximum time limit for a single LRU tail flush iteration by the page
cleaner thread */
UNIV_INTERN ulint	srv_cleaner_max_lru_time = 1000;

/** The maximum time limit for a single flush list flush iteration by the page
cleaner thread */
UNIV_INTERN ulint	srv_cleaner_max_flush_time = 1000;

/** Page cleaner flush list flush batches are further divided into this chunk
size  */
UNIV_INTERN ulint	srv_cleaner_flush_chunk_size = 100;

/** Page cleaner LRU list flush batches are further divided into this chunk
size  */
UNIV_INTERN ulint	srv_cleaner_lru_chunk_size = 100;

/** If free list length is lower than this percentage of srv_LRU_scan_depth,
page cleaner LRU flushes will issue flush batches to the same instance in a
row  */
UNIV_INTERN ulint	srv_cleaner_free_list_lwm = 10;

/** If TRUE, page cleaner heuristics use evicted instead of flushed page counts
for its heuristics  */
UNIV_INTERN my_bool	srv_cleaner_eviction_factor = FALSE;

/** Page cleaner LSN age factor formula option */
UNIV_INTERN ulong	srv_cleaner_lsn_age_factor
	= SRV_CLEANER_LSN_AGE_FACTOR_HIGH_CHECKPOINT;

/** Empty free list for a query thread handling algorithm option  */
UNIV_INTERN ulong	srv_empty_free_list_algorithm
	= SRV_EMPTY_FREE_LIST_BACKOFF;

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
320 321
/* This parameter is deprecated. Use srv_n_io_[read|write]_threads
instead. */
322
UNIV_INTERN ulint	srv_n_file_io_threads	= ULINT_MAX;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
323 324 325
UNIV_INTERN ulint	srv_n_read_io_threads	= ULINT_MAX;
UNIV_INTERN ulint	srv_n_write_io_threads	= ULINT_MAX;

326 327 328
/* Switch to enable random read ahead. */
UNIV_INTERN my_bool	srv_random_read_ahead	= FALSE;

329 330 331
/* The log block size */
UNIV_INTERN ulint	srv_log_block_size	= 0;

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
332 333 334 335
/* 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;
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

#ifdef UNIV_LOG_ARCHIVE
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;
#endif /* UNIV_LOG_ARCHIVE */

/* 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. */

UNIV_INTERN ulong	srv_insert_buffer_batch_size = 20;

UNIV_INTERN char*	srv_file_flush_method_str = NULL;
UNIV_INTERN ulint	srv_unix_file_flush_method = SRV_UNIX_FSYNC;
UNIV_INTERN ulint	srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;

UNIV_INTERN ulint	srv_max_n_open_files	  = 300;

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
359 360
/* Number of IO operations per second the server can do */
UNIV_INTERN ulong	srv_io_capacity         = 200;
361
UNIV_INTERN ulong	srv_max_io_capacity     = 400;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
362

363 364 365 366 367
/* 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. */

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
368
UNIV_INTERN ulong	srv_max_buf_pool_modified_pct	= 75;
369
UNIV_INTERN ulong	srv_max_dirty_pages_pct_lwm	= 50;
370

371 372 373
/* This is the percentage of log capacity at which adaptive flushing,
if enabled, will kick in. */
UNIV_INTERN ulong	srv_adaptive_flushing_lwm	= 10;
Sergei Golubchik's avatar
Sergei Golubchik committed
374

375 376 377 378 379 380
/* Number of iterations over which adaptive flushing is averaged. */
UNIV_INTERN ulong	srv_flushing_avg_loops		= 30;

/* The tid of the cleaner thread */
UNIV_INTERN os_tid_t	srv_cleaner_tid;

381 382 383
/* The tid of the LRU manager thread */
UNIV_INTERN os_tid_t	srv_lru_manager_tid;

384 385 386 387 388 389 390 391 392
/* The tids of the purge threads */
UNIV_INTERN os_tid_t	srv_purge_tids[SRV_MAX_N_PURGE_THREADS];

/* The tids of the I/O threads */
UNIV_INTERN os_tid_t	srv_io_tids[SRV_MAX_N_IO_THREADS];

/* The tid of the master thread */
UNIV_INTERN os_tid_t	srv_master_tid;

393
/* The relative scheduling priority of the cleaner and LRU manager threads */
394
UNIV_INTERN ulint	srv_sched_priority_cleaner	= 19;
Sergei Golubchik's avatar
Sergei Golubchik committed
395

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
/* The relative scheduling priority of the purge threads */
UNIV_INTERN ulint	srv_sched_priority_purge	= 19;

/* The relative scheduling priority of the I/O threads */
UNIV_INTERN ulint	srv_sched_priority_io		= 19;

/* The relative scheduling priority of the master thread */
UNIV_INTERN ulint	srv_sched_priority_master	= 19;

/* The relative priority of the current thread.  If 0, low priority; if 1, high
priority.  */
UNIV_INTERN UNIV_THREAD_LOCAL ulint srv_current_thread_priority = 0;

/* The relative priority of the purge coordinator and worker threads.  */
UNIV_INTERN my_bool	srv_purge_thread_priority	= FALSE;

/* The relative priority of the I/O threads.  */
UNIV_INTERN my_bool	srv_io_thread_priority		= FALSE;

/* The relative priority of the cleaner thread.  */
UNIV_INTERN my_bool	srv_cleaner_thread_priority	= FALSE;

/* The relative priority of the master thread.  */
UNIV_INTERN my_bool	srv_master_thread_priority	= FALSE;

/* The number of purge threads to use.*/
UNIV_INTERN ulong	srv_n_purge_threads = 1;

/* the number of pages to purge in one batch */
UNIV_INTERN ulong	srv_purge_batch_size = 20;
Sergei Golubchik's avatar
Sergei Golubchik committed
426

427 428 429
/* Internal setting for "innodb_stats_method". Decides how InnoDB treats
NULL value when collecting statistics. By default, it is set to
SRV_STATS_NULLS_EQUAL(0), ie. all NULL value are treated equal */
430
UNIV_INTERN ulong srv_innodb_stats_method = SRV_STATS_NULLS_EQUAL;
431

432
UNIV_INTERN srv_stats_t	srv_stats;
433

434
/* structure to pass status variables to MySQL */
435
UNIV_INTERN export_var_t export_vars;
436

437 438 439 440 441 442 443 444 445 446 447 448 449 450
/** Normally 0. When nonzero, skip some phases of crash recovery,
starting from SRV_FORCE_IGNORE_CORRUPT, so that data can be recovered
by SELECT or mysqldump. When this is nonzero, we do not allow any user
modifications to the data. */
UNIV_INTERN ulong	srv_force_recovery;
#ifndef DBUG_OFF
/** Inject a crash at different steps of the recovery process.
This is for testing and debugging only. */
UNIV_INTERN ulong	srv_force_recovery_crash;
#endif /* !DBUG_OFF */

/** Print all user-level transactions deadlocks to mysqld stderr */

UNIV_INTERN my_bool	srv_print_all_deadlocks = FALSE;
451

452 453 454
/* Produce a stacktrace on long semaphore wait */
UNIV_INTERN my_bool     srv_use_stacktrace = FALSE;

455 456
/** Enable INFORMATION_SCHEMA.innodb_cmp_per_index */
UNIV_INTERN my_bool	srv_cmp_per_index_enabled = FALSE;
457 458 459 460 461 462 463 464 465 466

/* 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). */
UNIV_INTERN ulint	srv_fast_shutdown	= 0;

/* Generate a innodb_status.<pid> file */
UNIV_INTERN ibool	srv_innodb_status	= FALSE;

Vadim Tkachenko's avatar
Vadim Tkachenko committed
467
/* When estimating number of different key values in an index, sample
468 469 470 471 472 473 474 475 476
this many index pages, there are 2 ways to calculate statistics:
* persistent stats that are calculated by ANALYZE TABLE and saved
  in the innodb database.
* quick transient stats, that are used if persistent stats for the given
  table/index are not found in the innodb database */
UNIV_INTERN unsigned long long	srv_stats_transient_sample_pages = 8;
UNIV_INTERN my_bool		srv_stats_persistent = TRUE;
UNIV_INTERN unsigned long long	srv_stats_persistent_sample_pages = 20;
UNIV_INTERN my_bool		srv_stats_auto_recalc = TRUE;
477 478

UNIV_INTERN ibool	srv_use_doublewrite_buf	= TRUE;
479

480 481 482 483 484
/** doublewrite buffer is 1MB is size i.e.: it can hold 128 16K pages.
The following parameter is the size of the buffer that is used for
batch flushing i.e.: LRU flushing and flush_list flushing. The rest
of the pages are used for single page flushing. */
UNIV_INTERN ulong	srv_doublewrite_batch_size	= 120;
485

Vadim Tkachenko's avatar
Vadim Tkachenko committed
486
UNIV_INTERN ulong	srv_replication_delay		= 0;
487

488
UNIV_INTERN ulong	srv_pass_corrupt_table = 0; /* 0:disable 1:enable */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
489

490
UNIV_INTERN ulong	srv_log_checksum_algorithm =
491 492
	SRV_CHECKSUM_ALGORITHM_INNODB;

493
/*-------------------------------------------*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
494 495
UNIV_INTERN ulong	srv_n_spin_wait_rounds	= 30;
UNIV_INTERN ulong	srv_spin_wait_delay	= 6;
496 497 498 499 500 501 502 503 504 505
UNIV_INTERN ibool	srv_priority_boost	= TRUE;

#ifdef UNIV_DEBUG
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;
#endif /* UNIV_DEBUG */

506 507 508 509
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;
Sergei Golubchik's avatar
Sergei Golubchik committed
510

511 512 513
UNIV_INTERN ulint	srv_truncated_status_writes	= 0;
UNIV_INTERN ulint	srv_available_undo_logs         = 0;

514 515 516 517
UNIV_INTERN ib_uint64_t srv_page_compression_saved      = 0;
UNIV_INTERN ib_uint64_t srv_page_compression_trim_sect512       = 0;
UNIV_INTERN ib_uint64_t srv_page_compression_trim_sect4096      = 0;
UNIV_INTERN ib_uint64_t srv_index_pages_written         = 0;
518
UNIV_INTERN ib_uint64_t srv_non_index_pages_written     = 0;
519 520 521 522 523
UNIV_INTERN ib_uint64_t srv_pages_page_compressed       = 0;
UNIV_INTERN ib_uint64_t srv_page_compressed_trim_op     = 0;
UNIV_INTERN ib_uint64_t srv_page_compressed_trim_op_saved     = 0;
UNIV_INTERN ib_uint64_t srv_index_page_decompressed     = 0;

524
/* Ensure status variables are on separate cache lines */
525 526 527 528 529 530 531

#define CACHE_LINE_SIZE 64
#define CACHE_ALIGNED __attribute__ ((aligned (CACHE_LINE_SIZE)))

UNIV_INTERN byte
counters_pad_start[CACHE_LINE_SIZE] __attribute__((unused)) = {0};

532 533 534
UNIV_INTERN ulint		srv_read_views_memory CACHE_ALIGNED	= 0;
UNIV_INTERN ulint		srv_descriptors_memory CACHE_ALIGNED	= 0;

535 536
UNIV_INTERN byte
counters_pad_end[CACHE_LINE_SIZE] __attribute__((unused)) = {0};
537

538 539
/* Set the following to 0 if you want InnoDB to write messages on
stderr on startup/shutdown. */
540
UNIV_INTERN ibool	srv_print_verbose_log		= TRUE;
541 542
UNIV_INTERN my_bool	srv_print_innodb_monitor	= FALSE;
UNIV_INTERN my_bool	srv_print_innodb_lock_monitor	= FALSE;
543 544 545
UNIV_INTERN ibool	srv_print_innodb_tablespace_monitor = FALSE;
UNIV_INTERN ibool	srv_print_innodb_table_monitor = FALSE;

546 547 548
/** If this flag is set tables without primary key are not allowed */
UNIV_INTERN my_bool	srv_force_primary_key		= FALSE;

549 550 551 552 553 554 555 556
/* Array of English strings describing the current state of an
i/o handler thread */

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];

UNIV_INTERN time_t	srv_last_monitor_time;

557
UNIV_INTERN ib_mutex_t	srv_innodb_monitor_mutex;
558

559 560
/* Mutex for locking srv_monitor_file. Not created if srv_read_only_mode */
UNIV_INTERN ib_mutex_t	srv_monitor_file_mutex;
Sergei Golubchik's avatar
Sergei Golubchik committed
561 562

#ifdef UNIV_PFS_MUTEX
563 564 565 566 567
# ifndef HAVE_ATOMIC_BUILTINS
/* Key to register server_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	server_mutex_key;
# endif /* !HAVE_ATOMIC_BUILTINS */
/** Key to register srv_innodb_monitor_mutex with performance schema */
Sergei Golubchik's avatar
Sergei Golubchik committed
568
UNIV_INTERN mysql_pfs_key_t	srv_innodb_monitor_mutex_key;
569
/** Key to register srv_monitor_file_mutex with performance schema */
Sergei Golubchik's avatar
Sergei Golubchik committed
570
UNIV_INTERN mysql_pfs_key_t	srv_monitor_file_mutex_key;
571
/** Key to register srv_dict_tmpfile_mutex with performance schema */
Sergei Golubchik's avatar
Sergei Golubchik committed
572
UNIV_INTERN mysql_pfs_key_t	srv_dict_tmpfile_mutex_key;
573
/** Key to register the mutex with performance schema */
Sergei Golubchik's avatar
Sergei Golubchik committed
574
UNIV_INTERN mysql_pfs_key_t	srv_misc_tmpfile_mutex_key;
575 576 577 578
/** Key to register srv_sys_t::mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_sys_mutex_key;
/** Key to register srv_sys_t::tasks_mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t	srv_sys_tasks_mutex_key;
Sergei Golubchik's avatar
Sergei Golubchik committed
579 580
#endif /* UNIV_PFS_MUTEX */

581
/** Temporary file for innodb monitor output */
582
UNIV_INTERN FILE*	srv_monitor_file;
583
/** Mutex for locking srv_dict_tmpfile. Not created if srv_read_only_mode.
584 585
This mutex has a very high rank; threads reserving it should not
be holding any InnoDB latches. */
586 587
UNIV_INTERN ib_mutex_t	srv_dict_tmpfile_mutex;
/** Temporary file for output from the data dictionary */
588
UNIV_INTERN FILE*	srv_dict_tmpfile;
589
/** Mutex for locking srv_misc_tmpfile. Not created if srv_read_only_mode.
590 591
This mutex has a very low rank; threads reserving it should not
acquire any further latches or sleep before releasing this one. */
592 593
UNIV_INTERN ib_mutex_t	srv_misc_tmpfile_mutex;
/** Temporary file for miscellanous diagnostic output */
594 595 596 597 598
UNIV_INTERN FILE*	srv_misc_tmpfile;

UNIV_INTERN ulint	srv_main_thread_process_no	= 0;
UNIV_INTERN ulint	srv_main_thread_id		= 0;

599 600 601 602 603 604 605 606 607 608
/* The following counts are used by the srv_master_thread. */

/** Iterations of the loop bounded by 'srv_active' label. */
static ulint		srv_main_active_loops		= 0;
/** Iterations of the loop bounded by the 'srv_idle' label. */
static ulint		srv_main_idle_loops		= 0;
/** Iterations of the loop bounded by the 'srv_shutdown' label. */
static ulint		srv_main_shutdown_loops		= 0;
/** Log writes involving flush. */
static ulint		srv_log_writes_and_flush	= 0;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
609 610 611 612 613 614 615

/* 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;

616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
/* Interval in seconds at which various tasks are performed by the
master thread when server is active. In order to balance the workload,
we should try to keep intervals such that they are not multiple of
each other. For example, if we have intervals for various tasks
defined as 5, 10, 15, 60 then all tasks will be performed when
current_time % 60 == 0 and no tasks will be performed when
current_time % 5 != 0. */

# define	SRV_MASTER_CHECKPOINT_INTERVAL		(7)
# define	SRV_MASTER_PURGE_INTERVAL		(10)
#ifdef MEM_PERIODIC_CHECK
# define	SRV_MASTER_MEM_VALIDATE_INTERVAL	(13)
#endif /* MEM_PERIODIC_CHECK */
# define	SRV_MASTER_DICT_LRU_INTERVAL		(47)

/** Acquire the system_mutex. */
#define srv_sys_mutex_enter() do {			\
	mutex_enter(&srv_sys->mutex);			\
} while (0)

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

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

#define fetch_lock_wait_timeout(trx)			\
	((trx)->lock.allowed_to_wait			\
	 ? thd_lock_wait_timeout((trx)->mysql_thd)	\
	 : 0)
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
649

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
/*
	IMPLEMENTATION OF THE SERVER MAIN PROGRAM
	=========================================

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

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

query thread		--	thread;

lock			--	semaphore;

kernel			--	kernel;

query thread execution:
668
(a) without lock mutex
669
reserved		--	process executing in user mode;
670
(b) with lock mutex reserved
671 672
			--	process executing in kernel mode;

673 674 675 676 677 678 679 680 681 682 683
The server has several backgroind threads all running at the same
priority as user threads. It periodically checks if here is anything
happening in the server which requires intervention of the master
thread. Such situations may be, for example, when flushing of dirty
blocks is needed in the buffer pool or old version of database rows
have to be cleaned away (purged). The user can configure a separate
dedicated purge thread(s) too, in which case the master thread does not
do any purging.

The threads which we call user threads serve the queries of the MySQL
server. They run at normal priority.
684 685

When there is no activity in the system, also the master thread
686
suspends itself to wait for an event making the server totally silent.
687 688 689 690 691 692 693 694 695

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.

696 697 698 699 700 701 702 703 704 705 706 707 708 709
One solution to the priority inversion problem would be to keep record
of which thread owns which resource and in the above case boost the
priority of the background thread so that it will be scheduled and it
can release the resource.  This solution is called priority inheritance
in real-time programming.  A drawback of this solution is that the overhead
of acquiring a mutex increases slightly, maybe 0.2 microseconds on a 100
MHz Pentium, because the thread has to call os_thread_get_curr_id.  This may
be compared to 0.5 microsecond overhead for a mutex lock-unlock pair. Note
that the thread cannot store the information in the resource , say mutex,
itself, because competing threads could wipe out the information if it is
stored before acquiring the mutex, and if it stored afterwards, the
information is outdated for the time of one machine instruction, at least.
(To be precise, the information could be stored to lock_word in mutex if
the machine supports atomic swap.)
710 711

The above solution with priority inheritance may become actual in the
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
future, currently we do not implement any priority twiddling solution.
Our general aim is to reduce the contention of all mutexes by making
them more fine grained.

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

/** The server system struct */
struct srv_sys_t{
	ib_mutex_t	tasks_mutex;		/*!< variable protecting the
						tasks queue */
	UT_LIST_BASE_NODE_T(que_thr_t)
			tasks;			/*!< task queue */

	ib_mutex_t	mutex;			/*!< variable protecting the
						fields below. */
	ulint		n_sys_threads;		/*!< size of the sys_threads
						array */

	srv_slot_t*	sys_threads;		/*!< server thread table */

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

	srv_stats_t::ulint_ctr_1_t
			activity_count;		/*!< For tracking server
						activity */
743 744
};

745 746 747 748
#ifndef HAVE_ATOMIC_BUILTINS
/** Mutex protecting some server global variables. */
UNIV_INTERN ib_mutex_t	server_mutex;
#endif /* !HAVE_ATOMIC_BUILTINS */
749

750
static srv_sys_t*	srv_sys	= NULL;
751

752
/** Event to signal the monitor thread. */
Sergei Golubchik's avatar
Sergei Golubchik committed
753 754
UNIV_INTERN os_event_t	srv_monitor_event;

755
/** Event to signal the error thread */
Sergei Golubchik's avatar
Sergei Golubchik committed
756 757
UNIV_INTERN os_event_t	srv_error_event;

758 759
/** Event to signal the buffer pool dump/load thread */
UNIV_INTERN os_event_t	srv_buf_dump_event;
760

761 762
/** The buffer pool dump/load file name */
UNIV_INTERN char*	srv_buf_dump_filename;
763

764 765 766 767
/** Boolean config knobs that tell InnoDB to dump the buffer pool at shutdown
and/or load it during startup. */
UNIV_INTERN char	srv_buffer_pool_dump_at_shutdown = FALSE;
UNIV_INTERN char	srv_buffer_pool_load_at_startup = FALSE;
768

769 770
/** Slot index in the srv_sys->sys_threads array for the purge thread. */
static const ulint	SRV_PURGE_SLOT	= 1;
771

772 773
/** Slot index in the srv_sys->sys_threads array for the master thread. */
static const ulint	SRV_MASTER_SLOT = 0;
774

775
UNIV_INTERN os_event_t	srv_checkpoint_completed_event;
776

777
UNIV_INTERN os_event_t	srv_redo_log_thread_finished_event;
Sergei Golubchik's avatar
Sergei Golubchik committed
778

779
/*********************************************************************//**
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
780
Prints counters for work done by srv_master_thread. */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
781 782
static
void
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
783 784 785
srv_print_master_thread_info(
/*=========================*/
	FILE  *file)    /* in: output stream */
Vadim Tkachenko's avatar
Vadim Tkachenko committed
786
{
787 788 789 790 791
	fprintf(file, "srv_master_thread loops: %lu srv_active, "
		"%lu srv_shutdown, %lu srv_idle\n",
		srv_main_active_loops,
		srv_main_shutdown_loops,
		srv_main_idle_loops);
792
	fprintf(file, "srv_master_thread log flush and writes: %lu\n",
793
		srv_log_writes_and_flush);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
794 795
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
796
/*********************************************************************//**
797 798 799 800 801
Sets the info describing an i/o thread current state. */
UNIV_INTERN
void
srv_set_io_thread_op_info(
/*======================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
802 803
	ulint		i,	/*!< in: the 'segment' of the i/o thread */
	const char*	str)	/*!< in: constant char string describing the
804 805 806 807 808 809 810
				state */
{
	ut_a(i < SRV_MAX_N_IO_THREADS);

	srv_io_thread_op_info[i] = str;
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
811
/*********************************************************************//**
812
Resets the info describing an i/o thread current state. */
813
UNIV_INTERN
814 815 816
void
srv_reset_io_thread_op_info()
/*=========================*/
817
{
818 819
	for (ulint i = 0; i < UT_ARR_SIZE(srv_io_thread_op_info); ++i) {
		srv_io_thread_op_info[i] = "not started yet";
820 821 822
	}
}

Sergei Golubchik's avatar
Sergei Golubchik committed
823 824 825 826 827 828 829 830
#ifdef UNIV_DEBUG
/*********************************************************************//**
Validates the type of a thread table slot.
@return TRUE if ok */
static
ibool
srv_thread_type_validate(
/*=====================*/
831
	srv_thread_type	type)	/*!< in: thread type */
Sergei Golubchik's avatar
Sergei Golubchik committed
832 833
{
	switch (type) {
834 835
	case SRV_NONE:
		break;
Sergei Golubchik's avatar
Sergei Golubchik committed
836
	case SRV_WORKER:
837
	case SRV_PURGE:
Sergei Golubchik's avatar
Sergei Golubchik committed
838 839 840 841 842 843 844 845
	case SRV_MASTER:
		return(TRUE);
	}
	ut_error;
	return(FALSE);
}
#endif /* UNIV_DEBUG */

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
846
/*********************************************************************//**
Sergei Golubchik's avatar
Sergei Golubchik committed
847 848
Gets the type of a thread table slot.
@return thread type */
849
static
850
srv_thread_type
Sergei Golubchik's avatar
Sergei Golubchik committed
851 852 853 854
srv_slot_get_type(
/*==============*/
	const srv_slot_t*	slot)	/*!< in: thread slot */
{
855
	srv_thread_type	type = slot->type;
Sergei Golubchik's avatar
Sergei Golubchik committed
856 857 858 859 860 861 862 863 864
	ut_ad(srv_thread_type_validate(type));
	return(type);
}

/*********************************************************************//**
Reserves a slot in the thread table for the current thread.
@return	reserved slot */
static
srv_slot_t*
865 866 867
srv_reserve_slot(
/*=============*/
	srv_thread_type	type)	/*!< in: type of the thread */
868
{
869 870 871
	srv_slot_t*	slot = 0;

	srv_sys_mutex_enter();
872

Sergei Golubchik's avatar
Sergei Golubchik committed
873
	ut_ad(srv_thread_type_validate(type));
874

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
	switch (type) {
	case SRV_MASTER:
		slot = &srv_sys->sys_threads[SRV_MASTER_SLOT];
		break;

	case SRV_PURGE:
		slot = &srv_sys->sys_threads[SRV_PURGE_SLOT];
		break;

	case SRV_WORKER:
		/* Find an empty slot, skip the master and purge slots. */
		for (slot = &srv_sys->sys_threads[2];
		     slot->in_use;
		     ++slot) {

			ut_a(slot < &srv_sys->sys_threads[
			     srv_sys->n_sys_threads]);
		}
		break;
894

895 896
	case SRV_NONE:
		ut_error;
897 898
	}

899 900
	ut_a(!slot->in_use);

901 902 903
	slot->in_use = TRUE;
	slot->suspended = FALSE;
	slot->type = type;
904

Sergei Golubchik's avatar
Sergei Golubchik committed
905
	ut_ad(srv_slot_get_type(slot) == type);
906

907 908 909 910
	++srv_sys->n_threads_active[type];

	srv_sys_mutex_exit();

Sergei Golubchik's avatar
Sergei Golubchik committed
911
	return(slot);
912 913
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
914
/*********************************************************************//**
915
Suspends the calling thread to wait for the event in its thread slot.
916
@return the current signal count of the event. */
917
static
918 919 920
ib_int64_t
srv_suspend_thread_low(
/*===================*/
Sergei Golubchik's avatar
Sergei Golubchik committed
921
	srv_slot_t*	slot)	/*!< in/out: thread slot */
922 923
{

924 925 926
	ut_ad(!srv_read_only_mode);
	ut_ad(srv_sys_mutex_own());

Sergei Golubchik's avatar
Sergei Golubchik committed
927
	ut_ad(slot->in_use);
928

929 930 931 932 933 934 935 936 937 938 939
	srv_thread_type	type = srv_slot_get_type(slot);

	switch (type) {
	case SRV_NONE:
		ut_error;

	case SRV_MASTER:
		/* We have only one master thread and it
		should be the first entry always. */
		ut_a(srv_sys->n_threads_active[type] == 1);
		break;
940

941 942 943 944 945 946 947 948 949 950 951
	case SRV_PURGE:
		/* We have only one purge coordinator thread
		and it should be the second entry always. */
		ut_a(srv_sys->n_threads_active[type] == 1);
		break;

	case SRV_WORKER:
		ut_a(srv_n_purge_threads > 1);
		ut_a(srv_sys->n_threads_active[type] > 0);
		break;
	}
952

953
	ut_a(!slot->suspended);
954 955
	slot->suspended = TRUE;

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
	ut_a(srv_sys->n_threads_active[type] > 0);

	srv_sys->n_threads_active[type]--;

	return(os_event_reset(slot->event));
}

/*********************************************************************//**
Suspends the calling thread to wait for the event in its thread slot.
@return the current signal count of the event. */
static
ib_int64_t
srv_suspend_thread(
/*===============*/
	srv_slot_t*	slot)	/*!< in/out: thread slot */
{
	srv_sys_mutex_enter();

	ib_int64_t	sig_count = srv_suspend_thread_low(slot);
975

976
	srv_sys_mutex_exit();
977

978
	return(sig_count);
979 980
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
981
/*********************************************************************//**
982
Releases threads of the type given from suspension in the thread table.
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
983 984
NOTE! The server mutex has to be reserved by the caller!
@return number of threads released: this may be less than n if not
985
        enough threads were suspended at the moment. */
986 987 988 989
UNIV_INTERN
ulint
srv_release_threads(
/*================*/
990 991
	srv_thread_type	type,	/*!< in: thread type */
	ulint		n)	/*!< in: number of threads to release */
992 993 994 995
{
	ulint		i;
	ulint		count	= 0;

Sergei Golubchik's avatar
Sergei Golubchik committed
996
	ut_ad(srv_thread_type_validate(type));
997 998
	ut_ad(n > 0);

999
	srv_sys_mutex_enter();
1000

1001 1002
	for (i = 0; i < srv_sys->n_sys_threads; i++) {
		srv_slot_t*	slot;
1003

1004
		slot = &srv_sys->sys_threads[i];
1005

1006 1007 1008
		if (slot->in_use
		    && srv_slot_get_type(slot) == type
		    && slot->suspended) {
1009

1010 1011 1012
			switch (type) {
			case SRV_NONE:
				ut_error;
1013

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
			case SRV_MASTER:
				/* We have only one master thread and it
				should be the first entry always. */
				ut_a(n == 1);
				ut_a(i == SRV_MASTER_SLOT);
				ut_a(srv_sys->n_threads_active[type] == 0);
				break;

			case SRV_PURGE:
				/* We have only one purge coordinator thread
				and it should be the second entry always. */
				ut_a(n == 1);
				ut_a(i == SRV_PURGE_SLOT);
				ut_a(srv_n_purge_threads > 0);
				ut_a(srv_sys->n_threads_active[type] == 0);
				break;
1030

1031 1032 1033 1034 1035
			case SRV_WORKER:
				ut_a(srv_n_purge_threads > 1);
				ut_a(srv_sys->n_threads_active[type]
				     < srv_n_purge_threads - 1);
				break;
1036 1037
			}

1038 1039 1040 1041 1042
			slot->suspended = FALSE;

			++srv_sys->n_threads_active[type];

			os_event_set(slot->event);
1043

1044
			if (++count == n) {
1045 1046 1047 1048 1049
				break;
			}
		}
	}

1050 1051
	srv_sys_mutex_exit();

1052 1053 1054
	return(count);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1055
/*********************************************************************//**
1056 1057 1058 1059 1060 1061
Release a thread's slot. */
static
void
srv_free_slot(
/*==========*/
	srv_slot_t*	slot)	/*!< in/out: thread slot */
1062
{
1063
	srv_sys_mutex_enter();
1064

1065 1066 1067
	if (!slot->suspended) {
		/* Mark the thread as inactive. */
		srv_suspend_thread_low(slot);
Sergei Golubchik's avatar
Sergei Golubchik committed
1068
	}
1069

1070 1071 1072
	/* Free the slot for reuse. */
	ut_ad(slot->in_use);
	slot->in_use = FALSE;
1073

1074
	srv_sys_mutex_exit();
1075 1076
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1077
/*********************************************************************//**
1078 1079 1080 1081 1082 1083
Initializes the server. */
UNIV_INTERN
void
srv_init(void)
/*==========*/
{
1084 1085
	ulint	n_sys_threads = 0;
	ulint	srv_sys_sz = sizeof(*srv_sys);
1086

1087 1088 1089
#ifndef HAVE_ATOMIC_BUILTINS
	mutex_create(server_mutex_key, &server_mutex, SYNC_ANY_LATCH);
#endif /* !HAVE_ATOMIC_BUILTINS */
1090

Sergei Golubchik's avatar
Sergei Golubchik committed
1091 1092
	mutex_create(srv_innodb_monitor_mutex_key,
		     &srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
1093

1094
	if (!srv_read_only_mode) {
1095

1096 1097
		/* Number of purge threads + master thread */
		n_sys_threads = srv_n_purge_threads + 1;
1098

1099
		srv_sys_sz += n_sys_threads * sizeof(*srv_sys->sys_threads);
1100 1101
	}

1102
	srv_sys = static_cast<srv_sys_t*>(mem_zalloc(srv_sys_sz));
Sergei Golubchik's avatar
Sergei Golubchik committed
1103

1104
	srv_sys->n_sys_threads = n_sys_threads;
Sergei Golubchik's avatar
Sergei Golubchik committed
1105

1106
	if (!srv_read_only_mode) {
Sergei Golubchik's avatar
Sergei Golubchik committed
1107

1108
		mutex_create(srv_sys_mutex_key, &srv_sys->mutex, SYNC_THREADS);
1109

1110 1111
		mutex_create(srv_sys_tasks_mutex_key,
			     &srv_sys->tasks_mutex, SYNC_ANY_LATCH);
1112

1113
		srv_sys->sys_threads = (srv_slot_t*) &srv_sys[1];
1114

1115 1116
		for (ulint i = 0; i < srv_sys->n_sys_threads; ++i) {
			srv_slot_t*	slot = &srv_sys->sys_threads[i];
1117

1118
			slot->event = os_event_create();
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1119

1120 1121
			ut_a(slot->event);
		}
1122

1123
		srv_error_event = os_event_create();
1124

1125
		srv_monitor_event = os_event_create();
1126

1127
		srv_buf_dump_event = os_event_create();
1128

1129
		srv_checkpoint_completed_event = os_event_create();
1130

1131 1132 1133
		srv_redo_log_thread_finished_event = os_event_create();

		UT_LIST_INIT(srv_sys->tasks);
1134 1135
	}

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	/* page_zip_stat_per_index_mutex is acquired from:
	1. page_zip_compress() (after SYNC_FSP)
	2. page_zip_decompress()
	3. i_s_cmp_per_index_fill_low() (where SYNC_DICT is acquired)
	4. innodb_cmp_per_index_update(), no other latches
	since we do not acquire any other latches while holding this mutex,
	it can have very low level. We pick SYNC_ANY_LATCH for it. */

	mutex_create(
		page_zip_stat_per_index_mutex_key,
		&page_zip_stat_per_index_mutex, SYNC_ANY_LATCH);

	/* Create dummy indexes for infimum and supremum records */

	dict_ind_init();

	srv_conc_init();

1154 1155
	/* Initialize some INFORMATION SCHEMA internal structures */
	trx_i_s_cache_init(trx_i_s_cache);
1156 1157

	ut_crc32_init();
1158 1159
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1160
/*********************************************************************//**
1161
Frees the data structures created in srv_init(). */
1162 1163 1164 1165 1166
UNIV_INTERN
void
srv_free(void)
/*==========*/
{
1167
	srv_conc_free();
1168

1169 1170
	/* The mutexes srv_sys->mutex and srv_sys->tasks_mutex should have
	been freed by sync_close() already. */
1171 1172 1173 1174
	mem_free(srv_sys);
	srv_sys = NULL;

	trx_i_s_cache_free(trx_i_s_cache);
1175 1176 1177 1178 1179

	if (!srv_read_only_mode) {
		os_event_free(srv_buf_dump_event);
		srv_buf_dump_event = NULL;
	}
1180 1181
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1182
/*********************************************************************//**
1183 1184 1185 1186 1187 1188 1189
Initializes the synchronization primitives, memory system, and the thread
local storage. */
UNIV_INTERN
void
srv_general_init(void)
/*==================*/
{
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1190
	ut_mem_init();
1191 1192
	/* Reset the system variables in the recovery module. */
	recv_sys_var_init();
1193 1194 1195
	os_sync_init();
	sync_init();
	mem_init(srv_mem_pool_size);
1196 1197
	que_init();
	row_mysql_init();
1198 1199
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1200
/*********************************************************************//**
1201 1202 1203 1204 1205
Normalizes init parameter values to use units we use inside InnoDB. */
static
void
srv_normalize_init_values(void)
/*===========================*/
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1206
{
1207 1208
	ulint	n;
	ulint	i;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1209

1210
	n = srv_n_data_files;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1211

1212 1213 1214
	for (i = 0; i < n; i++) {
		srv_data_file_sizes[i] = srv_data_file_sizes[i]
			* ((1024 * 1024) / UNIV_PAGE_SIZE);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1215
	}
1216

1217 1218
	srv_last_file_size_max = srv_last_file_size_max
		* ((1024 * 1024) / UNIV_PAGE_SIZE);
1219

1220
	srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1221

1222
	srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1223

1224
	srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1225 1226
}

1227 1228
/*********************************************************************//**
Boots the InnoDB server. */
1229 1230
UNIV_INTERN
void
1231 1232
srv_boot(void)
/*==========*/
1233
{
1234 1235
	/* Transform the init parameter values given by MySQL to
	use units we use inside InnoDB: */
1236

1237
	srv_normalize_init_values();
Sergei Golubchik's avatar
Sergei Golubchik committed
1238

1239 1240
	/* Initialize synchronization primitives, memory management, and thread
	local storage */
1241

1242
	srv_general_init();
1243

1244
	/* Initialize this module */
1245

1246 1247
	srv_init();
	srv_mon_create();
1248 1249
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1250
/******************************************************************//**
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
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();

Sergei Golubchik's avatar
Sergei Golubchik committed
1268
	buf_refresh_io_stats_all();
1269

1270 1271 1272 1273
	srv_n_rows_inserted_old = srv_stats.n_rows_inserted;
	srv_n_rows_updated_old = srv_stats.n_rows_updated;
	srv_n_rows_deleted_old = srv_stats.n_rows_deleted;
	srv_n_rows_read_old = srv_stats.n_rows_read;
1274 1275 1276 1277

	mutex_exit(&srv_innodb_monitor_mutex);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1278
/******************************************************************//**
1279 1280 1281
Outputs to a file the output of the InnoDB Monitor.
@return FALSE if not all information printed
due to failure to obtain necessary mutex */
1282
UNIV_INTERN
1283
ibool
1284 1285
srv_printf_innodb_monitor(
/*======================*/
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1286
	FILE*	file,		/*!< in: output stream */
1287 1288 1289
	ibool	nowait,		/*!< in: whether to wait for the
				lock_sys_t:: mutex */
	ulint*	trx_start_pos,	/*!< out: file position of the start of
1290
				the list of active transactions */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1291
	ulint*	trx_end)	/*!< out: file position of the end of
1292 1293 1294 1295 1296
				the list of active transactions */
{
	double	time_elapsed;
	time_t	current_time;
	ulint	n_reserved;
1297
	ibool	ret;
1298

1299 1300
	ulong	btr_search_sys_constant;
	ulong	btr_search_sys_variable;
1301 1302 1303 1304 1305 1306
	ulint	lock_sys_subtotal;
	ulint	recv_sys_subtotal;

	ulint	i;
	trx_t*	trx;

1307 1308 1309 1310 1311
	mutex_enter(&srv_innodb_monitor_mutex);

	current_time = time(NULL);

	/* We add 0.001 seconds to time_elapsed to prevent division
1312 1313
	by zero if two users happen to call SHOW ENGINE INNODB STATUS at the
	same time */
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326

	time_elapsed = difftime(current_time, srv_last_monitor_time)
		+ 0.001;

	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",
1327
		(ulong) time_elapsed);
1328

1329 1330 1331
	fputs("-----------------\n"
	      "BACKGROUND THREAD\n"
	      "-----------------\n", file);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1332 1333
	srv_print_master_thread_info(file);

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
	fputs("----------\n"
	      "SEMAPHORES\n"
	      "----------\n", file);
	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);

1346
	if (!srv_read_only_mode && ftell(dict_foreign_err_file) != 0L) {
1347 1348 1349 1350 1351 1352 1353 1354
		fputs("------------------------\n"
		      "LATEST FOREIGN KEY ERROR\n"
		      "------------------------\n", file);
		ut_copy_file(file, dict_foreign_err_file);
	}

	mutex_exit(&dict_foreign_err_mutex);

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
	/* Only if lock_print_info_summary proceeds correctly,
	before we call the lock_print_info_all_transactions
	to print all the lock information. IMPORTANT NOTE: This
	function acquires the lock mutex on success. */
	ret = lock_print_info_summary(file, nowait);

	if (ret) {
		if (trx_start_pos) {
			long	t = ftell(file);
			if (t < 0) {
				*trx_start_pos = ULINT_UNDEFINED;
			} else {
				*trx_start_pos = (ulint) t;
			}
		}

		/* NOTE: If we get here then we have the lock mutex. This
		function will release the lock mutex that we acquired when
		we called the lock_print_info_summary() function earlier. */

		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;
			}
		}
	}

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
	fputs("--------\n"
	      "FILE I/O\n"
	      "--------\n", file);
	os_aio_print(file);

	fputs("-------------------------------------\n"
	      "INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
	      "-------------------------------------\n", file);
	ibuf_print(file);


	fprintf(file,
		"%.2f hash searches/s, %.2f non-hash searches/s\n",
		(btr_cur_n_sea - btr_cur_n_sea_old)
		/ time_elapsed,
		(btr_cur_n_non_sea - btr_cur_n_non_sea_old)
		/ time_elapsed);
	btr_cur_n_sea_old = btr_cur_n_sea;
	btr_cur_n_non_sea_old = btr_cur_n_non_sea;

	fputs("---\n"
	      "LOG\n"
	      "---\n", file);
	log_print(file);

	fputs("----------------------\n"
	      "BUFFER POOL AND MEMORY\n"
	      "----------------------\n", file);
	fprintf(file,
1416 1417 1418 1419
			"Total memory allocated " ULINTPF
			"; in additional pool allocated " ULINTPF "\n",
			ut_total_allocated_memory,
			mem_pool_get_reserved(mem_comm_pool));
1420

1421 1422
	fprintf(file,
		"Total memory allocated by read views " ULINTPF "\n",
1423
		os_atomic_increment_ulint(&srv_read_views_memory, 0));
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

	/* Calculate AHI constant and variable memory allocations */

	btr_search_sys_constant = 0;
	btr_search_sys_variable = 0;

	ut_ad(btr_search_sys->hash_tables);

	for (i = 0; i < btr_search_index_num; i++) {
		hash_table_t* ht = btr_search_sys->hash_tables[i];

		ut_ad(ht);
		ut_ad(ht->heap);

		/* Multiple mutexes/heaps are currently never used for adaptive
		hash index tables. */
1440
		ut_ad(!ht->n_sync_obj);
1441 1442 1443 1444
		ut_ad(!ht->heaps);

		btr_search_sys_variable += mem_heap_get_size(ht->heap);
		btr_search_sys_constant += ht->n_cells * sizeof(hash_cell_t);
1445 1446 1447 1448
	}

	lock_sys_subtotal = 0;
	if (trx_sys) {
1449
		mutex_enter(&trx_sys->mutex);
1450 1451
		trx = UT_LIST_GET_FIRST(trx_sys->mysql_trx_list);
		while (trx) {
1452 1453 1454 1455
			lock_sys_subtotal
				+= ((trx->lock.lock_heap)
				    ? mem_heap_get_size(trx->lock.lock_heap)
				    : 0);
1456 1457
			trx = UT_LIST_GET_NEXT(mysql_trx_list, trx);
		}
1458
		mutex_exit(&trx_sys->mutex);
1459 1460 1461 1462 1463 1464 1465
	}

	recv_sys_subtotal = ((recv_sys && recv_sys->addr_hash)
			? mem_heap_get_size(recv_sys->heap) : 0);

	fprintf(file,
			"Internal hash tables (constant factor + variable factor)\n"
1466
			"    Adaptive hash index %lu \t(%lu + " ULINTPF ")\n"
Sergei Golubchik's avatar
Sergei Golubchik committed
1467
			"    Page hash           %lu (buffer pool 0 only)\n"
1468 1469 1470 1471
			"    Dictionary cache    %lu \t(%lu + " ULINTPF ")\n"
			"    File system         %lu \t(%lu + " ULINTPF ")\n"
			"    Lock system         %lu \t(%lu + " ULINTPF ")\n"
			"    Recovery system     %lu \t(%lu + " ULINTPF ")\n",
1472

1473 1474 1475
			btr_search_sys_constant + btr_search_sys_variable,
			btr_search_sys_constant,
			btr_search_sys_variable,
1476

Sergei Golubchik's avatar
Sergei Golubchik committed
1477
			(ulong) (buf_pool_from_array(0)->page_hash->n_cells * sizeof(hash_cell_t)),
1478 1479 1480 1481 1482 1483 1484 1485

			(ulong) (dict_sys ? ((dict_sys->table_hash->n_cells
						+ dict_sys->table_id_hash->n_cells
						) * sizeof(hash_cell_t)
					+ dict_sys->size) : 0),
			(ulong) (dict_sys ? ((dict_sys->table_hash->n_cells
							+ dict_sys->table_id_hash->n_cells
							) * sizeof(hash_cell_t)) : 0),
1486
			dict_sys ? (dict_sys->size) : 0,
1487 1488 1489 1490

			(ulong) (fil_system_hash_cells() * sizeof(hash_cell_t)
					+ fil_system_hash_nodes()),
			(ulong) (fil_system_hash_cells() * sizeof(hash_cell_t)),
1491
			fil_system_hash_nodes(),
1492 1493 1494 1495

			(ulong) ((lock_sys ? (lock_sys->rec_hash->n_cells * sizeof(hash_cell_t)) : 0)
					+ lock_sys_subtotal),
			(ulong) (lock_sys ? (lock_sys->rec_hash->n_cells * sizeof(hash_cell_t)) : 0),
1496
			lock_sys_subtotal,
1497 1498 1499 1500 1501 1502

			(ulong) (((recv_sys && recv_sys->addr_hash)
						? (recv_sys->addr_hash->n_cells * sizeof(hash_cell_t)) : 0)
					+ recv_sys_subtotal),
			(ulong) ((recv_sys && recv_sys->addr_hash)
					? (recv_sys->addr_hash->n_cells * sizeof(hash_cell_t)) : 0),
1503
			recv_sys_subtotal);
1504

1505 1506 1507 1508 1509 1510 1511 1512 1513
	fprintf(file, "Dictionary memory allocated " ULINTPF "\n",
		dict_sys->size);

	buf_print_io(file);

	fputs("--------------\n"
	      "ROW OPERATIONS\n"
	      "--------------\n", file);
	fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n",
1514 1515
		(long) srv_conc_get_active_threads(),
		srv_conc_get_waiting_threads());
1516

1517
	mutex_enter(&trx_sys->mutex);
1518

1519 1520 1521
	fprintf(file, "%lu read views open inside InnoDB\n",
		UT_LIST_GET_LEN(trx_sys->view_list));

1522 1523 1524 1525 1526
	fprintf(file, "%lu RW transactions active inside InnoDB\n",
		UT_LIST_GET_LEN(trx_sys->rw_trx_list));

	fprintf(file, "%lu RO transactions active inside InnoDB\n",
		UT_LIST_GET_LEN(trx_sys->ro_trx_list));
1527 1528 1529 1530

	fprintf(file, "%lu out of %lu descriptors used\n",
		trx_sys->descr_n_used, trx_sys->descr_n_max);

Sergei Golubchik's avatar
Sergei Golubchik committed
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
	if (UT_LIST_GET_LEN(trx_sys->view_list)) {
		read_view_t*	view = UT_LIST_GET_LAST(trx_sys->view_list);

		if (view) {
			fprintf(file, "---OLDEST VIEW---\n");
			read_view_print(file, view);
			fprintf(file, "-----------------\n");
		}
	}

1541
	mutex_exit(&trx_sys->mutex);
1542

1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
	n_reserved = fil_space_get_n_reserved_extents(0);
	if (n_reserved > 0) {
		fprintf(file,
			"%lu tablespace extents now reserved for"
			" B-tree split operations\n",
			(ulong) n_reserved);
	}

#ifdef UNIV_LINUX
	fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n",
		(ulong) srv_main_thread_process_no,
		(ulong) srv_main_thread_id,
		srv_main_thread_op_info);
#else
	fprintf(file, "Main thread id %lu, state: %s\n",
		(ulong) srv_main_thread_id,
		srv_main_thread_op_info);
#endif
	fprintf(file,
		"Number of rows inserted " ULINTPF
		", updated " ULINTPF ", deleted " ULINTPF
		", read " ULINTPF "\n",
1565 1566 1567 1568
		(ulint) srv_stats.n_rows_inserted,
		(ulint) srv_stats.n_rows_updated,
		(ulint) srv_stats.n_rows_deleted,
		(ulint) srv_stats.n_rows_read);
1569 1570 1571
	fprintf(file,
		"%.2f inserts/s, %.2f updates/s,"
		" %.2f deletes/s, %.2f reads/s\n",
1572
		((ulint) srv_stats.n_rows_inserted - srv_n_rows_inserted_old)
1573
		/ time_elapsed,
1574
		((ulint) srv_stats.n_rows_updated - srv_n_rows_updated_old)
1575
		/ time_elapsed,
1576
		((ulint) srv_stats.n_rows_deleted - srv_n_rows_deleted_old)
1577
		/ time_elapsed,
1578
		((ulint) srv_stats.n_rows_read - srv_n_rows_read_old)
1579 1580
		/ time_elapsed);

1581 1582 1583 1584
	srv_n_rows_inserted_old = srv_stats.n_rows_inserted;
	srv_n_rows_updated_old = srv_stats.n_rows_updated;
	srv_n_rows_deleted_old = srv_stats.n_rows_deleted;
	srv_n_rows_read_old = srv_stats.n_rows_read;
1585

1586 1587 1588 1589 1590 1591 1592
	/* 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) {
		lock_print_info_all_transactions(file);
1593 1594
	}

1595 1596 1597 1598 1599
	fputs("----------------------------\n"
	      "END OF INNODB MONITOR OUTPUT\n"
	      "============================\n", file);
	mutex_exit(&srv_innodb_monitor_mutex);
	fflush(file);
1600 1601

	return(ret);
1602 1603
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1604
/******************************************************************//**
1605 1606 1607 1608
Function to pass InnoDB status variables to MySQL */
UNIV_INTERN
void
srv_export_innodb_status(void)
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1609
/*==========================*/
1610
{
1611 1612 1613 1614 1615 1616 1617 1618
	buf_pool_stat_t		stat;
	buf_pools_list_size_t	buf_pools_list_size;
	ulint			LRU_len;
	ulint			free_len;
	ulint			flush_list_len;
	ulint			mem_adaptive_hash, mem_dictionary;
	read_view_t*		oldest_view;
	ulint			i;
Sergei Golubchik's avatar
Sergei Golubchik committed
1619 1620 1621

	buf_get_total_stat(&stat);
	buf_get_total_list_len(&LRU_len, &free_len, &flush_list_len);
1622
	buf_get_total_list_size_in_bytes(&buf_pools_list_size);
Sergei Golubchik's avatar
Sergei Golubchik committed
1623

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
	mem_adaptive_hash = 0;

	ut_ad(btr_search_sys->hash_tables);

	for (i = 0; i < btr_search_index_num; i++) {
		hash_table_t*	ht = btr_search_sys->hash_tables[i];

		ut_ad(ht);
		ut_ad(ht->heap);
		/* Multiple mutexes/heaps are currently never used for adaptive
		hash index tables. */
1635
		ut_ad(!ht->n_sync_obj);
1636 1637 1638 1639
		ut_ad(!ht->heaps);

		mem_adaptive_hash += mem_heap_get_size(ht->heap);
		mem_adaptive_hash += ht->n_cells * sizeof(hash_cell_t);
Sergei Golubchik's avatar
Sergei Golubchik committed
1640 1641 1642 1643 1644 1645 1646
	}

	mem_dictionary = (dict_sys ? ((dict_sys->table_hash->n_cells
					+ dict_sys->table_id_hash->n_cells
				      ) * sizeof(hash_cell_t)
				+ dict_sys->size) : 0);

1647 1648
	mutex_enter(&srv_innodb_monitor_mutex);

1649 1650
	export_vars.innodb_data_pending_reads =
		os_n_pending_reads;
Sergei Golubchik's avatar
Sergei Golubchik committed
1651

1652 1653 1654 1655 1656 1657
	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;
Sergei Golubchik's avatar
Sergei Golubchik committed
1658 1659 1660 1661 1662 1663
	export_vars.innodb_adaptive_hash_hash_searches
		= btr_cur_n_sea;
	export_vars.innodb_adaptive_hash_non_hash_searches
		= btr_cur_n_non_sea;
	export_vars.innodb_background_log_sync
		= srv_log_writes_and_flush;
1664

1665
	export_vars.innodb_data_fsyncs = os_n_fsyncs;
1666 1667 1668

	export_vars.innodb_data_read = srv_stats.data_read;

1669
	export_vars.innodb_data_reads = os_n_file_reads;
1670

1671
	export_vars.innodb_data_writes = os_n_file_writes;
1672 1673 1674

	export_vars.innodb_data_written = srv_stats.data_written;

Sergei Golubchik's avatar
Sergei Golubchik committed
1675
	export_vars.innodb_buffer_pool_read_requests = stat.n_page_gets;
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699

	export_vars.innodb_buffer_pool_write_requests =
		srv_stats.buf_pool_write_requests;

	export_vars.innodb_buffer_pool_wait_free =
		srv_stats.buf_pool_wait_free;

	export_vars.innodb_buffer_pool_pages_flushed =
		srv_stats.buf_pool_flushed;

	export_vars.innodb_buffer_pool_reads = srv_stats.buf_pool_reads;

	export_vars.innodb_buffer_pool_read_ahead_rnd =
		stat.n_ra_pages_read_rnd;

	export_vars.innodb_buffer_pool_read_ahead =
		stat.n_ra_pages_read;

	export_vars.innodb_buffer_pool_read_ahead_evicted =
		stat.n_ra_pages_evicted;

	export_vars.innodb_buffer_pool_pages_LRU_flushed =
		stat.buf_lru_flush_page_count;

Sergei Golubchik's avatar
Sergei Golubchik committed
1700
	export_vars.innodb_buffer_pool_pages_data = LRU_len;
1701

1702 1703 1704
	export_vars.innodb_buffer_pool_bytes_data =
		buf_pools_list_size.LRU_bytes
		+ buf_pools_list_size.unzip_LRU_bytes;
1705

Sergei Golubchik's avatar
Sergei Golubchik committed
1706
	export_vars.innodb_buffer_pool_pages_dirty = flush_list_len;
1707

1708 1709
	export_vars.innodb_buffer_pool_bytes_dirty =
		buf_pools_list_size.flush_list_bytes;
1710

Sergei Golubchik's avatar
Sergei Golubchik committed
1711
	export_vars.innodb_buffer_pool_pages_free = free_len;
1712 1713 1714

	export_vars.innodb_deadlocks = srv_stats.lock_deadlock_count;

Vadim Tkachenko's avatar
Vadim Tkachenko committed
1715
#ifdef UNIV_DEBUG
1716 1717
	export_vars.innodb_buffer_pool_pages_latched =
		buf_get_latched_pages_number();
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1718
#endif /* UNIV_DEBUG */
Sergei Golubchik's avatar
Sergei Golubchik committed
1719 1720
	export_vars.innodb_buffer_pool_pages_total = buf_pool_get_n_pages();

1721 1722
	export_vars.innodb_buffer_pool_pages_misc =
		buf_pool_get_n_pages() - LRU_len - free_len;
Sergei Golubchik's avatar
Sergei Golubchik committed
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756

	export_vars.innodb_buffer_pool_pages_made_young
		= stat.n_pages_made_young;
	export_vars.innodb_buffer_pool_pages_made_not_young
		= stat.n_pages_not_made_young;
	export_vars.innodb_buffer_pool_pages_old = 0;
	for (i = 0; i < srv_buf_pool_instances; i++) {
		buf_pool_t*	buf_pool = buf_pool_from_array(i);
		export_vars.innodb_buffer_pool_pages_old
			+= buf_pool->LRU_old_len;
	}
	export_vars.innodb_checkpoint_age
		= (log_sys->lsn - log_sys->last_checkpoint_lsn);
	export_vars.innodb_checkpoint_max_age
		= log_sys->max_checkpoint_age;
	export_vars.innodb_history_list_length
		= trx_sys->rseg_history_len;
	ibuf_export_ibuf_status(
			&export_vars.innodb_ibuf_size,
			&export_vars.innodb_ibuf_free_list,
			&export_vars.innodb_ibuf_segment_size,
			&export_vars.innodb_ibuf_merges,
			&export_vars.innodb_ibuf_merged_inserts,
			&export_vars.innodb_ibuf_merged_delete_marks,
			&export_vars.innodb_ibuf_merged_deletes,
			&export_vars.innodb_ibuf_discarded_inserts,
			&export_vars.innodb_ibuf_discarded_delete_marks,
			&export_vars.innodb_ibuf_discarded_deletes);
	export_vars.innodb_lsn_current
		= log_sys->lsn;
	export_vars.innodb_lsn_flushed
		= log_sys->flushed_to_disk_lsn;
	export_vars.innodb_lsn_last_checkpoint
		= log_sys->last_checkpoint_lsn;
1757 1758 1759 1760
	export_vars.innodb_master_thread_active_loops
		= srv_main_active_loops;
	export_vars.innodb_master_thread_idle_loops
		= srv_main_idle_loops;
Sergei Golubchik's avatar
Sergei Golubchik committed
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
	export_vars.innodb_max_trx_id
		= trx_sys->max_trx_id;
	export_vars.innodb_mem_adaptive_hash
		= mem_adaptive_hash;
	export_vars.innodb_mem_dictionary
		= mem_dictionary;
	export_vars.innodb_mem_total
		= ut_total_allocated_memory;
	export_vars.innodb_mutex_os_waits
		= mutex_os_wait_count;
	export_vars.innodb_mutex_spin_rounds
		= mutex_spin_round_count;
	export_vars.innodb_mutex_spin_waits
		= mutex_spin_wait_count;
	export_vars.innodb_s_lock_os_waits
1776
		= rw_lock_stats.rw_s_os_wait_count;
Sergei Golubchik's avatar
Sergei Golubchik committed
1777
	export_vars.innodb_s_lock_spin_rounds
1778
		= rw_lock_stats.rw_s_spin_round_count;
Sergei Golubchik's avatar
Sergei Golubchik committed
1779
	export_vars.innodb_s_lock_spin_waits
1780
		= rw_lock_stats.rw_s_spin_wait_count;
Sergei Golubchik's avatar
Sergei Golubchik committed
1781
	export_vars.innodb_x_lock_os_waits
1782
		= rw_lock_stats.rw_x_os_wait_count;
Sergei Golubchik's avatar
Sergei Golubchik committed
1783
	export_vars.innodb_x_lock_spin_rounds
1784
		= rw_lock_stats.rw_x_spin_round_count;
Sergei Golubchik's avatar
Sergei Golubchik committed
1785
	export_vars.innodb_x_lock_spin_waits
1786
		= rw_lock_stats.rw_x_spin_wait_count;
Sergei Golubchik's avatar
Sergei Golubchik committed
1787 1788 1789 1790 1791

	oldest_view = UT_LIST_GET_LAST(trx_sys->view_list);
	export_vars.innodb_oldest_view_low_limit_trx_id
		= oldest_view ? oldest_view->low_limit_id : 0;

1792 1793
	export_vars.innodb_purge_trx_id = purge_sys->limit.trx_no;
	export_vars.innodb_purge_undo_no = purge_sys->limit.undo_no;
Sergei Golubchik's avatar
Sergei Golubchik committed
1794 1795
	export_vars.innodb_current_row_locks
		= lock_sys->rec_num;
1796

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1797
#ifdef HAVE_ATOMIC_BUILTINS
Vadim Tkachenko's avatar
Vadim Tkachenko committed
1798 1799 1800 1801
	export_vars.innodb_have_atomic_builtins = 1;
#else
	export_vars.innodb_have_atomic_builtins = 0;
#endif
1802
	export_vars.innodb_page_size = UNIV_PAGE_SIZE;
1803 1804 1805 1806 1807

	export_vars.innodb_log_waits = srv_stats.log_waits;

	export_vars.innodb_os_log_written = srv_stats.os_log_written;

1808
	export_vars.innodb_os_log_fsyncs = fil_n_log_flushes;
1809

1810
	export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes;
1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823

	export_vars.innodb_os_log_pending_writes =
		srv_stats.os_log_pending_writes;

	export_vars.innodb_log_write_requests = srv_stats.log_write_requests;

	export_vars.innodb_log_writes = srv_stats.log_writes;

	export_vars.innodb_dblwr_pages_written =
		srv_stats.dblwr_pages_written;

	export_vars.innodb_dblwr_writes = srv_stats.dblwr_writes;

Sergei Golubchik's avatar
Sergei Golubchik committed
1824
	export_vars.innodb_pages_created = stat.n_pages_created;
1825

Sergei Golubchik's avatar
Sergei Golubchik committed
1826
	export_vars.innodb_pages_read = stat.n_pages_read;
1827

Sergei Golubchik's avatar
Sergei Golubchik committed
1828
	export_vars.innodb_pages_written = stat.n_pages_written;
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

	export_vars.innodb_row_lock_waits = srv_stats.n_lock_wait_count;

	export_vars.innodb_row_lock_current_waits =
		srv_stats.n_lock_wait_current_count;

	export_vars.innodb_row_lock_time = srv_stats.n_lock_wait_time / 1000;

	if (srv_stats.n_lock_wait_count > 0) {

1839
		export_vars.innodb_row_lock_time_avg = (ulint)
1840 1841 1842
			(srv_stats.n_lock_wait_time
			 / 1000 / srv_stats.n_lock_wait_count);

1843 1844 1845
	} else {
		export_vars.innodb_row_lock_time_avg = 0;
	}
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864

	export_vars.innodb_row_lock_time_max =
		lock_sys->n_lock_max_wait_time / 1000;

	export_vars.innodb_rows_read = srv_stats.n_rows_read;

	export_vars.innodb_rows_inserted = srv_stats.n_rows_inserted;

	export_vars.innodb_rows_updated = srv_stats.n_rows_updated;

	export_vars.innodb_rows_deleted = srv_stats.n_rows_deleted;

	export_vars.innodb_num_open_files = fil_n_file_opened;

	export_vars.innodb_truncated_status_writes =
		srv_truncated_status_writes;

	export_vars.innodb_available_undo_logs = srv_available_undo_logs;
	export_vars.innodb_read_views_memory
1865
		= os_atomic_increment_ulint(&srv_read_views_memory, 0);
1866
	export_vars.innodb_descriptors_memory
1867
		= os_atomic_increment_ulint(&srv_descriptors_memory, 0);
1868

1869 1870 1871 1872
	export_vars.innodb_page_compression_saved = srv_stats.page_compression_saved;
	export_vars.innodb_page_compression_trim_sect512 = srv_stats.page_compression_trim_sect512;
	export_vars.innodb_page_compression_trim_sect4096 = srv_stats.page_compression_trim_sect4096;
	export_vars.innodb_index_pages_written = srv_stats.index_pages_written;
1873
	export_vars.innodb_non_index_pages_written = srv_stats.non_index_pages_written;
1874 1875 1876 1877 1878
	export_vars.innodb_pages_page_compressed = srv_stats.pages_page_compressed;
	export_vars.innodb_page_compressed_trim_op = srv_stats.page_compressed_trim_op;
	export_vars.innodb_page_compressed_trim_op_saved = srv_stats.page_compressed_trim_op_saved;
	export_vars.innodb_pages_page_decompressed = srv_stats.pages_page_decompressed;

1879
#ifdef UNIV_DEBUG
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
	rw_lock_s_lock(&purge_sys->latch);
	trx_id_t	done_trx_no	= purge_sys->done.trx_no;
	trx_id_t	up_limit_id	= purge_sys->view
		? purge_sys->view->up_limit_id
		: 0;
	rw_lock_s_unlock(&purge_sys->latch);

	mutex_enter(&trx_sys->mutex);
	trx_id_t	max_trx_id	= trx_sys->rw_max_trx_id;
	mutex_exit(&trx_sys->mutex);

	if (!done_trx_no || max_trx_id < done_trx_no - 1) {
		export_vars.innodb_purge_trx_id_age = 0;
	} else {
		export_vars.innodb_purge_trx_id_age =
			(ulint) (max_trx_id - done_trx_no + 1);
	}
1897

1898 1899 1900 1901 1902 1903
	if (!up_limit_id
	    || max_trx_id < up_limit_id) {
		export_vars.innodb_purge_view_trx_id_age = 0;
	} else {
		export_vars.innodb_purge_view_trx_id_age =
			(ulint) (max_trx_id - up_limit_id);
1904 1905 1906
	}
#endif /* UNIV_DEBUG */

1907 1908 1909
	mutex_exit(&srv_innodb_monitor_mutex);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1910
/*********************************************************************//**
1911
A thread which prints the info output by various InnoDB monitors.
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1912
@return	a dummy parameter */
1913
extern "C" UNIV_INTERN
1914
os_thread_ret_t
1915 1916
DECLARE_THREAD(srv_monitor_thread)(
/*===============================*/
1917
	void*	arg __attribute__((unused)))
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
1918
			/*!< in: a dummy parameter required by
1919 1920
			os_thread_create */
{
Sergei Golubchik's avatar
Sergei Golubchik committed
1921
	ib_int64_t	sig_count;
1922 1923 1924 1925 1926
	double		time_elapsed;
	time_t		current_time;
	time_t		last_table_monitor_time;
	time_t		last_tablespace_monitor_time;
	time_t		last_monitor_time;
1927 1928
	ulint		mutex_skipped;
	ibool		last_srv_print_monitor;
1929

1930 1931
	ut_ad(!srv_read_only_mode);

1932 1933 1934
#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Lock timeout thread starts, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
1935
#endif /* UNIV_DEBUG_THREAD_CREATION */
Sergei Golubchik's avatar
Sergei Golubchik committed
1936 1937 1938

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_monitor_thread_key);
1939 1940
#endif /* UNIV_PFS_THREAD */
	srv_monitor_active = TRUE;
Sergei Golubchik's avatar
Sergei Golubchik committed
1941

1942
	UT_NOT_USED(arg);
Sergei Golubchik's avatar
Sergei Golubchik committed
1943 1944 1945 1946
	srv_last_monitor_time = ut_time();
	last_table_monitor_time = ut_time();
	last_tablespace_monitor_time = ut_time();
	last_monitor_time = ut_time();
1947 1948
	mutex_skipped = 0;
	last_srv_print_monitor = srv_print_innodb_monitor;
1949
loop:
1950
	/* Wake up every 5 seconds to see if we need to print
Sergei Golubchik's avatar
Sergei Golubchik committed
1951
	monitor information or if signalled at shutdown. */
1952

Sergei Golubchik's avatar
Sergei Golubchik committed
1953
	sig_count = os_event_reset(srv_monitor_event);
1954

Sergei Golubchik's avatar
Sergei Golubchik committed
1955 1956 1957
	os_event_wait_time_low(srv_monitor_event, 5000000, sig_count);

	current_time = ut_time();
1958 1959 1960 1961

	time_elapsed = difftime(current_time, last_monitor_time);

	if (time_elapsed > 15) {
Sergei Golubchik's avatar
Sergei Golubchik committed
1962
		last_monitor_time = ut_time();
1963 1964

		if (srv_print_innodb_monitor) {
1965 1966
			/* Reset mutex_skipped counter everytime
			srv_print_innodb_monitor changes. This is to
1967
			ensure we will not be blocked by lock_sys->mutex
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
			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;
1985 1986
		}

1987

1988 1989 1990 1991
		/* We don't create the temp files or associated
		mutexes in read-only-mode */

		if (!srv_read_only_mode && srv_innodb_status) {
1992 1993
			mutex_enter(&srv_monitor_file_mutex);
			rewind(srv_monitor_file);
1994 1995 1996 1997 1998 1999 2000 2001
			if (!srv_printf_innodb_monitor(srv_monitor_file,
						MUTEX_NOWAIT(mutex_skipped),
						NULL, NULL)) {
				mutex_skipped++;
			} else {
				mutex_skipped = 0;
			}

2002 2003 2004 2005 2006 2007 2008
			os_file_set_eof(srv_monitor_file);
			mutex_exit(&srv_monitor_file_mutex);
		}

		if (srv_print_innodb_tablespace_monitor
		    && difftime(current_time,
				last_tablespace_monitor_time) > 60) {
Sergei Golubchik's avatar
Sergei Golubchik committed
2009
			last_tablespace_monitor_time = ut_time();
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034

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

			ut_print_timestamp(stderr);

			fputs(" INNODB TABLESPACE MONITOR OUTPUT\n"
			      "========================"
			      "========================\n",
			      stderr);

			fsp_print(0);
			fputs("Validating tablespace\n", stderr);
			fsp_validate(0);
			fputs("Validation ok\n"
			      "---------------------------------------\n"
			      "END OF INNODB TABLESPACE MONITOR OUTPUT\n"
			      "=======================================\n",
			      stderr);
		}

		if (srv_print_innodb_table_monitor
		    && difftime(current_time, last_table_monitor_time) > 60) {

Sergei Golubchik's avatar
Sergei Golubchik committed
2035
			last_table_monitor_time = ut_time();
2036

2037 2038 2039
			fprintf(stderr, "Warning: %s\n",
				DEPRECATED_MSG_INNODB_TABLE_MONITOR);

2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
			fputs("===========================================\n",
			      stderr);

			ut_print_timestamp(stderr);

			fputs(" INNODB TABLE MONITOR OUTPUT\n"
			      "===========================================\n",
			      stderr);
			dict_print();

			fputs("-----------------------------------\n"
			      "END OF INNODB TABLE MONITOR OUTPUT\n"
			      "==================================\n",
			      stderr);
2054 2055 2056

			fprintf(stderr, "Warning: %s\n",
				DEPRECATED_MSG_INNODB_TABLE_MONITOR);
2057 2058 2059
		}
	}

2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
	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;
	}

	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;
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2084
/*********************************************************************//**
2085
A thread which prints warnings about semaphore waits which have lasted
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2086 2087
too long. These can be used to track bugs which cause hangs.
@return	a dummy parameter */
2088
extern "C" UNIV_INTERN
2089
os_thread_ret_t
2090 2091
DECLARE_THREAD(srv_error_monitor_thread)(
/*=====================================*/
2092
	void*	arg __attribute__((unused)))
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2093
			/*!< in: a dummy parameter required by
2094 2095 2096 2097
			os_thread_create */
{
	/* number of successive fatal timeouts observed */
	ulint		fatal_cnt	= 0;
2098 2099
	lsn_t		old_lsn;
	lsn_t		new_lsn;
Sergei Golubchik's avatar
Sergei Golubchik committed
2100 2101 2102 2103 2104 2105 2106
	ib_int64_t	sig_count;
	/* longest waiting thread for a semaphore */
	os_thread_id_t	waiter		= os_thread_get_curr_id();
	os_thread_id_t	old_waiter	= waiter;
	/* the semaphore that is being waited for */
	const void*	sema		= NULL;
	const void*	old_sema	= NULL;
2107

2108 2109
	ut_ad(!srv_read_only_mode);

2110 2111 2112 2113 2114
	old_lsn = srv_start_lsn;

#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Error monitor thread starts, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
2115
#endif /* UNIV_DEBUG_THREAD_CREATION */
Sergei Golubchik's avatar
Sergei Golubchik committed
2116 2117 2118

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_error_monitor_thread_key);
2119
#endif /* UNIV_PFS_THREAD */
2120 2121
	srv_error_monitor_active = TRUE;

2122
loop:
2123 2124 2125 2126 2127 2128 2129 2130
	/* 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();

	if (new_lsn < old_lsn) {
		ut_print_timestamp(stderr);
		fprintf(stderr,
2131
			"  InnoDB: Error: old log sequence number " LSN_PF
2132
			" was greater\n"
2133
			"InnoDB: than the new log sequence number " LSN_PF "!\n"
2134 2135 2136
			"InnoDB: Please submit a bug report"
			" to http://bugs.mysql.com\n",
			old_lsn, new_lsn);
Sergei Golubchik's avatar
Sergei Golubchik committed
2137
		ut_ad(0);
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
	}

	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();
	}

	/* Update the statistics collected for deciding LRU
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2150
	eviction policy. */
2151 2152 2153 2154 2155
	buf_LRU_stat_update();

	/* 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: */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2156

2157 2158
	sync_arr_wake_threads_if_sema_free();

Sergei Golubchik's avatar
Sergei Golubchik committed
2159 2160
	if (sync_array_print_long_waits(&waiter, &sema)
	    && sema == old_sema && os_thread_eq(waiter, old_waiter)) {
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
		fatal_cnt++;
		if (fatal_cnt > 10) {

			fprintf(stderr,
				"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);

			ut_error;
		}
	} else {
		fatal_cnt = 0;
Sergei Golubchik's avatar
Sergei Golubchik committed
2175 2176
		old_waiter = waiter;
		old_sema = sema;
2177 2178
	}

2179 2180 2181 2182 2183
	if (srv_kill_idle_transaction && trx_sys) {
		trx_t*	trx;
		time_t	now;
rescan_idle:
		now = time(NULL);
2184
		mutex_enter(&trx_sys->mutex);
2185 2186
		trx = UT_LIST_GET_FIRST(trx_sys->mysql_trx_list);
		while (trx) {
2187 2188
			if (!trx_state_eq(trx, TRX_STATE_NOT_STARTED)
			    && trx_state_eq(trx, TRX_STATE_ACTIVE)
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
			    && trx->mysql_thd
			    && innobase_thd_is_idle(trx->mysql_thd)) {
				ib_int64_t	start_time = innobase_thd_get_start_time(trx->mysql_thd);
				ulong		thd_id = innobase_thd_get_thread_id(trx->mysql_thd);

				if (trx->last_stmt_start != start_time) {
					trx->idle_start = now;
					trx->last_stmt_start = start_time;
				} else if (difftime(now, trx->idle_start)
					   > srv_kill_idle_transaction) {
					/* kill the session */
2200
					mutex_exit(&trx_sys->mutex);
2201 2202 2203 2204 2205 2206
					innobase_thd_kill(thd_id);
					goto rescan_idle;
				}
			}
			trx = UT_LIST_GET_NEXT(mysql_trx_list, trx);
		}
2207
		mutex_exit(&trx_sys->mutex);
2208 2209
	}

2210 2211 2212 2213 2214
	/* Flush stderr so that a database user gets the output
	to possible MySQL error file */

	fflush(stderr);

Sergei Golubchik's avatar
Sergei Golubchik committed
2215 2216 2217
	sig_count = os_event_reset(srv_error_event);

	os_event_wait_time_low(srv_error_event, 1000000, sig_count);
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233

	if (srv_shutdown_state < SRV_SHUTDOWN_CLEANUP) {

		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);

	OS_THREAD_DUMMY_RETURN;
}

2234 2235
/******************************************************************//**
Increment the server activity count. */
2236
UNIV_INTERN
2237 2238 2239
void
srv_inc_activity_count(void)
/*========================*/
2240
{
2241
	srv_sys->activity_count.inc();
2242 2243
}

Sergei Golubchik's avatar
Sergei Golubchik committed
2244
/**********************************************************************//**
Sergei Golubchik's avatar
Sergei Golubchik committed
2245
Check whether any background thread is active. If so return the thread
2246 2247
type.
@return SRV_NONE if all are suspended or have exited, thread
Sergei Golubchik's avatar
Sergei Golubchik committed
2248
type if any are still active. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2249
UNIV_INTERN
2250
srv_thread_type
Sergei Golubchik's avatar
Sergei Golubchik committed
2251 2252
srv_get_active_thread_type(void)
/*============================*/
Sergei Golubchik's avatar
Sergei Golubchik committed
2253
{
2254 2255 2256 2257 2258
	srv_thread_type ret = SRV_NONE;

	if (srv_read_only_mode) {
		return(SRV_NONE);
	}
Sergei Golubchik's avatar
Sergei Golubchik committed
2259

2260
	srv_sys_mutex_enter();
Sergei Golubchik's avatar
Sergei Golubchik committed
2261

2262 2263 2264
	for (ulint i = SRV_WORKER; i <= SRV_MASTER; ++i) {
		if (srv_sys->n_threads_active[i] != 0) {
			ret = static_cast<srv_thread_type>(i);
Sergei Golubchik's avatar
Sergei Golubchik committed
2265 2266 2267 2268
			break;
		}
	}

2269
	srv_sys_mutex_exit();
Sergei Golubchik's avatar
Sergei Golubchik committed
2270

2271 2272 2273 2274 2275
	/* Check only on shutdown. */
	if (ret == SRV_NONE
	    && srv_shutdown_state != SRV_SHUTDOWN_NONE
	    && trx_purge_state() != PURGE_STATE_DISABLED
	    && trx_purge_state() != PURGE_STATE_EXIT) {
Sergei Golubchik's avatar
Sergei Golubchik committed
2276

2277 2278
		ret = SRV_PURGE;
	}
Sergei Golubchik's avatar
Sergei Golubchik committed
2279

2280 2281
	return(ret);
}
Sergei Golubchik's avatar
Sergei Golubchik committed
2282

2283 2284 2285 2286 2287 2288 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
/**********************************************************************//**
Check whether any background thread are active. If so print which thread
is active. Send the threads wakeup signal.
@return name of thread that is active or NULL */
UNIV_INTERN
const char*
srv_any_background_threads_are_active(void)
/*=======================================*/
{
	const char*	thread_active = NULL;

	if (srv_read_only_mode) {
		return(NULL);
	} else if (srv_error_monitor_active) {
		thread_active = "srv_error_monitor_thread";
	} else if (lock_sys->timeout_thread_active) {
		thread_active = "srv_lock_timeout thread";
	} else if (srv_monitor_active) {
		thread_active = "srv_monitor_thread";
	} else if (srv_buf_dump_thread_active) {
		thread_active = "buf_dump_thread";
	} else if (srv_dict_stats_thread_active) {
		thread_active = "dict_stats_thread";
	}

	os_event_set(srv_error_event);
	os_event_set(srv_monitor_event);
	os_event_set(srv_buf_dump_event);
	os_event_set(lock_sys->timeout_event);
	os_event_set(dict_stats_event);

	return(thread_active);
Sergei Golubchik's avatar
Sergei Golubchik committed
2315 2316
}

2317 2318 2319
/******************************************************************//**
A thread which follows the redo log and outputs the changed page bitmap.
@return a dummy value */
2320
extern "C" UNIV_INTERN
2321
os_thread_ret_t
2322 2323
DECLARE_THREAD(srv_redo_log_follow_thread)(
/*=======================================*/
2324 2325 2326 2327
	void*	arg __attribute__((unused)))	/*!< in: a dummy parameter
						     required by
						     os_thread_create */
{
2328 2329
	ut_ad(!srv_read_only_mode);

2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Redo log follower thread starts, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
#endif

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_log_tracking_thread_key);
#endif

	my_thread_init();

	do {
		os_event_wait(srv_checkpoint_completed_event);
		os_event_reset(srv_checkpoint_completed_event);

2345 2346 2347 2348 2349 2350
#ifdef UNIV_DEBUG
		if (!srv_track_changed_pages) {
			continue;
		}
#endif

2351
		if (srv_shutdown_state < SRV_SHUTDOWN_LAST_PHASE) {
2352 2353
			if (!log_online_follow_redo_log()) {
				/* TODO: sync with I_S log tracking status? */
2354 2355 2356
				ib_logf(IB_LOG_LEVEL_ERROR,
					"log tracking bitmap write failed, "
					"stopping log tracking thread!\n");
2357 2358
				break;
			}
2359 2360 2361 2362
		}

	} while (srv_shutdown_state < SRV_SHUTDOWN_LAST_PHASE);

2363
	srv_track_changed_pages = FALSE;
2364 2365 2366 2367 2368 2369 2370 2371 2372
	log_online_read_shutdown();
	os_event_set(srv_redo_log_thread_finished_event);

	my_thread_end();
	os_thread_exit(NULL);

	OS_THREAD_DUMMY_RETURN;
}

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
/*************************************************************//**
Removes old archived transaction log files.
Both parameters couldn't be provided at the same time */
dberr_t
purge_archived_logs(
	time_t	before_date,		/*!< in: all files modified
					before timestamp should be removed */
	lsn_t	before_no)		/*!< in: files with this number in name
					and earler should be removed */
{
	log_group_t*	group = UT_LIST_GET_FIRST(log_sys->log_groups);

	os_file_dir_t	dir;
	os_file_stat_t	fileinfo;
	char		archived_log_filename[OS_FILE_MAX_PATH];
	char		namegen[OS_FILE_MAX_PATH];
	ulint		dirnamelen;

	if (srv_arch_dir) {
		dir = os_file_opendir(srv_arch_dir, FALSE);
		if (!dir) {
			ib_logf(IB_LOG_LEVEL_WARN,
				"opening archived log directory %s failed. "
				"Purge archived logs are not available\n",
				srv_arch_dir);
			/* failed to open directory */
			return(DB_ERROR);
		}
	} else {
		/* log archive directory is not specified */
		return(DB_ERROR);
	}

	dirnamelen = strlen(srv_arch_dir);

	memcpy(archived_log_filename, srv_arch_dir, dirnamelen);
	if (dirnamelen &&
		archived_log_filename[dirnamelen - 1] != SRV_PATH_SEPARATOR) {
		archived_log_filename[dirnamelen++] = SRV_PATH_SEPARATOR;
	}

	memset(&fileinfo, 0, sizeof(fileinfo));
	while(!os_file_readdir_next_file(srv_arch_dir, dir,
				&fileinfo) ) {
		if (strncmp(fileinfo.name,
			IB_ARCHIVED_LOGS_PREFIX, IB_ARCHIVED_LOGS_PREFIX_LEN)) {
			continue;
		}
		if (dirnamelen + strlen(fileinfo.name) + 2 > OS_FILE_MAX_PATH)
			continue;

		snprintf(archived_log_filename + dirnamelen, OS_FILE_MAX_PATH,
				"%s", fileinfo.name);

		if (before_no) {
			ib_uint64_t log_file_no = strtoull(fileinfo.name +
					IB_ARCHIVED_LOGS_PREFIX_LEN,
					NULL, 10);
			if (log_file_no == 0 || before_no <= log_file_no) {
				continue;
			}
		} else {
			fileinfo.mtime = 0;
			if (os_file_get_status(archived_log_filename,
					&fileinfo, false) != DB_SUCCESS ||
					fileinfo.mtime == 0) {
				continue;
			}

			if (before_date == 0 || fileinfo.mtime > before_date) {
				continue;
			}
		}

		/* We are going to delete archived file. Acquire log_sys->mutex
		to make sure that we are the only who try to delete file. This
		also prevents log system from using this file. Do not delete
		file if it is currently in progress of writting or have
		pending IO. This is enforced by checking:
		  1. fil_space_contains_node.
		  2. group->archived_offset % group->file_size != 0, i.e. 
		     there is archive in progress and we are going to delete it.
		This covers 3 cases:
		  a. Usual case when we have one archive in progress,
		     both 1 and 2 are TRUE
		  b. When we have more then 1 archive in fil_space,
		     this can happen when flushed LSN range crosses file
		     boundary
		  c. When we have empty fil_space, but existing file will be
		     opened once archiving operation is requested. This usually
		     happens on startup.
		*/

		mutex_enter(&log_sys->mutex);

		log_archived_file_name_gen(namegen, sizeof(namegen),
					   group->id, group->archived_file_no);

		if (fil_space_contains_node(group->archive_space_id,
					    archived_log_filename) ||
		    (group->archived_offset % group->file_size != 0 &&
		     strcmp(namegen, archived_log_filename) == 0)) {

			mutex_exit(&log_sys->mutex);
			continue;
		}

		if (!os_file_delete_if_exists(innodb_file_data_key,
					     archived_log_filename)) {

			ib_logf(IB_LOG_LEVEL_WARN,
				"can't delete archived log file %s.\n",
				archived_log_filename);

			mutex_exit(&log_sys->mutex);
			os_file_closedir(dir);

			return(DB_ERROR);
		}

		mutex_exit(&log_sys->mutex);
	}

	os_file_closedir(dir);

	return(DB_SUCCESS);
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2501
/*******************************************************************//**
2502 2503 2504
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
Sergei Golubchik's avatar
Sergei Golubchik committed
2505 2506
thread stays suspended (we do not protect our operation with the
srv_sys_t->mutex, for performance reasons). */
2507 2508 2509 2510 2511
UNIV_INTERN
void
srv_active_wake_master_thread(void)
/*===============================*/
{
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
	if (srv_read_only_mode) {
		return;
	}

	ut_ad(!srv_sys_mutex_own());

	srv_inc_activity_count();

	if (srv_sys->n_threads_active[SRV_MASTER] == 0) {
		srv_slot_t*	slot;

		srv_sys_mutex_enter();

		slot = &srv_sys->sys_threads[SRV_MASTER_SLOT];
2526

2527
		/* Only if the master thread has been started. */
2528

2529 2530 2531 2532 2533 2534 2535 2536
		if (slot->in_use) {
			ut_a(srv_slot_get_type(slot) == SRV_MASTER);

			if (slot->suspended) {

				slot->suspended = FALSE;

				++srv_sys->n_threads_active[SRV_MASTER];
2537

2538 2539 2540
				os_event_set(slot->event);
			}
		}
2541

2542
		srv_sys_mutex_exit();
2543 2544 2545
	}
}

Sergei Golubchik's avatar
Sergei Golubchik committed
2546 2547 2548 2549
/*******************************************************************//**
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
2550 2551
(we do not protect our check with the srv_sys_t:mutex and the
purge_sys->latch, for performance reasons). */
Sergei Golubchik's avatar
Sergei Golubchik committed
2552 2553 2554 2555 2556
UNIV_INTERN
void
srv_wake_purge_thread_if_not_active(void)
/*=====================================*/
{
2557
	ut_ad(!srv_sys_mutex_own());
Sergei Golubchik's avatar
Sergei Golubchik committed
2558

2559 2560
	if (purge_sys->state == PURGE_STATE_RUN
	    && srv_sys->n_threads_active[SRV_PURGE] == 0) {
Sergei Golubchik's avatar
Sergei Golubchik committed
2561

2562
		srv_release_threads(SRV_PURGE, 1);
Sergei Golubchik's avatar
Sergei Golubchik committed
2563 2564 2565
	}
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2566
/*******************************************************************//**
2567 2568 2569 2570 2571 2572
Wakes up the master thread if it is suspended or being suspended. */
UNIV_INTERN
void
srv_wake_master_thread(void)
/*========================*/
{
2573
	ut_ad(!srv_sys_mutex_own());
2574

2575
	srv_inc_activity_count();
2576 2577 2578 2579

	srv_release_threads(SRV_MASTER, 1);
}

Sergei Golubchik's avatar
Sergei Golubchik committed
2580
/*******************************************************************//**
2581 2582 2583
Get current server activity count. We don't hold srv_sys::mutex while
reading this value as it is only used in heuristics.
@return activity count. */
Sergei Golubchik's avatar
Sergei Golubchik committed
2584
UNIV_INTERN
2585 2586 2587
ulint
srv_get_activity_count(void)
/*========================*/
Sergei Golubchik's avatar
Sergei Golubchik committed
2588
{
2589 2590
	return(srv_sys->activity_count);
}
Sergei Golubchik's avatar
Sergei Golubchik committed
2591

2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
/*******************************************************************//**
Check if there has been any activity.
@return FALSE if no change in activity counter. */
UNIV_INTERN
ibool
srv_check_activity(
/*===============*/
	ulint		old_activity_count)	/*!< in: old activity count */
{
	return(srv_sys->activity_count != old_activity_count);
Sergei Golubchik's avatar
Sergei Golubchik committed
2602 2603
}

2604
/********************************************************************//**
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
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";
2617 2618
	if (difftime(current_time, srv_last_log_flush_time)
	    >= srv_flush_log_at_timeout) {
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2619 2620 2621 2622 2623 2624
		log_buffer_sync_in_background(TRUE);
		srv_last_log_flush_time = current_time;
		srv_log_writes_and_flush++;
	}
}

2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 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 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778
/********************************************************************//**
Make room in the table cache by evicting an unused table.
@return number of tables evicted. */
static
ulint
srv_master_evict_from_table_cache(
/*==============================*/
	ulint	pct_check)	/*!< in: max percent to check */
{
	ulint	n_tables_evicted = 0;

	rw_lock_x_lock(&dict_operation_lock);

	dict_mutex_enter_for_mysql();

	n_tables_evicted = dict_make_room_in_cache(
		innobase_get_table_cache_size(), pct_check);

	dict_mutex_exit_for_mysql();

	rw_lock_x_unlock(&dict_operation_lock);

	return(n_tables_evicted);
}

/*********************************************************************//**
This function prints progress message every 60 seconds during server
shutdown, for any activities that master thread is pending on. */
static
void
srv_shutdown_print_master_pending(
/*==============================*/
	ib_time_t*	last_print_time,	/*!< last time the function
						print the message */
	ulint		n_tables_to_drop,	/*!< number of tables to
						be dropped */
	ulint		n_bytes_merged)		/*!< number of change buffer
						just merged */
{
	ib_time_t	current_time;
	double		time_elapsed;

	current_time = ut_time();
	time_elapsed = ut_difftime(current_time, *last_print_time);

	if (time_elapsed > 60) {
		*last_print_time = ut_time();

		if (n_tables_to_drop) {
			ut_print_timestamp(stderr);
			fprintf(stderr, "  InnoDB: Waiting for "
				"%lu table(s) to be dropped\n",
				(ulong) n_tables_to_drop);
		}

		/* Check change buffer merge, we only wait for change buffer
		merge if it is a slow shutdown */
		if (!srv_fast_shutdown && n_bytes_merged) {
			ut_print_timestamp(stderr);
			fprintf(stderr, "  InnoDB: Waiting for change "
				"buffer merge to complete\n"
				"  InnoDB: number of bytes of change buffer "
				"just merged:  %lu\n",
				n_bytes_merged);
		}
	}
}

/*********************************************************************//**
Perform the tasks that the master thread is supposed to do when the
server is active. There are two types of tasks. The first category is
of such tasks which are performed at each inovcation of this function.
We assume that this function is called roughly every second when the
server is active. The second category is of such tasks which are
performed at some interval e.g.: purge, dict_LRU cleanup etc. */
static
void
srv_master_do_active_tasks(void)
/*============================*/
{
	ib_time_t	cur_time = ut_time();
	ullint		counter_time = ut_time_us(NULL);

	/* First do the tasks that we are suppose to do at each
	invocation of this function. */

	++srv_main_active_loops;

	MONITOR_INC(MONITOR_MASTER_ACTIVE_LOOPS);

	/* 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();
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND, counter_time);

	if (srv_shutdown_state > 0) {
		return;
	}

	/* make sure that there is enough reusable space in the redo
	log files */
	srv_main_thread_op_info = "checking free log space";
	log_free_check();

	/* Do an ibuf merge */
	srv_main_thread_op_info = "doing insert buffer merge";
	counter_time = ut_time_us(NULL);
	ibuf_contract_in_background(0, FALSE);
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time);

	/* Flush logs if needed */
	srv_main_thread_op_info = "flushing log";
	srv_sync_log_buffer_in_background();
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_LOG_FLUSH_MICROSECOND, counter_time);

	/* Now see if various tasks that are performed at defined
	intervals need to be performed. */

#ifdef MEM_PERIODIC_CHECK
	/* Check magic numbers of every allocated mem block once in
	SRV_MASTER_MEM_VALIDATE_INTERVAL seconds */
	if (cur_time % SRV_MASTER_MEM_VALIDATE_INTERVAL == 0) {
		mem_validate_all_blocks();
		MONITOR_INC_TIME_IN_MICRO_SECS(
			MONITOR_SRV_MEM_VALIDATE_MICROSECOND, counter_time);
	}
#endif
	if (srv_shutdown_state > 0) {
		return;
	}

	if (srv_shutdown_state > 0) {
		return;
	}

	if (cur_time % SRV_MASTER_DICT_LRU_INTERVAL == 0) {
		srv_main_thread_op_info = "enforcing dict cache limit";
		srv_master_evict_from_table_cache(50);
		MONITOR_INC_TIME_IN_MICRO_SECS(
			MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time);
	}

	if (srv_shutdown_state > 0) {
		return;
	}

	/* Make a new checkpoint */
	if (cur_time % SRV_MASTER_CHECKPOINT_INTERVAL == 0) {
		srv_main_thread_op_info = "making checkpoint";
2779
		log_checkpoint(TRUE, FALSE, TRUE);
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
		MONITOR_INC_TIME_IN_MICRO_SECS(
			MONITOR_SRV_CHECKPOINT_MICROSECOND, counter_time);
	}
}

/*********************************************************************//**
Perform the tasks that the master thread is supposed to do whenever the
server is idle. We do check for the server state during this function
and if the server has entered the shutdown phase we may return from
the function without completing the required tasks.
Note that the server can move to active state when we are executing this
function but we don't check for that as we are suppose to perform more
or less same tasks when server is active. */
static
void
srv_master_do_idle_tasks(void)
/*==========================*/
{
	ullint	counter_time;

	++srv_main_idle_loops;

	MONITOR_INC(MONITOR_MASTER_IDLE_LOOPS);


	/* ALTER TABLE in MySQL requires on Unix that the table handler
	can drop tables lazily after there no longer are SELECT
	queries to them. */
	counter_time = ut_time_us(NULL);
	srv_main_thread_op_info = "doing background drop tables";
	row_drop_tables_for_mysql_in_background();
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND,
			 counter_time);

	if (srv_shutdown_state > 0) {
		return;
	}

	/* make sure that there is enough reusable space in the redo
	log files */
	srv_main_thread_op_info = "checking free log space";
	log_free_check();

	/* Do an ibuf merge */
	counter_time = ut_time_us(NULL);
	srv_main_thread_op_info = "doing insert buffer merge";
	ibuf_contract_in_background(0, TRUE);
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time);

	if (srv_shutdown_state > 0) {
		return;
	}

	srv_main_thread_op_info = "enforcing dict cache limit";
	srv_master_evict_from_table_cache(100);
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time);

	/* Flush logs if needed */
	srv_sync_log_buffer_in_background();
	MONITOR_INC_TIME_IN_MICRO_SECS(
		MONITOR_SRV_LOG_FLUSH_MICROSECOND, counter_time);

	if (srv_shutdown_state > 0) {
		return;
	}

	/* Make a new checkpoint */
	srv_main_thread_op_info = "making checkpoint";
2851
	log_checkpoint(TRUE, FALSE, TRUE);
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
	MONITOR_INC_TIME_IN_MICRO_SECS(MONITOR_SRV_CHECKPOINT_MICROSECOND,
				       counter_time);

	if (srv_shutdown_state > 0) {
		return;
	}

	if (srv_log_arch_expire_sec) {
		srv_main_thread_op_info = "purging archived logs";
		purge_archived_logs(ut_time() - srv_log_arch_expire_sec,
				0);
	}
}

/*********************************************************************//**
Perform the tasks during shutdown. The tasks that we do at shutdown
depend on srv_fast_shutdown:
2 => very fast shutdown => do no book keeping
1 => normal shutdown => clear drop table queue and make checkpoint
0 => slow shutdown => in addition to above do complete purge and ibuf
merge
@return TRUE if some work was done. FALSE otherwise */
static
ibool
srv_master_do_shutdown_tasks(
/*=========================*/
	ib_time_t*	last_print_time)/*!< last time the function
					print the message */
{
	ulint		n_bytes_merged = 0;
	ulint		n_tables_to_drop = 0;

	ut_ad(!srv_read_only_mode);

	++srv_main_shutdown_loops;

	ut_a(srv_shutdown_state > 0);

	/* In very fast shutdown none of the following is necessary */
	if (srv_fast_shutdown == 2) {
		return(FALSE);
	}

	/* 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";
	n_tables_to_drop = row_drop_tables_for_mysql_in_background();

	/* make sure that there is enough reusable space in the redo
	log files */
	srv_main_thread_op_info = "checking free log space";
	log_free_check();

	/* In case of normal shutdown we don't do ibuf merge or purge */
	if (srv_fast_shutdown == 1) {
		goto func_exit;
	}

	/* Do an ibuf merge */
	srv_main_thread_op_info = "doing insert buffer merge";
	n_bytes_merged = ibuf_contract_in_background(0, TRUE);

	/* Flush logs if needed */
	srv_sync_log_buffer_in_background();

func_exit:
	/* Make a new checkpoint about once in 10 seconds */
	srv_main_thread_op_info = "making checkpoint";
2921
	log_checkpoint(TRUE, FALSE, FALSE);
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935

	/* Print progress message every 60 seconds during shutdown */
	if (srv_shutdown_state > 0 && srv_print_verbose_log) {
		srv_shutdown_print_master_pending(
			last_print_time, n_tables_to_drop, n_bytes_merged);
	}

	return(n_bytes_merged || n_tables_to_drop);
}

/*********************************************************************//**
Puts master thread to sleep. At this point we are using polling to
service various activities. Master thread sleeps for one second before
checking the state of the server again */
Sergei Golubchik's avatar
Sergei Golubchik committed
2936 2937
static
void
2938 2939
srv_master_sleep(void)
/*==================*/
Sergei Golubchik's avatar
Sergei Golubchik committed
2940
{
2941 2942 2943
	srv_main_thread_op_info = "sleeping";
	os_thread_sleep(1000000);
	srv_main_thread_op_info = "";
Sergei Golubchik's avatar
Sergei Golubchik committed
2944 2945
}

Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2946 2947 2948
/*********************************************************************//**
The master thread controlling the server.
@return	a dummy parameter */
2949
extern "C" UNIV_INTERN
2950
os_thread_ret_t
2951 2952
DECLARE_THREAD(srv_master_thread)(
/*==============================*/
2953
	void*	arg __attribute__((unused)))
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2954
			/*!< in: a dummy parameter required by
2955 2956
			os_thread_create */
{
Sergei Golubchik's avatar
Sergei Golubchik committed
2957
	srv_slot_t*	slot;
2958 2959
	ulint		old_activity_count = srv_get_activity_count();
	ib_time_t	last_print_time;
2960

2961
	ut_ad(!srv_read_only_mode);
Vadim Tkachenko's avatar
Vadim Tkachenko committed
2962

2963 2964 2965
	srv_master_tid = os_thread_get_tid();

	os_thread_set_priority(srv_master_tid, srv_sched_priority_master);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
2966

2967 2968 2969
#ifdef UNIV_DEBUG_THREAD_CREATION
	fprintf(stderr, "Master thread starts, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
2970
#endif /* UNIV_DEBUG_THREAD_CREATION */
Sergei Golubchik's avatar
Sergei Golubchik committed
2971 2972 2973

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_master_thread_key);
2974
#endif /* UNIV_PFS_THREAD */
Sergei Golubchik's avatar
Sergei Golubchik committed
2975

2976 2977 2978
	srv_main_thread_process_no = os_proc_get_number();
	srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());

2979 2980
	slot = srv_reserve_slot(SRV_MASTER);
	ut_a(slot == srv_sys->sys_threads);
Sergei Golubchik's avatar
Sergei Golubchik committed
2981 2982

	last_print_time = ut_time();
2983 2984 2985 2986 2987
loop:
	if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
		goto suspend_thread;
	}

2988
	while (srv_shutdown_state == SRV_SHUTDOWN_NONE) {
2989

2990
		srv_master_sleep();
2991

2992
		MONITOR_INC(MONITOR_MASTER_THREAD_SLEEP);
2993

2994
		srv_current_thread_priority = srv_master_thread_priority;
2995

2996 2997 2998 2999 3000
		if (srv_check_activity(old_activity_count)) {
			old_activity_count = srv_get_activity_count();
			srv_master_do_active_tasks();
		} else {
			srv_master_do_idle_tasks();
3001
		}
3002
	}
Sergei Golubchik's avatar
Sergei Golubchik committed
3003

3004
	while (srv_master_do_shutdown_tasks(&last_print_time)) {
Sergei Golubchik's avatar
Sergei Golubchik committed
3005

3006 3007 3008
		/* Shouldn't loop here in case of very fast shutdown */
		ut_ad(srv_fast_shutdown < 2);
	}
Sergei Golubchik's avatar
Sergei Golubchik committed
3009

3010 3011
suspend_thread:
	srv_main_thread_op_info = "suspending";
Sergei Golubchik's avatar
Sergei Golubchik committed
3012

3013
	srv_suspend_thread(slot);
Sergei Golubchik's avatar
Sergei Golubchik committed
3014

3015 3016 3017 3018 3019
	/* 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. */
	srv_main_thread_op_info = "waiting for server activity";
Sergei Golubchik's avatar
Sergei Golubchik committed
3020

3021
	os_event_wait(slot->event);
Sergei Golubchik's avatar
Sergei Golubchik committed
3022

3023 3024 3025
	if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
		os_thread_exit(NULL);
	}
3026

3027
	goto loop;
Sergei Golubchik's avatar
Sergei Golubchik committed
3028

3029 3030
	OS_THREAD_DUMMY_RETURN;	/* Not reached, avoid compiler warning */
}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3031

3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
/*********************************************************************//**
Check if purge should stop.
@return true if it should shutdown. */
static
bool
srv_purge_should_exit(
/*==============*/
	ulint		n_purged)	/*!< in: pages purged in last batch */
{
	switch (srv_shutdown_state) {
	case SRV_SHUTDOWN_NONE:
		/* Normal operation. */
		break;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3045

3046 3047 3048 3049
	case SRV_SHUTDOWN_CLEANUP:
	case SRV_SHUTDOWN_EXIT_THREADS:
		/* Exit unless slow shutdown requested or all done. */
		return(srv_fast_shutdown != 0 || n_purged == 0);
3050

3051 3052 3053 3054
	case SRV_SHUTDOWN_LAST_PHASE:
	case SRV_SHUTDOWN_FLUSH_PHASE:
		ut_error;
	}
3055

3056 3057
	return(false);
}
3058

3059 3060 3061 3062 3063 3064 3065 3066 3067
/*********************************************************************//**
Fetch and execute a task from the work queue.
@return	true if a task was executed */
static
bool
srv_task_execute(void)
/*==================*/
{
	que_thr_t*	thr = NULL;
3068

3069 3070
	ut_ad(!srv_read_only_mode);
	ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
3071

3072
	mutex_enter(&srv_sys->tasks_mutex);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3073

3074
	if (UT_LIST_GET_LEN(srv_sys->tasks) > 0) {
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3075

3076
		thr = UT_LIST_GET_FIRST(srv_sys->tasks);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3077

3078
		ut_a(que_node_get_type(thr->child) == QUE_NODE_PURGE);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3079

3080 3081
		UT_LIST_REMOVE(queue, srv_sys->tasks, thr);
	}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3082

3083
	mutex_exit(&srv_sys->tasks_mutex);
3084

3085
	if (thr != NULL) {
3086

3087
		que_run_threads(thr);
3088

3089 3090
		os_atomic_inc_ulint(
			&purge_sys->bh_mutex, &purge_sys->n_completed, 1);
3091

3092 3093
		srv_inc_activity_count();
	}
3094

3095 3096
	return(thr != NULL);
}
3097

3098
static ulint purge_tid_i = 0;
3099

3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111
/*********************************************************************//**
Worker thread that reads tasks from the work queue and executes them.
@return	a dummy parameter */
extern "C" UNIV_INTERN
os_thread_ret_t
DECLARE_THREAD(srv_worker_thread)(
/*==============================*/
	void*	arg __attribute__((unused)))	/*!< in: a dummy parameter
						required by os_thread_create */
{
	srv_slot_t*	slot;
	ulint		tid_i = os_atomic_increment_ulint(&purge_tid_i, 1);
3112

3113 3114 3115
	ut_ad(tid_i < srv_n_purge_threads);
	ut_ad(!srv_read_only_mode);
	ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
3116

3117 3118 3119
	srv_purge_tids[tid_i] = os_thread_get_tid();
	os_thread_set_priority(srv_purge_tids[tid_i],
			       srv_sched_priority_purge);
3120

3121 3122 3123 3124 3125
#ifdef UNIV_DEBUG_THREAD_CREATION
	ut_print_timestamp(stderr);
	fprintf(stderr, " InnoDB: worker thread starting, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
#endif /* UNIV_DEBUG_THREAD_CREATION */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3126

3127
	slot = srv_reserve_slot(SRV_WORKER);
3128

3129
	ut_a(srv_n_purge_threads > 1);
3130

3131
	srv_sys_mutex_enter();
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3132

3133
	ut_a(srv_sys->n_threads_active[SRV_WORKER] < srv_n_purge_threads);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3134

3135
	srv_sys_mutex_exit();
3136

3137 3138 3139
	/* We need to ensure that the worker threads exit after the
	purge coordinator thread. Otherwise the purge coordinaor can
	end up waiting forever in trx_purge_wait_for_workers_to_complete() */
3140

3141 3142
	do {
		srv_suspend_thread(slot);
3143

3144
		os_event_wait(slot->event);
3145

3146
		srv_current_thread_priority = srv_purge_thread_priority;
Sergei Golubchik's avatar
Sergei Golubchik committed
3147

3148
		if (srv_task_execute()) {
3149

3150 3151
			/* If there are tasks in the queue, wakeup
			the purge coordinator thread. */
3152

3153
			srv_wake_purge_thread_if_not_active();
3154 3155
		}

3156 3157 3158
		/* Note: we are checking the state without holding the
		purge_sys->latch here. */
	} while (purge_sys->state != PURGE_STATE_EXIT);
3159

3160
	srv_free_slot(slot);
3161

3162
	rw_lock_x_lock(&purge_sys->latch);
3163

3164 3165 3166
	ut_a(!purge_sys->running);
	ut_a(purge_sys->state == PURGE_STATE_EXIT);
	ut_a(srv_shutdown_state > SRV_SHUTDOWN_NONE);
3167

3168
	rw_lock_x_unlock(&purge_sys->latch);
3169

3170 3171 3172 3173 3174
#ifdef UNIV_DEBUG_THREAD_CREATION
	ut_print_timestamp(stderr);
	fprintf(stderr, " InnoDB: Purge worker thread exiting, id %lu\n",
		os_thread_pf(os_thread_get_curr_id()));
#endif /* UNIV_DEBUG_THREAD_CREATION */
3175

3176 3177 3178
	/* 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);
3179

3180 3181
	OS_THREAD_DUMMY_RETURN;	/* Not reached, avoid compiler warning */
}
3182

3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
/*********************************************************************//**
Do the actual purge operation.
@return length of history list before the last purge batch. */
static
ulint
srv_do_purge(
/*=========*/
	ulint		n_threads,	/*!< in: number of threads to use */
	ulint*		n_total_purged)	/*!< in/out: total pages purged */
{
	ulint		n_pages_purged;
3194

3195 3196 3197 3198
	static ulint	count = 0;
	static ulint	n_use_threads = 0;
	static ulint	rseg_history_len = 0;
	ulint		old_activity_count = srv_get_activity_count();
3199

3200 3201
	ut_a(n_threads > 0);
	ut_ad(!srv_read_only_mode);
3202

3203 3204 3205 3206 3207
	/* Purge until there are no more records to purge and there is
	no change in configuration or server state. If the user has
	configured more than one purge thread then we treat that as a
	pool of threads and only use the extra threads if purge can't
	keep up with updates. */
3208

3209 3210
	if (n_use_threads == 0) {
		n_use_threads = n_threads;
3211 3212
	}

3213 3214
	do {
		srv_current_thread_priority = srv_purge_thread_priority;
3215

3216 3217 3218
		if (trx_sys->rseg_history_len > rseg_history_len
		    || (srv_max_purge_lag > 0
			&& rseg_history_len > srv_max_purge_lag)) {
3219

3220 3221
			/* History length is now longer than what it was
			when we took the last snapshot. Use more threads. */
3222

3223 3224 3225
			if (n_use_threads < n_threads) {
				++n_use_threads;
			}
3226

3227 3228
		} else if (srv_check_activity(old_activity_count)
			   && n_use_threads > 1) {
3229

3230 3231
			/* History length same or smaller since last snapshot,
			use fewer threads. */
3232

3233
			--n_use_threads;
3234

3235 3236
			old_activity_count = srv_get_activity_count();
		}
3237

3238 3239
		/* Ensure that the purge threads are less than what
		was configured. */
3240

3241 3242
		ut_a(n_use_threads > 0);
		ut_a(n_use_threads <= n_threads);
3243

3244 3245 3246 3247
		/* Take a snapshot of the history list before purge. */
		if ((rseg_history_len = trx_sys->rseg_history_len) == 0) {
			break;
		}
3248

3249 3250
		n_pages_purged = trx_purge(
			n_use_threads, srv_purge_batch_size, false);
3251

3252 3253 3254 3255 3256
		if (!(count++ % TRX_SYS_N_RSEGS)) {
			/* Force a truncate of the history list. */
			n_pages_purged += trx_purge(
				1, srv_purge_batch_size, true);
		}
3257

3258
		*n_total_purged += n_pages_purged;
3259

3260
	} while (!srv_purge_should_exit(n_pages_purged) && n_pages_purged > 0);
3261

3262 3263
	return(rseg_history_len);
}
3264

3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
/*********************************************************************//**
Suspend the purge coordinator thread. */
static
void
srv_purge_coordinator_suspend(
/*==========================*/
	srv_slot_t*	slot,			/*!< in/out: Purge coordinator
						thread slot */
	ulint		rseg_history_len)	/*!< in: history list length
						before last purge */
{
	ut_ad(!srv_read_only_mode);
	ut_a(slot->type == SRV_PURGE);
3278

3279
	bool		stop = false;
3280

3281 3282
	/** Maximum wait time on the purge event, in micro-seconds. */
	static const ulint SRV_PURGE_MAX_TIMEOUT = 10000;
3283

3284
	ib_int64_t	sig_count = srv_suspend_thread(slot);
3285

3286 3287
	do {
		ulint		ret;
3288

3289
		rw_lock_x_lock(&purge_sys->latch);
3290

3291
		purge_sys->running = false;
3292

3293
		rw_lock_x_unlock(&purge_sys->latch);
3294

3295 3296
		/* We don't wait right away on the the non-timed wait because
		we want to signal the thread that wants to suspend purge. */
3297

3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309
		if (stop) {
			os_event_wait_low(slot->event, sig_count);
			ret = 0;
		} else if (rseg_history_len <= trx_sys->rseg_history_len) {
			ret = os_event_wait_time_low(
				slot->event, SRV_PURGE_MAX_TIMEOUT, sig_count);
		} else {
			/* We don't want to waste time waiting, if the
			history list increased by the time we got here,
			unless purge has been stopped. */
			ret = 0;
		}
3310

3311
		srv_sys_mutex_enter();
3312

3313 3314
		/* The thread can be in state !suspended after the timeout
		but before this check if another thread sent a wakeup signal. */
3315

3316 3317 3318 3319 3320
		if (slot->suspended) {
			slot->suspended = FALSE;
			++srv_sys->n_threads_active[slot->type];
			ut_a(srv_sys->n_threads_active[slot->type] == 1);
		}
3321

3322
		srv_sys_mutex_exit();
3323

3324
		sig_count = srv_suspend_thread(slot);
Sergei Golubchik's avatar
Sergei Golubchik committed
3325

3326
		rw_lock_x_lock(&purge_sys->latch);
3327

3328 3329
		stop = (srv_shutdown_state == SRV_SHUTDOWN_NONE
			&& purge_sys->state == PURGE_STATE_STOP);
3330

3331 3332 3333 3334 3335
		if (!stop) {
			ut_a(purge_sys->n_stop == 0);
			purge_sys->running = true;
		} else {
			ut_a(purge_sys->n_stop > 0);
3336

3337 3338
			/* Signal that we are suspended. */
			os_event_set(purge_sys->event);
3339 3340
		}

3341
		rw_lock_x_unlock(&purge_sys->latch);
3342

3343
		if (ret == OS_SYNC_TIME_EXCEEDED) {
3344

3345 3346 3347 3348 3349
			/* No new records added since wait started then simply
			wait for new records. The magic number 5000 is an
			approximation for the case where we have cached UNDO
			log records which prevent truncate of the UNDO
			segments. */
3350

3351 3352
			if (rseg_history_len == trx_sys->rseg_history_len
			    && trx_sys->rseg_history_len < 5000) {
3353

3354 3355 3356
				stop = true;
			}
		}
3357

3358
	} while (stop);
3359

3360
	srv_sys_mutex_enter();
3361

3362 3363 3364 3365
	if (slot->suspended) {
		slot->suspended = FALSE;
		++srv_sys->n_threads_active[slot->type];
		ut_a(srv_sys->n_threads_active[slot->type] == 1);
3366 3367
	}

3368
	srv_sys_mutex_exit();
3369
}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3370

Sergei Golubchik's avatar
Sergei Golubchik committed
3371
/*********************************************************************//**
3372
Purge coordinator thread that schedules the purge tasks.
Sergei Golubchik's avatar
Sergei Golubchik committed
3373
@return	a dummy parameter */
3374
extern "C" UNIV_INTERN
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3375
os_thread_ret_t
3376 3377
DECLARE_THREAD(srv_purge_coordinator_thread)(
/*=========================================*/
Sergei Golubchik's avatar
Sergei Golubchik committed
3378 3379
	void*	arg __attribute__((unused)))	/*!< in: a dummy parameter
						required by os_thread_create */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3380
{
Sergei Golubchik's avatar
Sergei Golubchik committed
3381
	srv_slot_t*	slot;
3382 3383 3384 3385 3386 3387 3388 3389 3390
	ulint           n_total_purged = ULINT_UNDEFINED;

	ut_ad(!srv_read_only_mode);
	ut_a(srv_n_purge_threads >= 1);
	ut_a(trx_purge_state() == PURGE_STATE_INIT);
	ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);

	srv_purge_tids[0] = os_thread_get_tid();
	os_thread_set_priority(srv_purge_tids[0], srv_sched_priority_purge);
Sergei Golubchik's avatar
Sergei Golubchik committed
3391

3392 3393 3394 3395 3396 3397
	rw_lock_x_lock(&purge_sys->latch);

	purge_sys->running = true;
	purge_sys->state = PURGE_STATE_RUN;

	rw_lock_x_unlock(&purge_sys->latch);
Sergei Golubchik's avatar
Sergei Golubchik committed
3398 3399 3400 3401

#ifdef UNIV_PFS_THREAD
	pfs_register_thread(srv_purge_thread_key);
#endif /* UNIV_PFS_THREAD */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3402 3403

#ifdef UNIV_DEBUG_THREAD_CREATION
3404 3405
	ut_print_timestamp(stderr);
	fprintf(stderr, " InnoDB: Purge coordinator thread created, id %lu\n",
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3406
		os_thread_pf(os_thread_get_curr_id()));
Sergei Golubchik's avatar
Sergei Golubchik committed
3407
#endif /* UNIV_DEBUG_THREAD_CREATION */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3408

3409
	slot = srv_reserve_slot(SRV_PURGE);
Sergei Golubchik's avatar
Sergei Golubchik committed
3410

3411
	ulint	rseg_history_len = trx_sys->rseg_history_len;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3412

3413 3414 3415
	do {
		/* If there are no records to purge or the last
		purge didn't purge any records then wait for activity. */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3416

3417 3418 3419
		if (srv_shutdown_state == SRV_SHUTDOWN_NONE
		    && (purge_sys->state == PURGE_STATE_STOP
			|| n_total_purged == 0)) {
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3420

3421 3422
			srv_purge_coordinator_suspend(slot, rseg_history_len);
		}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3423

3424 3425 3426 3427
		if (srv_purge_should_exit(n_total_purged)) {
			ut_a(!slot->suspended);
			break;
		}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3428

3429
		n_total_purged = 0;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3430

3431
		srv_current_thread_priority = srv_purge_thread_priority;
Sergei Golubchik's avatar
Sergei Golubchik committed
3432

3433 3434
		rseg_history_len = srv_do_purge(
			srv_n_purge_threads, &n_total_purged);
Sergei Golubchik's avatar
Sergei Golubchik committed
3435

3436
		srv_inc_activity_count();
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3437

3438
	} while (!srv_purge_should_exit(n_total_purged));
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3439

3440 3441
	/* Ensure that we don't jump out of the loop unless the
	exit condition is satisfied. */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3442

3443
	ut_a(srv_purge_should_exit(n_total_purged));
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3444

3445
	ulint	n_pages_purged = ULINT_MAX;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3446

3447 3448 3449 3450 3451 3452
	/* Ensure that all records are purged if it is not a fast shutdown.
	This covers the case where a record can be added after we exit the
	loop above. */
	while (srv_fast_shutdown == 0 && n_pages_purged > 0) {
		n_pages_purged = trx_purge(1, srv_purge_batch_size, false);
	}
Sergei Golubchik's avatar
Sergei Golubchik committed
3453

3454 3455 3456
	/* Force a truncate of the history list. */
	n_pages_purged = trx_purge(1, srv_purge_batch_size, true);
	ut_a(n_pages_purged == 0 || srv_fast_shutdown != 0);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3457

3458 3459 3460
	/* The task queue should always be empty, independent of fast
	shutdown state. */
	ut_a(srv_get_task_queue_length() == 0);
Sergei Golubchik's avatar
Sergei Golubchik committed
3461

3462
	srv_free_slot(slot);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3463

3464 3465
	/* Note that we are shutting down. */
	rw_lock_x_lock(&purge_sys->latch);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3466

3467
	purge_sys->state = PURGE_STATE_EXIT;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3468

3469
	purge_sys->running = false;
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3470

3471
	rw_lock_x_unlock(&purge_sys->latch);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3472 3473

#ifdef UNIV_DEBUG_THREAD_CREATION
3474 3475
	ut_print_timestamp(stderr);
	fprintf(stderr, " InnoDB: Purge coordinator exiting, id %lu\n",
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3476
		os_thread_pf(os_thread_get_curr_id()));
Sergei Golubchik's avatar
Sergei Golubchik committed
3477
#endif /* UNIV_DEBUG_THREAD_CREATION */
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3478

3479 3480 3481 3482 3483
	/* Ensure that all the worker threads quit. */
	if (srv_n_purge_threads > 1) {
		srv_release_threads(SRV_WORKER, srv_n_purge_threads - 1);
	}

Sergei Golubchik's avatar
Sergei Golubchik committed
3484 3485 3486
	/* 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);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3487

Sergei Golubchik's avatar
Sergei Golubchik committed
3488 3489
	OS_THREAD_DUMMY_RETURN;	/* Not reached, avoid compiler warning */
}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3490

Sergei Golubchik's avatar
Sergei Golubchik committed
3491 3492 3493 3494 3495 3496 3497 3498 3499
/**********************************************************************//**
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 */
{
3500 3501
	ut_ad(!srv_read_only_mode);
	mutex_enter(&srv_sys->tasks_mutex);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3502

Sergei Golubchik's avatar
Sergei Golubchik committed
3503
	UT_LIST_ADD_LAST(queue, srv_sys->tasks, thr);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3504

3505 3506
	mutex_exit(&srv_sys->tasks_mutex);

Sergei Golubchik's avatar
Sergei Golubchik committed
3507
	srv_release_threads(SRV_WORKER, 1);
3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
}

/**********************************************************************//**
Get count of tasks in the queue.
@return number of tasks in queue  */
UNIV_INTERN
ulint
srv_get_task_queue_length(void)
/*===========================*/
{
	ulint	n_tasks;

	ut_ad(!srv_read_only_mode);

	mutex_enter(&srv_sys->tasks_mutex);
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3523

3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549
	n_tasks = UT_LIST_GET_LEN(srv_sys->tasks);

	mutex_exit(&srv_sys->tasks_mutex);

	return(n_tasks);
}

/**********************************************************************//**
Wakeup the purge threads. */
UNIV_INTERN
void
srv_purge_wakeup(void)
/*==================*/
{
	ut_ad(!srv_read_only_mode);

	if (srv_force_recovery < SRV_FORCE_NO_BACKGROUND) {

		srv_release_threads(SRV_PURGE, 1);

		if (srv_n_purge_threads > 1) {
			ulint	n_workers = srv_n_purge_threads - 1;

			srv_release_threads(SRV_WORKER, n_workers);
		}
	}
Aleksandr Kuzminsky's avatar
Aleksandr Kuzminsky committed
3550
}
3551