You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2890 lines
82 KiB

10 years ago
10 years ago
10 years ago
12 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
12 years ago
12 years ago
10 years ago
  1. /*****************************************************************************
  2. Copyright (c) 1995, 2016, Oracle and/or its affiliates. All Rights Reserved.
  3. Copyright (c) 2008, 2009 Google Inc.
  4. Copyright (c) 2009, Percona Inc.
  5. Portions of this file contain modifications contributed and copyrighted by
  6. Google, Inc. Those modifications are gratefully acknowledged and are described
  7. briefly in the InnoDB documentation. The contributions by Google are
  8. incorporated with their permission, and subject to the conditions contained in
  9. the file COPYING.Google.
  10. Portions of this file contain modifications contributed and copyrighted
  11. by Percona Inc.. Those modifications are
  12. gratefully acknowledged and are described briefly in the InnoDB
  13. documentation. The contributions by Percona Inc. are incorporated with
  14. their permission, and subject to the conditions contained in the file
  15. COPYING.Percona.
  16. This program is free software; you can redistribute it and/or modify it under
  17. the terms of the GNU General Public License as published by the Free Software
  18. Foundation; version 2 of the License.
  19. This program is distributed in the hope that it will be useful, but WITHOUT
  20. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  21. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  22. You should have received a copy of the GNU General Public License along with
  23. this program; if not, write to the Free Software Foundation, Inc.,
  24. 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
  25. *****************************************************************************/
  26. /**************************************************//**
  27. @file srv/srv0srv.cc
  28. The database server main program
  29. Created 10/8/1995 Heikki Tuuri
  30. *******************************************************/
  31. /* Dummy comment */
  32. #include "srv0srv.h"
  33. #include "ut0mem.h"
  34. #include "ut0ut.h"
  35. #include "os0proc.h"
  36. #include "mem0mem.h"
  37. #include "mem0pool.h"
  38. #include "sync0sync.h"
  39. #include "que0que.h"
  40. #include "log0recv.h"
  41. #include "pars0pars.h"
  42. #include "usr0sess.h"
  43. #include "lock0lock.h"
  44. #include "trx0purge.h"
  45. #include "ibuf0ibuf.h"
  46. #include "buf0flu.h"
  47. #include "buf0lru.h"
  48. #include "btr0sea.h"
  49. #include "dict0load.h"
  50. #include "dict0boot.h"
  51. #include "dict0stats_bg.h" /* dict_stats_event */
  52. #include "srv0start.h"
  53. #include "row0mysql.h"
  54. #include "ha_prototypes.h"
  55. #include "trx0i_s.h"
  56. #include "os0sync.h" /* for HAVE_ATOMIC_BUILTINS */
  57. #include "srv0mon.h"
  58. #include "ut0crc32.h"
  59. #include "mysql/plugin.h"
  60. #include "mysql/service_thd_wait.h"
  61. /* The following is the maximum allowed duration of a lock wait. */
  62. UNIV_INTERN ulint srv_fatal_semaphore_wait_threshold = 600;
  63. /* How much data manipulation language (DML) statements need to be delayed,
  64. in microseconds, in order to reduce the lagging of the purge thread. */
  65. UNIV_INTERN ulint srv_dml_needed_delay = 0;
  66. UNIV_INTERN ibool srv_monitor_active = FALSE;
  67. UNIV_INTERN ibool srv_error_monitor_active = FALSE;
  68. UNIV_INTERN ibool srv_buf_dump_thread_active = FALSE;
  69. UNIV_INTERN ibool srv_dict_stats_thread_active = FALSE;
  70. UNIV_INTERN const char* srv_main_thread_op_info = "";
  71. /** Prefix used by MySQL to indicate pre-5.1 table name encoding */
  72. const char srv_mysql50_table_name_prefix[10] = "#mysql50#";
  73. /* Server parameters which are read from the initfile */
  74. /* The following three are dir paths which are catenated before file
  75. names, where the file name itself may also contain a path */
  76. UNIV_INTERN char* srv_data_home = NULL;
  77. /** Rollback files directory, can be absolute. */
  78. UNIV_INTERN char* srv_undo_dir = NULL;
  79. /** The number of tablespaces to use for rollback segments. */
  80. UNIV_INTERN ulong srv_undo_tablespaces = 8;
  81. /** The number of UNDO tablespaces that are open and ready to use. */
  82. UNIV_INTERN ulint srv_undo_tablespaces_open = 8;
  83. /* The number of rollback segments to use */
  84. UNIV_INTERN ulong srv_undo_logs = 1;
  85. #ifdef UNIV_LOG_ARCHIVE
  86. UNIV_INTERN char* srv_arch_dir = NULL;
  87. #endif /* UNIV_LOG_ARCHIVE */
  88. /** Set if InnoDB must operate in read-only mode. We don't do any
  89. recovery and open all tables in RO mode instead of RW mode. We don't
  90. sync the max trx id to disk either. */
  91. UNIV_INTERN my_bool srv_read_only_mode;
  92. /** store to its own file each table created by an user; data
  93. dictionary tables are in the system tablespace 0 */
  94. UNIV_INTERN my_bool srv_file_per_table;
  95. /** The file format to use on new *.ibd files. */
  96. UNIV_INTERN ulint srv_file_format = 0;
  97. /** Whether to check file format during startup. A value of
  98. UNIV_FORMAT_MAX + 1 means no checking ie. FALSE. The default is to
  99. set it to the highest format we support. */
  100. UNIV_INTERN ulint srv_max_file_format_at_startup = UNIV_FORMAT_MAX;
  101. /** Set if InnoDB operates in read-only mode or innodb-force-recovery
  102. is greater than SRV_FORCE_NO_TRX_UNDO. */
  103. UNIV_INTERN my_bool high_level_read_only;
  104. #if UNIV_FORMAT_A
  105. # error "UNIV_FORMAT_A must be 0!"
  106. #endif
  107. /** Place locks to records only i.e. do not use next-key locking except
  108. on duplicate key checking and foreign key checking */
  109. UNIV_INTERN ibool srv_locks_unsafe_for_binlog = FALSE;
  110. /** Sort buffer size in index creation */
  111. UNIV_INTERN ulong srv_sort_buf_size = 1048576;
  112. /** Maximum modification log file size for online index creation */
  113. UNIV_INTERN unsigned long long srv_online_max_size;
  114. /* If this flag is TRUE, then we will use the native aio of the
  115. OS (provided we compiled Innobase with it in), otherwise we will
  116. use simulated aio we build below with threads.
  117. Currently we support native aio on windows and linux */
  118. UNIV_INTERN my_bool srv_use_native_aio = TRUE;
  119. UNIV_INTERN my_bool srv_numa_interleave = FALSE;
  120. #ifdef __WIN__
  121. /* Windows native condition variables. We use runtime loading / function
  122. pointers, because they are not available on Windows Server 2003 and
  123. Windows XP/2000.
  124. We use condition for events on Windows if possible, even if os_event
  125. resembles Windows kernel event object well API-wise. The reason is
  126. performance, kernel objects are heavyweights and WaitForSingleObject() is a
  127. performance killer causing calling thread to context switch. Besides, Innodb
  128. is preallocating large number (often millions) of os_events. With kernel event
  129. objects it takes a big chunk out of non-paged pool, which is better suited
  130. for tasks like IO than for storing idle event objects. */
  131. UNIV_INTERN ibool srv_use_native_conditions = FALSE;
  132. #endif /* __WIN__ */
  133. UNIV_INTERN ulint srv_n_data_files = 0;
  134. UNIV_INTERN char** srv_data_file_names = NULL;
  135. /* size in database pages */
  136. UNIV_INTERN ulint* srv_data_file_sizes = NULL;
  137. /* if TRUE, then we auto-extend the last data file */
  138. UNIV_INTERN ibool srv_auto_extend_last_data_file = FALSE;
  139. /* if != 0, this tells the max size auto-extending may increase the
  140. last data file size */
  141. UNIV_INTERN ulint srv_last_file_size_max = 0;
  142. /* If the last data file is auto-extended, we add this
  143. many pages to it at a time */
  144. UNIV_INTERN ulong srv_auto_extend_increment = 8;
  145. UNIV_INTERN ulint* srv_data_file_is_raw_partition = NULL;
  146. /* If the following is TRUE we do not allow inserts etc. This protects
  147. the user from forgetting the 'newraw' keyword to my.cnf */
  148. UNIV_INTERN ibool srv_created_new_raw = FALSE;
  149. UNIV_INTERN char* srv_log_group_home_dir = NULL;
  150. UNIV_INTERN ulong srv_n_log_files = SRV_N_LOG_FILES_MAX;
  151. /* size in database pages */
  152. UNIV_INTERN ib_uint64_t srv_log_file_size = IB_UINT64_MAX;
  153. UNIV_INTERN ib_uint64_t srv_log_file_size_requested;
  154. /* size in database pages */
  155. UNIV_INTERN ulint srv_log_buffer_size = ULINT_MAX;
  156. UNIV_INTERN ulong srv_flush_log_at_trx_commit = 1;
  157. UNIV_INTERN uint srv_flush_log_at_timeout = 1;
  158. UNIV_INTERN ulong srv_page_size = UNIV_PAGE_SIZE_DEF;
  159. UNIV_INTERN ulong srv_page_size_shift = UNIV_PAGE_SIZE_SHIFT_DEF;
  160. /* Try to flush dirty pages so as to avoid IO bursts at
  161. the checkpoints. */
  162. UNIV_INTERN char srv_adaptive_flushing = TRUE;
  163. /** Maximum number of times allowed to conditionally acquire
  164. mutex before switching to blocking wait on the mutex */
  165. #define MAX_MUTEX_NOWAIT 20
  166. /** Check whether the number of failed nonblocking mutex
  167. acquisition attempts exceeds maximum allowed value. If so,
  168. srv_printf_innodb_monitor() will request mutex acquisition
  169. with mutex_enter(), which will wait until it gets the mutex. */
  170. #define MUTEX_NOWAIT(mutex_skipped) ((mutex_skipped) < MAX_MUTEX_NOWAIT)
  171. /** The sort order table of the MySQL latin1_swedish_ci character set
  172. collation */
  173. UNIV_INTERN const byte* srv_latin1_ordering;
  174. /* use os/external memory allocator */
  175. UNIV_INTERN my_bool srv_use_sys_malloc = TRUE;
  176. /* requested size in kilobytes */
  177. UNIV_INTERN ulint srv_buf_pool_size = ULINT_MAX;
  178. /* requested number of buffer pool instances */
  179. UNIV_INTERN ulint srv_buf_pool_instances = 1;
  180. /* number of locks to protect buf_pool->page_hash */
  181. UNIV_INTERN ulong srv_n_page_hash_locks = 16;
  182. /** Scan depth for LRU flush batch i.e.: number of blocks scanned*/
  183. UNIV_INTERN ulong srv_LRU_scan_depth = 1024;
  184. /** whether or not to flush neighbors of a block */
  185. UNIV_INTERN ulong srv_flush_neighbors = 1;
  186. /* previously requested size */
  187. UNIV_INTERN ulint srv_buf_pool_old_size;
  188. /* current size in kilobytes */
  189. UNIV_INTERN ulint srv_buf_pool_curr_size = 0;
  190. /* size in bytes */
  191. UNIV_INTERN ulint srv_mem_pool_size = ULINT_MAX;
  192. UNIV_INTERN ulint srv_lock_table_size = ULINT_MAX;
  193. /* This parameter is deprecated. Use srv_n_io_[read|write]_threads
  194. instead. */
  195. UNIV_INTERN ulint srv_n_file_io_threads = ULINT_MAX;
  196. UNIV_INTERN ulint srv_n_read_io_threads = ULINT_MAX;
  197. UNIV_INTERN ulint srv_n_write_io_threads = ULINT_MAX;
  198. /* Switch to enable random read ahead. */
  199. UNIV_INTERN my_bool srv_random_read_ahead = FALSE;
  200. /* User settable value of the number of pages that must be present
  201. in the buffer cache and accessed sequentially for InnoDB to trigger a
  202. readahead request. */
  203. UNIV_INTERN ulong srv_read_ahead_threshold = 56;
  204. #ifdef UNIV_LOG_ARCHIVE
  205. UNIV_INTERN ibool srv_log_archive_on = FALSE;
  206. UNIV_INTERN ibool srv_archive_recovery = 0;
  207. UNIV_INTERN ib_uint64_t srv_archive_recovery_limit_lsn;
  208. #endif /* UNIV_LOG_ARCHIVE */
  209. /* This parameter is used to throttle the number of insert buffers that are
  210. merged in a batch. By increasing this parameter on a faster disk you can
  211. possibly reduce the number of I/O operations performed to complete the
  212. merge operation. The value of this parameter is used as is by the
  213. background loop when the system is idle (low load), on a busy system
  214. the parameter is scaled down by a factor of 4, this is to avoid putting
  215. a heavier load on the I/O sub system. */
  216. UNIV_INTERN ulong srv_insert_buffer_batch_size = 20;
  217. UNIV_INTERN char* srv_file_flush_method_str = NULL;
  218. UNIV_INTERN ulint srv_unix_file_flush_method = SRV_UNIX_FSYNC;
  219. UNIV_INTERN ulint srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;
  220. UNIV_INTERN ulint srv_max_n_open_files = 300;
  221. /* Number of IO operations per second the server can do */
  222. UNIV_INTERN ulong srv_io_capacity = 200;
  223. UNIV_INTERN ulong srv_max_io_capacity = 400;
  224. /* The InnoDB main thread tries to keep the ratio of modified pages
  225. in the buffer pool to all database pages in the buffer pool smaller than
  226. the following number. But it is not guaranteed that the value stays below
  227. that during a time of heavy update/insert activity. */
  228. UNIV_INTERN ulong srv_max_buf_pool_modified_pct = 75;
  229. UNIV_INTERN ulong srv_max_dirty_pages_pct_lwm = 50;
  230. /* This is the percentage of log capacity at which adaptive flushing,
  231. if enabled, will kick in. */
  232. UNIV_INTERN ulong srv_adaptive_flushing_lwm = 10;
  233. /* Number of iterations over which adaptive flushing is averaged. */
  234. UNIV_INTERN ulong srv_flushing_avg_loops = 30;
  235. /* The number of purge threads to use.*/
  236. UNIV_INTERN ulong srv_n_purge_threads = 1;
  237. /* the number of pages to purge in one batch */
  238. UNIV_INTERN ulong srv_purge_batch_size = 20;
  239. /* Internal setting for "innodb_stats_method". Decides how InnoDB treats
  240. NULL value when collecting statistics. By default, it is set to
  241. SRV_STATS_NULLS_EQUAL(0), ie. all NULL value are treated equal */
  242. UNIV_INTERN ulong srv_innodb_stats_method = SRV_STATS_NULLS_EQUAL;
  243. UNIV_INTERN srv_stats_t srv_stats;
  244. /* structure to pass status variables to MySQL */
  245. UNIV_INTERN export_var_t export_vars;
  246. /** Normally 0. When nonzero, skip some phases of crash recovery,
  247. starting from SRV_FORCE_IGNORE_CORRUPT, so that data can be recovered
  248. by SELECT or mysqldump. When this is nonzero, we do not allow any user
  249. modifications to the data. */
  250. UNIV_INTERN ulong srv_force_recovery;
  251. #ifndef DBUG_OFF
  252. /** Inject a crash at different steps of the recovery process.
  253. This is for testing and debugging only. */
  254. UNIV_INTERN ulong srv_force_recovery_crash;
  255. #endif /* !DBUG_OFF */
  256. /** Print all user-level transactions deadlocks to mysqld stderr */
  257. UNIV_INTERN my_bool srv_print_all_deadlocks = FALSE;
  258. /** Enable INFORMATION_SCHEMA.innodb_cmp_per_index */
  259. UNIV_INTERN my_bool srv_cmp_per_index_enabled = FALSE;
  260. /* If the following is set to 1 then we do not run purge and insert buffer
  261. merge to completion before shutdown. If it is set to 2, do not even flush the
  262. buffer pool to data files at the shutdown: we effectively 'crash'
  263. InnoDB (but lose no committed transactions). */
  264. UNIV_INTERN ulint srv_fast_shutdown = 0;
  265. /* Generate a innodb_status.<pid> file */
  266. UNIV_INTERN ibool srv_innodb_status = FALSE;
  267. /* When estimating number of different key values in an index, sample
  268. this many index pages, there are 2 ways to calculate statistics:
  269. * persistent stats that are calculated by ANALYZE TABLE and saved
  270. in the innodb database.
  271. * quick transient stats, that are used if persistent stats for the given
  272. table/index are not found in the innodb database */
  273. UNIV_INTERN unsigned long long srv_stats_transient_sample_pages = 8;
  274. UNIV_INTERN my_bool srv_stats_persistent = TRUE;
  275. UNIV_INTERN unsigned long long srv_stats_persistent_sample_pages = 20;
  276. UNIV_INTERN my_bool srv_stats_auto_recalc = TRUE;
  277. UNIV_INTERN ibool srv_use_doublewrite_buf = TRUE;
  278. /** doublewrite buffer is 1MB is size i.e.: it can hold 128 16K pages.
  279. The following parameter is the size of the buffer that is used for
  280. batch flushing i.e.: LRU flushing and flush_list flushing. The rest
  281. of the pages are used for single page flushing. */
  282. UNIV_INTERN ulong srv_doublewrite_batch_size = 120;
  283. UNIV_INTERN ulong srv_replication_delay = 0;
  284. /*-------------------------------------------*/
  285. UNIV_INTERN ulong srv_n_spin_wait_rounds = 30;
  286. UNIV_INTERN ulong srv_spin_wait_delay = 6;
  287. UNIV_INTERN ibool srv_priority_boost = TRUE;
  288. #ifdef UNIV_DEBUG
  289. UNIV_INTERN ibool srv_print_thread_releases = FALSE;
  290. UNIV_INTERN ibool srv_print_lock_waits = FALSE;
  291. UNIV_INTERN ibool srv_print_buf_io = FALSE;
  292. UNIV_INTERN ibool srv_print_log_io = FALSE;
  293. UNIV_INTERN ibool srv_print_latch_waits = FALSE;
  294. #endif /* UNIV_DEBUG */
  295. static ulint srv_n_rows_inserted_old = 0;
  296. static ulint srv_n_rows_updated_old = 0;
  297. static ulint srv_n_rows_deleted_old = 0;
  298. static ulint srv_n_rows_read_old = 0;
  299. UNIV_INTERN ulint srv_truncated_status_writes = 0;
  300. UNIV_INTERN ulint srv_available_undo_logs = 0;
  301. /* Set the following to 0 if you want InnoDB to write messages on
  302. stderr on startup/shutdown. */
  303. UNIV_INTERN ibool srv_print_verbose_log = TRUE;
  304. UNIV_INTERN my_bool srv_print_innodb_monitor = FALSE;
  305. UNIV_INTERN my_bool srv_print_innodb_lock_monitor = FALSE;
  306. UNIV_INTERN ibool srv_print_innodb_tablespace_monitor = FALSE;
  307. UNIV_INTERN ibool srv_print_innodb_table_monitor = FALSE;
  308. /* Array of English strings describing the current state of an
  309. i/o handler thread */
  310. UNIV_INTERN const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
  311. UNIV_INTERN const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
  312. UNIV_INTERN time_t srv_last_monitor_time;
  313. UNIV_INTERN ib_mutex_t srv_innodb_monitor_mutex;
  314. /* Mutex for locking srv_monitor_file. Not created if srv_read_only_mode */
  315. UNIV_INTERN ib_mutex_t srv_monitor_file_mutex;
  316. #ifdef UNIV_PFS_MUTEX
  317. # ifndef HAVE_ATOMIC_BUILTINS
  318. /* Key to register server_mutex with performance schema */
  319. UNIV_INTERN mysql_pfs_key_t server_mutex_key;
  320. # endif /* !HAVE_ATOMIC_BUILTINS */
  321. /** Key to register srv_innodb_monitor_mutex with performance schema */
  322. UNIV_INTERN mysql_pfs_key_t srv_innodb_monitor_mutex_key;
  323. /** Key to register srv_monitor_file_mutex with performance schema */
  324. UNIV_INTERN mysql_pfs_key_t srv_monitor_file_mutex_key;
  325. /** Key to register srv_dict_tmpfile_mutex with performance schema */
  326. UNIV_INTERN mysql_pfs_key_t srv_dict_tmpfile_mutex_key;
  327. /** Key to register the mutex with performance schema */
  328. UNIV_INTERN mysql_pfs_key_t srv_misc_tmpfile_mutex_key;
  329. /** Key to register srv_sys_t::mutex with performance schema */
  330. UNIV_INTERN mysql_pfs_key_t srv_sys_mutex_key;
  331. /** Key to register srv_sys_t::tasks_mutex with performance schema */
  332. UNIV_INTERN mysql_pfs_key_t srv_sys_tasks_mutex_key;
  333. #endif /* UNIV_PFS_MUTEX */
  334. /** Temporary file for innodb monitor output */
  335. UNIV_INTERN FILE* srv_monitor_file;
  336. /** Mutex for locking srv_dict_tmpfile. Not created if srv_read_only_mode.
  337. This mutex has a very high rank; threads reserving it should not
  338. be holding any InnoDB latches. */
  339. UNIV_INTERN ib_mutex_t srv_dict_tmpfile_mutex;
  340. /** Temporary file for output from the data dictionary */
  341. UNIV_INTERN FILE* srv_dict_tmpfile;
  342. /** Mutex for locking srv_misc_tmpfile. Not created if srv_read_only_mode.
  343. This mutex has a very low rank; threads reserving it should not
  344. acquire any further latches or sleep before releasing this one. */
  345. UNIV_INTERN ib_mutex_t srv_misc_tmpfile_mutex;
  346. /** Temporary file for miscellanous diagnostic output */
  347. UNIV_INTERN FILE* srv_misc_tmpfile;
  348. UNIV_INTERN ulint srv_main_thread_process_no = 0;
  349. UNIV_INTERN ulint srv_main_thread_id = 0;
  350. /* The following counts are used by the srv_master_thread. */
  351. /** Iterations of the loop bounded by 'srv_active' label. */
  352. static ulint srv_main_active_loops = 0;
  353. /** Iterations of the loop bounded by the 'srv_idle' label. */
  354. static ulint srv_main_idle_loops = 0;
  355. /** Iterations of the loop bounded by the 'srv_shutdown' label. */
  356. static ulint srv_main_shutdown_loops = 0;
  357. /** Log writes involving flush. */
  358. static ulint srv_log_writes_and_flush = 0;
  359. /* This is only ever touched by the master thread. It records the
  360. time when the last flush of log file has happened. The master
  361. thread ensures that we flush the log files at least once per
  362. second. */
  363. static time_t srv_last_log_flush_time;
  364. /* Interval in seconds at which various tasks are performed by the
  365. master thread when server is active. In order to balance the workload,
  366. we should try to keep intervals such that they are not multiple of
  367. each other. For example, if we have intervals for various tasks
  368. defined as 5, 10, 15, 60 then all tasks will be performed when
  369. current_time % 60 == 0 and no tasks will be performed when
  370. current_time % 5 != 0. */
  371. # define SRV_MASTER_CHECKPOINT_INTERVAL (7)
  372. # define SRV_MASTER_PURGE_INTERVAL (10)
  373. #ifdef MEM_PERIODIC_CHECK
  374. # define SRV_MASTER_MEM_VALIDATE_INTERVAL (13)
  375. #endif /* MEM_PERIODIC_CHECK */
  376. # define SRV_MASTER_DICT_LRU_INTERVAL (47)
  377. /** Acquire the system_mutex. */
  378. #define srv_sys_mutex_enter() do { \
  379. mutex_enter(&srv_sys->mutex); \
  380. } while (0)
  381. /** Test if the system mutex is owned. */
  382. #define srv_sys_mutex_own() (mutex_own(&srv_sys->mutex) \
  383. && !srv_read_only_mode)
  384. /** Release the system mutex. */
  385. #define srv_sys_mutex_exit() do { \
  386. mutex_exit(&srv_sys->mutex); \
  387. } while (0)
  388. #define fetch_lock_wait_timeout(trx) \
  389. ((trx)->lock.allowed_to_wait \
  390. ? thd_lock_wait_timeout((trx)->mysql_thd) \
  391. : 0)
  392. /*
  393. IMPLEMENTATION OF THE SERVER MAIN PROGRAM
  394. =========================================
  395. There is the following analogue between this database
  396. server and an operating system kernel:
  397. DB concept equivalent OS concept
  398. ---------- ---------------------
  399. transaction -- process;
  400. query thread -- thread;
  401. lock -- semaphore;
  402. kernel -- kernel;
  403. query thread execution:
  404. (a) without lock mutex
  405. reserved -- process executing in user mode;
  406. (b) with lock mutex reserved
  407. -- process executing in kernel mode;
  408. The server has several backgroind threads all running at the same
  409. priority as user threads. It periodically checks if here is anything
  410. happening in the server which requires intervention of the master
  411. thread. Such situations may be, for example, when flushing of dirty
  412. blocks is needed in the buffer pool or old version of database rows
  413. have to be cleaned away (purged). The user can configure a separate
  414. dedicated purge thread(s) too, in which case the master thread does not
  415. do any purging.
  416. The threads which we call user threads serve the queries of the MySQL
  417. server. They run at normal priority.
  418. When there is no activity in the system, also the master thread
  419. suspends itself to wait for an event making the server totally silent.
  420. There is still one complication in our server design. If a
  421. background utility thread obtains a resource (e.g., mutex) needed by a user
  422. thread, and there is also some other user activity in the system,
  423. the user thread may have to wait indefinitely long for the
  424. resource, as the OS does not schedule a background thread if
  425. there is some other runnable user thread. This problem is called
  426. priority inversion in real-time programming.
  427. One solution to the priority inversion problem would be to keep record
  428. of which thread owns which resource and in the above case boost the
  429. priority of the background thread so that it will be scheduled and it
  430. can release the resource. This solution is called priority inheritance
  431. in real-time programming. A drawback of this solution is that the overhead
  432. of acquiring a mutex increases slightly, maybe 0.2 microseconds on a 100
  433. MHz Pentium, because the thread has to call os_thread_get_curr_id. This may
  434. be compared to 0.5 microsecond overhead for a mutex lock-unlock pair. Note
  435. that the thread cannot store the information in the resource , say mutex,
  436. itself, because competing threads could wipe out the information if it is
  437. stored before acquiring the mutex, and if it stored afterwards, the
  438. information is outdated for the time of one machine instruction, at least.
  439. (To be precise, the information could be stored to lock_word in mutex if
  440. the machine supports atomic swap.)
  441. The above solution with priority inheritance may become actual in the
  442. future, currently we do not implement any priority twiddling solution.
  443. Our general aim is to reduce the contention of all mutexes by making
  444. them more fine grained.
  445. The thread table contains information of the current status of each
  446. thread existing in the system, and also the event semaphores used in
  447. suspending the master thread and utility threads when they have nothing
  448. to do. The thread table can be seen as an analogue to the process table
  449. in a traditional Unix implementation. */
  450. /** The server system struct */
  451. struct srv_sys_t{
  452. ib_mutex_t tasks_mutex; /*!< variable protecting the
  453. tasks queue */
  454. UT_LIST_BASE_NODE_T(que_thr_t)
  455. tasks; /*!< task queue */
  456. ib_mutex_t mutex; /*!< variable protecting the
  457. fields below. */
  458. ulint n_sys_threads; /*!< size of the sys_threads
  459. array */
  460. srv_slot_t* sys_threads; /*!< server thread table */
  461. ulint n_threads_active[SRV_MASTER + 1];
  462. /*!< number of threads active
  463. in a thread class */
  464. srv_stats_t::ulint_ctr_1_t
  465. activity_count; /*!< For tracking server
  466. activity */
  467. };
  468. #ifndef HAVE_ATOMIC_BUILTINS
  469. /** Mutex protecting some server global variables. */
  470. UNIV_INTERN ib_mutex_t server_mutex;
  471. #endif /* !HAVE_ATOMIC_BUILTINS */
  472. static srv_sys_t* srv_sys = NULL;
  473. /** Event to signal the monitor thread. */
  474. UNIV_INTERN os_event_t srv_monitor_event;
  475. /** Event to signal the error thread */
  476. UNIV_INTERN os_event_t srv_error_event;
  477. /** Event to signal the buffer pool dump/load thread */
  478. UNIV_INTERN os_event_t srv_buf_dump_event;
  479. /** The buffer pool dump/load file name */
  480. UNIV_INTERN char* srv_buf_dump_filename;
  481. /** Boolean config knobs that tell InnoDB to dump the buffer pool at shutdown
  482. and/or load it during startup. */
  483. UNIV_INTERN char srv_buffer_pool_dump_at_shutdown = FALSE;
  484. UNIV_INTERN char srv_buffer_pool_load_at_startup = FALSE;
  485. /** Slot index in the srv_sys->sys_threads array for the purge thread. */
  486. static const ulint SRV_PURGE_SLOT = 1;
  487. /** Slot index in the srv_sys->sys_threads array for the master thread. */
  488. static const ulint SRV_MASTER_SLOT = 0;
  489. /*********************************************************************//**
  490. Prints counters for work done by srv_master_thread. */
  491. static
  492. void
  493. srv_print_master_thread_info(
  494. /*=========================*/
  495. FILE *file) /* in: output stream */
  496. {
  497. fprintf(file, "srv_master_thread loops: %lu srv_active, "
  498. "%lu srv_shutdown, %lu srv_idle\n",
  499. srv_main_active_loops,
  500. srv_main_shutdown_loops,
  501. srv_main_idle_loops);
  502. fprintf(file, "srv_master_thread log flush and writes: %lu\n",
  503. srv_log_writes_and_flush);
  504. }
  505. /*********************************************************************//**
  506. Sets the info describing an i/o thread current state. */
  507. UNIV_INTERN
  508. void
  509. srv_set_io_thread_op_info(
  510. /*======================*/
  511. ulint i, /*!< in: the 'segment' of the i/o thread */
  512. const char* str) /*!< in: constant char string describing the
  513. state */
  514. {
  515. ut_a(i < SRV_MAX_N_IO_THREADS);
  516. srv_io_thread_op_info[i] = str;
  517. }
  518. /*********************************************************************//**
  519. Resets the info describing an i/o thread current state. */
  520. UNIV_INTERN
  521. void
  522. srv_reset_io_thread_op_info()
  523. /*=========================*/
  524. {
  525. for (ulint i = 0; i < UT_ARR_SIZE(srv_io_thread_op_info); ++i) {
  526. srv_io_thread_op_info[i] = "not started yet";
  527. }
  528. }
  529. #ifdef UNIV_DEBUG
  530. /*********************************************************************//**
  531. Validates the type of a thread table slot.
  532. @return TRUE if ok */
  533. static
  534. ibool
  535. srv_thread_type_validate(
  536. /*=====================*/
  537. srv_thread_type type) /*!< in: thread type */
  538. {
  539. switch (type) {
  540. case SRV_NONE:
  541. break;
  542. case SRV_WORKER:
  543. case SRV_PURGE:
  544. case SRV_MASTER:
  545. return(TRUE);
  546. }
  547. ut_error;
  548. return(FALSE);
  549. }
  550. #endif /* UNIV_DEBUG */
  551. /*********************************************************************//**
  552. Gets the type of a thread table slot.
  553. @return thread type */
  554. static
  555. srv_thread_type
  556. srv_slot_get_type(
  557. /*==============*/
  558. const srv_slot_t* slot) /*!< in: thread slot */
  559. {
  560. srv_thread_type type = slot->type;
  561. ut_ad(srv_thread_type_validate(type));
  562. return(type);
  563. }
  564. /*********************************************************************//**
  565. Reserves a slot in the thread table for the current thread.
  566. @return reserved slot */
  567. static
  568. srv_slot_t*
  569. srv_reserve_slot(
  570. /*=============*/
  571. srv_thread_type type) /*!< in: type of the thread */
  572. {
  573. srv_slot_t* slot = 0;
  574. srv_sys_mutex_enter();
  575. ut_ad(srv_thread_type_validate(type));
  576. switch (type) {
  577. case SRV_MASTER:
  578. slot = &srv_sys->sys_threads[SRV_MASTER_SLOT];
  579. break;
  580. case SRV_PURGE:
  581. slot = &srv_sys->sys_threads[SRV_PURGE_SLOT];
  582. break;
  583. case SRV_WORKER:
  584. /* Find an empty slot, skip the master and purge slots. */
  585. for (slot = &srv_sys->sys_threads[2];
  586. slot->in_use;
  587. ++slot) {
  588. ut_a(slot < &srv_sys->sys_threads[
  589. srv_sys->n_sys_threads]);
  590. }
  591. break;
  592. case SRV_NONE:
  593. ut_error;
  594. }
  595. ut_a(!slot->in_use);
  596. slot->in_use = TRUE;
  597. slot->suspended = FALSE;
  598. slot->type = type;
  599. ut_ad(srv_slot_get_type(slot) == type);
  600. ++srv_sys->n_threads_active[type];
  601. srv_sys_mutex_exit();
  602. return(slot);
  603. }
  604. /*********************************************************************//**
  605. Suspends the calling thread to wait for the event in its thread slot.
  606. @return the current signal count of the event. */
  607. static
  608. ib_int64_t
  609. srv_suspend_thread_low(
  610. /*===================*/
  611. srv_slot_t* slot) /*!< in/out: thread slot */
  612. {
  613. ut_ad(!srv_read_only_mode);
  614. ut_ad(srv_sys_mutex_own());
  615. ut_ad(slot->in_use);
  616. srv_thread_type type = srv_slot_get_type(slot);
  617. switch (type) {
  618. case SRV_NONE:
  619. ut_error;
  620. case SRV_MASTER:
  621. /* We have only one master thread and it
  622. should be the first entry always. */
  623. ut_a(srv_sys->n_threads_active[type] == 1);
  624. break;
  625. case SRV_PURGE:
  626. /* We have only one purge coordinator thread
  627. and it should be the second entry always. */
  628. ut_a(srv_sys->n_threads_active[type] == 1);
  629. break;
  630. case SRV_WORKER:
  631. ut_a(srv_n_purge_threads > 1);
  632. ut_a(srv_sys->n_threads_active[type] > 0);
  633. break;
  634. }
  635. ut_a(!slot->suspended);
  636. slot->suspended = TRUE;
  637. ut_a(srv_sys->n_threads_active[type] > 0);
  638. srv_sys->n_threads_active[type]--;
  639. return(os_event_reset(slot->event));
  640. }
  641. /*********************************************************************//**
  642. Suspends the calling thread to wait for the event in its thread slot.
  643. @return the current signal count of the event. */
  644. static
  645. ib_int64_t
  646. srv_suspend_thread(
  647. /*===============*/
  648. srv_slot_t* slot) /*!< in/out: thread slot */
  649. {
  650. srv_sys_mutex_enter();
  651. ib_int64_t sig_count = srv_suspend_thread_low(slot);
  652. srv_sys_mutex_exit();
  653. return(sig_count);
  654. }
  655. /*********************************************************************//**
  656. Releases threads of the type given from suspension in the thread table.
  657. NOTE! The server mutex has to be reserved by the caller!
  658. @return number of threads released: this may be less than n if not
  659. enough threads were suspended at the moment. */
  660. UNIV_INTERN
  661. ulint
  662. srv_release_threads(
  663. /*================*/
  664. srv_thread_type type, /*!< in: thread type */
  665. ulint n) /*!< in: number of threads to release */
  666. {
  667. ulint i;
  668. ulint count = 0;
  669. ut_ad(srv_thread_type_validate(type));
  670. ut_ad(n > 0);
  671. srv_sys_mutex_enter();
  672. for (i = 0; i < srv_sys->n_sys_threads; i++) {
  673. srv_slot_t* slot;
  674. slot = &srv_sys->sys_threads[i];
  675. if (slot->in_use
  676. && srv_slot_get_type(slot) == type
  677. && slot->suspended) {
  678. switch (type) {
  679. case SRV_NONE:
  680. ut_error;
  681. case SRV_MASTER:
  682. /* We have only one master thread and it
  683. should be the first entry always. */
  684. ut_a(n == 1);
  685. ut_a(i == SRV_MASTER_SLOT);
  686. ut_a(srv_sys->n_threads_active[type] == 0);
  687. break;
  688. case SRV_PURGE:
  689. /* We have only one purge coordinator thread
  690. and it should be the second entry always. */
  691. ut_a(n == 1);
  692. ut_a(i == SRV_PURGE_SLOT);
  693. ut_a(srv_n_purge_threads > 0);
  694. ut_a(srv_sys->n_threads_active[type] == 0);
  695. break;
  696. case SRV_WORKER:
  697. ut_a(srv_n_purge_threads > 1);
  698. ut_a(srv_sys->n_threads_active[type]
  699. < srv_n_purge_threads - 1);
  700. break;
  701. }
  702. slot->suspended = FALSE;
  703. ++srv_sys->n_threads_active[type];
  704. os_event_set(slot->event);
  705. if (++count == n) {
  706. break;
  707. }
  708. }
  709. }
  710. srv_sys_mutex_exit();
  711. return(count);
  712. }
  713. /*********************************************************************//**
  714. Release a thread's slot. */
  715. static
  716. void
  717. srv_free_slot(
  718. /*==========*/
  719. srv_slot_t* slot) /*!< in/out: thread slot */
  720. {
  721. srv_sys_mutex_enter();
  722. if (!slot->suspended) {
  723. /* Mark the thread as inactive. */
  724. srv_suspend_thread_low(slot);
  725. }
  726. /* Free the slot for reuse. */
  727. ut_ad(slot->in_use);
  728. slot->in_use = FALSE;
  729. srv_sys_mutex_exit();
  730. }
  731. /*********************************************************************//**
  732. Initializes the server. */
  733. UNIV_INTERN
  734. void
  735. srv_init(void)
  736. /*==========*/
  737. {
  738. ulint n_sys_threads = 0;
  739. ulint srv_sys_sz = sizeof(*srv_sys);
  740. #ifndef HAVE_ATOMIC_BUILTINS
  741. mutex_create(server_mutex_key, &server_mutex, SYNC_ANY_LATCH);
  742. #endif /* !HAVE_ATOMIC_BUILTINS */
  743. mutex_create(srv_innodb_monitor_mutex_key,
  744. &srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
  745. if (!srv_read_only_mode) {
  746. /* Number of purge threads + master thread */
  747. n_sys_threads = srv_n_purge_threads + 1;
  748. srv_sys_sz += n_sys_threads * sizeof(*srv_sys->sys_threads);
  749. }
  750. srv_sys = static_cast<srv_sys_t*>(mem_zalloc(srv_sys_sz));
  751. srv_sys->n_sys_threads = n_sys_threads;
  752. if (!srv_read_only_mode) {
  753. mutex_create(srv_sys_mutex_key, &srv_sys->mutex, SYNC_THREADS);
  754. mutex_create(srv_sys_tasks_mutex_key,
  755. &srv_sys->tasks_mutex, SYNC_ANY_LATCH);
  756. srv_sys->sys_threads = (srv_slot_t*) &srv_sys[1];
  757. for (ulint i = 0; i < srv_sys->n_sys_threads; ++i) {
  758. srv_slot_t* slot = &srv_sys->sys_threads[i];
  759. slot->event = os_event_create();
  760. ut_a(slot->event);
  761. }
  762. srv_error_event = os_event_create();
  763. srv_monitor_event = os_event_create();
  764. srv_buf_dump_event = os_event_create();
  765. UT_LIST_INIT(srv_sys->tasks);
  766. }
  767. /* page_zip_stat_per_index_mutex is acquired from:
  768. 1. page_zip_compress() (after SYNC_FSP)
  769. 2. page_zip_decompress()
  770. 3. i_s_cmp_per_index_fill_low() (where SYNC_DICT is acquired)
  771. 4. innodb_cmp_per_index_update(), no other latches
  772. since we do not acquire any other latches while holding this mutex,
  773. it can have very low level. We pick SYNC_ANY_LATCH for it. */
  774. mutex_create(
  775. page_zip_stat_per_index_mutex_key,
  776. &page_zip_stat_per_index_mutex, SYNC_ANY_LATCH);
  777. /* Create dummy indexes for infimum and supremum records */
  778. dict_ind_init();
  779. srv_conc_init();
  780. /* Initialize some INFORMATION SCHEMA internal structures */
  781. trx_i_s_cache_init(trx_i_s_cache);
  782. ut_crc32_init();
  783. dict_mem_init();
  784. }
  785. /*********************************************************************//**
  786. Frees the data structures created in srv_init(). */
  787. UNIV_INTERN
  788. void
  789. srv_free(void)
  790. /*==========*/
  791. {
  792. srv_conc_free();
  793. /* The mutexes srv_sys->mutex and srv_sys->tasks_mutex should have
  794. been freed by sync_close() already. */
  795. mem_free(srv_sys);
  796. srv_sys = NULL;
  797. trx_i_s_cache_free(trx_i_s_cache);
  798. if (!srv_read_only_mode) {
  799. os_event_free(srv_buf_dump_event);
  800. srv_buf_dump_event = NULL;
  801. }
  802. }
  803. /*********************************************************************//**
  804. Initializes the synchronization primitives, memory system, and the thread
  805. local storage. */
  806. UNIV_INTERN
  807. void
  808. srv_general_init(void)
  809. /*==================*/
  810. {
  811. ut_mem_init();
  812. /* Reset the system variables in the recovery module. */
  813. recv_sys_var_init();
  814. os_sync_init();
  815. sync_init();
  816. mem_init(srv_mem_pool_size);
  817. que_init();
  818. row_mysql_init();
  819. }
  820. /*********************************************************************//**
  821. Normalizes init parameter values to use units we use inside InnoDB. */
  822. static
  823. void
  824. srv_normalize_init_values(void)
  825. /*===========================*/
  826. {
  827. ulint n;
  828. ulint i;
  829. n = srv_n_data_files;
  830. for (i = 0; i < n; i++) {
  831. srv_data_file_sizes[i] = srv_data_file_sizes[i]
  832. * ((1024 * 1024) / UNIV_PAGE_SIZE);
  833. }
  834. srv_last_file_size_max = srv_last_file_size_max
  835. * ((1024 * 1024) / UNIV_PAGE_SIZE);
  836. srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;
  837. srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;
  838. srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
  839. }
  840. /*********************************************************************//**
  841. Boots the InnoDB server. */
  842. UNIV_INTERN
  843. void
  844. srv_boot(void)
  845. /*==========*/
  846. {
  847. /* Transform the init parameter values given by MySQL to
  848. use units we use inside InnoDB: */
  849. srv_normalize_init_values();
  850. /* Initialize synchronization primitives, memory management, and thread
  851. local storage */
  852. srv_general_init();
  853. /* Initialize this module */
  854. srv_init();
  855. srv_mon_create();
  856. }
  857. /******************************************************************//**
  858. Refreshes the values used to calculate per-second averages. */
  859. static
  860. void
  861. srv_refresh_innodb_monitor_stats(void)
  862. /*==================================*/
  863. {
  864. mutex_enter(&srv_innodb_monitor_mutex);
  865. srv_last_monitor_time = time(NULL);
  866. os_aio_refresh_stats();
  867. btr_cur_n_sea_old = btr_cur_n_sea;
  868. btr_cur_n_non_sea_old = btr_cur_n_non_sea;
  869. log_refresh_stats();
  870. buf_refresh_io_stats_all();
  871. srv_n_rows_inserted_old = srv_stats.n_rows_inserted;
  872. srv_n_rows_updated_old = srv_stats.n_rows_updated;
  873. srv_n_rows_deleted_old = srv_stats.n_rows_deleted;
  874. srv_n_rows_read_old = srv_stats.n_rows_read;
  875. mutex_exit(&srv_innodb_monitor_mutex);
  876. }
  877. /******************************************************************//**
  878. Outputs to a file the output of the InnoDB Monitor.
  879. @return FALSE if not all information printed
  880. due to failure to obtain necessary mutex */
  881. UNIV_INTERN
  882. ibool
  883. srv_printf_innodb_monitor(
  884. /*======================*/
  885. FILE* file, /*!< in: output stream */
  886. ibool nowait, /*!< in: whether to wait for the
  887. lock_sys_t:: mutex */
  888. ulint* trx_start_pos, /*!< out: file position of the start of
  889. the list of active transactions */
  890. ulint* trx_end) /*!< out: file position of the end of
  891. the list of active transactions */
  892. {
  893. double time_elapsed;
  894. time_t current_time;
  895. ulint n_reserved;
  896. ibool ret;
  897. mutex_enter(&srv_innodb_monitor_mutex);
  898. current_time = time(NULL);
  899. /* We add 0.001 seconds to time_elapsed to prevent division
  900. by zero if two users happen to call SHOW ENGINE INNODB STATUS at the
  901. same time */
  902. time_elapsed = difftime(current_time, srv_last_monitor_time)
  903. + 0.001;
  904. srv_last_monitor_time = time(NULL);
  905. fputs("\n=====================================\n", file);
  906. ut_print_timestamp(file);
  907. fprintf(file,
  908. " INNODB MONITOR OUTPUT\n"
  909. "=====================================\n"
  910. "Per second averages calculated from the last %lu seconds\n",
  911. (ulong) time_elapsed);
  912. fputs("-----------------\n"
  913. "BACKGROUND THREAD\n"
  914. "-----------------\n", file);
  915. srv_print_master_thread_info(file);
  916. fputs("----------\n"
  917. "SEMAPHORES\n"
  918. "----------\n", file);
  919. sync_print(file);
  920. /* Conceptually, srv_innodb_monitor_mutex has a very high latching
  921. order level in sync0sync.h, while dict_foreign_err_mutex has a very
  922. low level 135. Therefore we can reserve the latter mutex here without
  923. a danger of a deadlock of threads. */
  924. mutex_enter(&dict_foreign_err_mutex);
  925. if (!srv_read_only_mode && ftell(dict_foreign_err_file) != 0L) {
  926. fputs("------------------------\n"
  927. "LATEST FOREIGN KEY ERROR\n"
  928. "------------------------\n", file);
  929. ut_copy_file(file, dict_foreign_err_file);
  930. }
  931. mutex_exit(&dict_foreign_err_mutex);
  932. /* Only if lock_print_info_summary proceeds correctly,
  933. before we call the lock_print_info_all_transactions
  934. to print all the lock information. IMPORTANT NOTE: This
  935. function acquires the lock mutex on success. */
  936. ret = lock_print_info_summary(file, nowait);
  937. if (ret) {
  938. if (trx_start_pos) {
  939. long t = ftell(file);
  940. if (t < 0) {
  941. *trx_start_pos = ULINT_UNDEFINED;
  942. } else {
  943. *trx_start_pos = (ulint) t;
  944. }
  945. }
  946. /* NOTE: If we get here then we have the lock mutex. This
  947. function will release the lock mutex that we acquired when
  948. we called the lock_print_info_summary() function earlier. */
  949. lock_print_info_all_transactions(file);
  950. if (trx_end) {
  951. long t = ftell(file);
  952. if (t < 0) {
  953. *trx_end = ULINT_UNDEFINED;
  954. } else {
  955. *trx_end = (ulint) t;
  956. }
  957. }
  958. }
  959. fputs("--------\n"
  960. "FILE I/O\n"
  961. "--------\n", file);
  962. os_aio_print(file);
  963. fputs("-------------------------------------\n"
  964. "INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
  965. "-------------------------------------\n", file);
  966. ibuf_print(file);
  967. ha_print_info(file, btr_search_sys->hash_index);
  968. fprintf(file,
  969. "%.2f hash searches/s, %.2f non-hash searches/s\n",
  970. (btr_cur_n_sea - btr_cur_n_sea_old)
  971. / time_elapsed,
  972. (btr_cur_n_non_sea - btr_cur_n_non_sea_old)
  973. / time_elapsed);
  974. btr_cur_n_sea_old = btr_cur_n_sea;
  975. btr_cur_n_non_sea_old = btr_cur_n_non_sea;
  976. fputs("---\n"
  977. "LOG\n"
  978. "---\n", file);
  979. log_print(file);
  980. fputs("----------------------\n"
  981. "BUFFER POOL AND MEMORY\n"
  982. "----------------------\n", file);
  983. fprintf(file,
  984. "Total memory allocated " ULINTPF
  985. "; in additional pool allocated " ULINTPF "\n",
  986. ut_total_allocated_memory,
  987. mem_pool_get_reserved(mem_comm_pool));
  988. fprintf(file, "Dictionary memory allocated " ULINTPF "\n",
  989. dict_sys->size);
  990. buf_print_io(file);
  991. fputs("--------------\n"
  992. "ROW OPERATIONS\n"
  993. "--------------\n", file);
  994. fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n",
  995. (long) srv_conc_get_active_threads(),
  996. srv_conc_get_waiting_threads());
  997. /* This is a dirty read, without holding trx_sys->mutex. */
  998. fprintf(file, "%lu read views open inside InnoDB\n",
  999. UT_LIST_GET_LEN(trx_sys->view_list));
  1000. n_reserved = fil_space_get_n_reserved_extents(0);
  1001. if (n_reserved > 0) {
  1002. fprintf(file,
  1003. "%lu tablespace extents now reserved for"
  1004. " B-tree split operations\n",
  1005. (ulong) n_reserved);
  1006. }
  1007. #ifdef UNIV_LINUX
  1008. fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n",
  1009. (ulong) srv_main_thread_process_no,
  1010. (ulong) srv_main_thread_id,
  1011. srv_main_thread_op_info);
  1012. #else
  1013. fprintf(file, "Main thread id %lu, state: %s\n",
  1014. (ulong) srv_main_thread_id,
  1015. srv_main_thread_op_info);
  1016. #endif
  1017. fprintf(file,
  1018. "Number of rows inserted " ULINTPF
  1019. ", updated " ULINTPF ", deleted " ULINTPF
  1020. ", read " ULINTPF "\n",
  1021. (ulint) srv_stats.n_rows_inserted,
  1022. (ulint) srv_stats.n_rows_updated,
  1023. (ulint) srv_stats.n_rows_deleted,
  1024. (ulint) srv_stats.n_rows_read);
  1025. fprintf(file,
  1026. "%.2f inserts/s, %.2f updates/s,"
  1027. " %.2f deletes/s, %.2f reads/s\n",
  1028. ((ulint) srv_stats.n_rows_inserted - srv_n_rows_inserted_old)
  1029. / time_elapsed,
  1030. ((ulint) srv_stats.n_rows_updated - srv_n_rows_updated_old)
  1031. / time_elapsed,
  1032. ((ulint) srv_stats.n_rows_deleted - srv_n_rows_deleted_old)
  1033. / time_elapsed,
  1034. ((ulint) srv_stats.n_rows_read - srv_n_rows_read_old)
  1035. / time_elapsed);
  1036. srv_n_rows_inserted_old = srv_stats.n_rows_inserted;
  1037. srv_n_rows_updated_old = srv_stats.n_rows_updated;
  1038. srv_n_rows_deleted_old = srv_stats.n_rows_deleted;
  1039. srv_n_rows_read_old = srv_stats.n_rows_read;
  1040. fputs("----------------------------\n"
  1041. "END OF INNODB MONITOR OUTPUT\n"
  1042. "============================\n", file);
  1043. mutex_exit(&srv_innodb_monitor_mutex);
  1044. fflush(file);
  1045. return(ret);
  1046. }
  1047. /******************************************************************//**
  1048. Function to pass InnoDB status variables to MySQL */
  1049. UNIV_INTERN
  1050. void
  1051. srv_export_innodb_status(void)
  1052. /*==========================*/
  1053. {
  1054. buf_pool_stat_t stat;
  1055. buf_pools_list_size_t buf_pools_list_size;
  1056. ulint LRU_len;
  1057. ulint free_len;
  1058. ulint flush_list_len;
  1059. buf_get_total_stat(&stat);
  1060. buf_get_total_list_len(&LRU_len, &free_len, &flush_list_len);
  1061. buf_get_total_list_size_in_bytes(&buf_pools_list_size);
  1062. mutex_enter(&srv_innodb_monitor_mutex);
  1063. export_vars.innodb_data_pending_reads =
  1064. os_n_pending_reads;
  1065. export_vars.innodb_data_pending_writes =
  1066. os_n_pending_writes;
  1067. export_vars.innodb_data_pending_fsyncs =
  1068. fil_n_pending_log_flushes
  1069. + fil_n_pending_tablespace_flushes;
  1070. export_vars.innodb_data_fsyncs = os_n_fsyncs;
  1071. export_vars.innodb_data_read = srv_stats.data_read;
  1072. export_vars.innodb_data_reads = os_n_file_reads;
  1073. export_vars.innodb_data_writes = os_n_file_writes;
  1074. export_vars.innodb_data_written = srv_stats.data_written;
  1075. export_vars.innodb_buffer_pool_read_requests = stat.n_page_gets;
  1076. export_vars.innodb_buffer_pool_write_requests =
  1077. srv_stats.buf_pool_write_requests;
  1078. export_vars.innodb_buffer_pool_wait_free =
  1079. srv_stats.buf_pool_wait_free;
  1080. export_vars.innodb_buffer_pool_pages_flushed =
  1081. srv_stats.buf_pool_flushed;
  1082. export_vars.innodb_buffer_pool_reads = srv_stats.buf_pool_reads;
  1083. export_vars.innodb_buffer_pool_read_ahead_rnd =
  1084. stat.n_ra_pages_read_rnd;
  1085. export_vars.innodb_buffer_pool_read_ahead =
  1086. stat.n_ra_pages_read;
  1087. export_vars.innodb_buffer_pool_read_ahead_evicted =
  1088. stat.n_ra_pages_evicted;
  1089. export_vars.innodb_buffer_pool_pages_data = LRU_len;
  1090. export_vars.innodb_buffer_pool_bytes_data =
  1091. buf_pools_list_size.LRU_bytes
  1092. + buf_pools_list_size.unzip_LRU_bytes;
  1093. export_vars.innodb_buffer_pool_pages_dirty = flush_list_len;
  1094. export_vars.innodb_buffer_pool_bytes_dirty =
  1095. buf_pools_list_size.flush_list_bytes;
  1096. export_vars.innodb_buffer_pool_pages_free = free_len;
  1097. #ifdef UNIV_DEBUG
  1098. export_vars.innodb_buffer_pool_pages_latched =
  1099. buf_get_latched_pages_number();
  1100. #endif /* UNIV_DEBUG */
  1101. export_vars.innodb_buffer_pool_pages_total = buf_pool_get_n_pages();
  1102. export_vars.innodb_buffer_pool_pages_misc =
  1103. buf_pool_get_n_pages() - LRU_len - free_len;
  1104. #ifdef HAVE_ATOMIC_BUILTINS
  1105. export_vars.innodb_have_atomic_builtins = 1;
  1106. #else
  1107. export_vars.innodb_have_atomic_builtins = 0;
  1108. #endif
  1109. export_vars.innodb_page_size = UNIV_PAGE_SIZE;
  1110. export_vars.innodb_log_waits = srv_stats.log_waits;
  1111. export_vars.innodb_os_log_written = srv_stats.os_log_written;
  1112. export_vars.innodb_os_log_fsyncs = fil_n_log_flushes;
  1113. export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes;
  1114. export_vars.innodb_os_log_pending_writes =
  1115. srv_stats.os_log_pending_writes;
  1116. export_vars.innodb_log_write_requests = srv_stats.log_write_requests;
  1117. export_vars.innodb_log_writes = srv_stats.log_writes;
  1118. export_vars.innodb_dblwr_pages_written =
  1119. srv_stats.dblwr_pages_written;
  1120. export_vars.innodb_dblwr_writes = srv_stats.dblwr_writes;
  1121. export_vars.innodb_pages_created = stat.n_pages_created;
  1122. export_vars.innodb_pages_read = stat.n_pages_read;
  1123. export_vars.innodb_pages_written = stat.n_pages_written;
  1124. export_vars.innodb_row_lock_waits = srv_stats.n_lock_wait_count;
  1125. export_vars.innodb_row_lock_current_waits =
  1126. srv_stats.n_lock_wait_current_count;
  1127. export_vars.innodb_row_lock_time = srv_stats.n_lock_wait_time / 1000;
  1128. if (srv_stats.n_lock_wait_count > 0) {
  1129. export_vars.innodb_row_lock_time_avg = (ulint)
  1130. (srv_stats.n_lock_wait_time
  1131. / 1000 / srv_stats.n_lock_wait_count);
  1132. } else {
  1133. export_vars.innodb_row_lock_time_avg = 0;
  1134. }
  1135. export_vars.innodb_row_lock_time_max =
  1136. lock_sys->n_lock_max_wait_time / 1000;
  1137. export_vars.innodb_rows_read = srv_stats.n_rows_read;
  1138. export_vars.innodb_rows_inserted = srv_stats.n_rows_inserted;
  1139. export_vars.innodb_rows_updated = srv_stats.n_rows_updated;
  1140. export_vars.innodb_rows_deleted = srv_stats.n_rows_deleted;
  1141. export_vars.innodb_num_open_files = fil_n_file_opened;
  1142. export_vars.innodb_truncated_status_writes =
  1143. srv_truncated_status_writes;
  1144. export_vars.innodb_available_undo_logs = srv_available_undo_logs;
  1145. #ifdef UNIV_DEBUG
  1146. rw_lock_s_lock(&purge_sys->latch);
  1147. trx_id_t done_trx_no = purge_sys->done.trx_no;
  1148. trx_id_t up_limit_id = purge_sys->view
  1149. ? purge_sys->view->up_limit_id
  1150. : 0;
  1151. rw_lock_s_unlock(&purge_sys->latch);
  1152. mutex_enter(&trx_sys->mutex);
  1153. trx_id_t max_trx_id = trx_sys->rw_max_trx_id;
  1154. mutex_exit(&trx_sys->mutex);
  1155. if (!done_trx_no || max_trx_id < done_trx_no - 1) {
  1156. export_vars.innodb_purge_trx_id_age = 0;
  1157. } else {
  1158. export_vars.innodb_purge_trx_id_age =
  1159. (ulint) (max_trx_id - done_trx_no + 1);
  1160. }
  1161. if (!up_limit_id
  1162. || max_trx_id < up_limit_id) {
  1163. export_vars.innodb_purge_view_trx_id_age = 0;
  1164. } else {
  1165. export_vars.innodb_purge_view_trx_id_age =
  1166. (ulint) (max_trx_id - up_limit_id);
  1167. }
  1168. #endif /* UNIV_DEBUG */
  1169. mutex_exit(&srv_innodb_monitor_mutex);
  1170. }
  1171. /*********************************************************************//**
  1172. A thread which prints the info output by various InnoDB monitors.
  1173. @return a dummy parameter */
  1174. extern "C" UNIV_INTERN
  1175. os_thread_ret_t
  1176. DECLARE_THREAD(srv_monitor_thread)(
  1177. /*===============================*/
  1178. void* arg __attribute__((unused)))
  1179. /*!< in: a dummy parameter required by
  1180. os_thread_create */
  1181. {
  1182. ib_int64_t sig_count;
  1183. double time_elapsed;
  1184. time_t current_time;
  1185. time_t last_table_monitor_time;
  1186. time_t last_tablespace_monitor_time;
  1187. time_t last_monitor_time;
  1188. ulint mutex_skipped;
  1189. ibool last_srv_print_monitor;
  1190. ut_ad(!srv_read_only_mode);
  1191. #ifdef UNIV_DEBUG_THREAD_CREATION
  1192. fprintf(stderr, "Lock timeout thread starts, id %lu\n",
  1193. os_thread_pf(os_thread_get_curr_id()));
  1194. #endif /* UNIV_DEBUG_THREAD_CREATION */
  1195. #ifdef UNIV_PFS_THREAD
  1196. pfs_register_thread(srv_monitor_thread_key);
  1197. #endif /* UNIV_PFS_THREAD */
  1198. srv_monitor_active = TRUE;
  1199. UT_NOT_USED(arg);
  1200. srv_last_monitor_time = ut_time();
  1201. last_table_monitor_time = ut_time();
  1202. last_tablespace_monitor_time = ut_time();
  1203. last_monitor_time = ut_time();
  1204. mutex_skipped = 0;
  1205. last_srv_print_monitor = srv_print_innodb_monitor;
  1206. loop:
  1207. /* Wake up every 5 seconds to see if we need to print
  1208. monitor information or if signalled at shutdown. */
  1209. sig_count = os_event_reset(srv_monitor_event);
  1210. os_event_wait_time_low(srv_monitor_event, 5000000, sig_count);
  1211. current_time = ut_time();
  1212. time_elapsed = difftime(current_time, last_monitor_time);
  1213. if (time_elapsed > 15) {
  1214. last_monitor_time = ut_time();
  1215. if (srv_print_innodb_monitor) {
  1216. /* Reset mutex_skipped counter everytime
  1217. srv_print_innodb_monitor changes. This is to
  1218. ensure we will not be blocked by lock_sys->mutex
  1219. for short duration information printing,
  1220. such as requested by sync_array_print_long_waits() */
  1221. if (!last_srv_print_monitor) {
  1222. mutex_skipped = 0;
  1223. last_srv_print_monitor = TRUE;
  1224. }
  1225. if (!srv_printf_innodb_monitor(stderr,
  1226. MUTEX_NOWAIT(mutex_skipped),
  1227. NULL, NULL)) {
  1228. mutex_skipped++;
  1229. } else {
  1230. /* Reset the counter */
  1231. mutex_skipped = 0;
  1232. }
  1233. } else {
  1234. last_srv_print_monitor = FALSE;
  1235. }
  1236. /* We don't create the temp files or associated
  1237. mutexes in read-only-mode */
  1238. if (!srv_read_only_mode && srv_innodb_status) {
  1239. mutex_enter(&srv_monitor_file_mutex);
  1240. rewind(srv_monitor_file);
  1241. if (!srv_printf_innodb_monitor(srv_monitor_file,
  1242. MUTEX_NOWAIT(mutex_skipped),
  1243. NULL, NULL)) {
  1244. mutex_skipped++;
  1245. } else {
  1246. mutex_skipped = 0;
  1247. }
  1248. os_file_set_eof(srv_monitor_file);
  1249. mutex_exit(&srv_monitor_file_mutex);
  1250. }
  1251. if (srv_print_innodb_tablespace_monitor
  1252. && difftime(current_time,
  1253. last_tablespace_monitor_time) > 60) {
  1254. last_tablespace_monitor_time = ut_time();
  1255. fputs("========================"
  1256. "========================\n",
  1257. stderr);
  1258. ut_print_timestamp(stderr);
  1259. fputs(" INNODB TABLESPACE MONITOR OUTPUT\n"
  1260. "========================"
  1261. "========================\n",
  1262. stderr);
  1263. fsp_print(0);
  1264. fputs("Validating tablespace\n", stderr);
  1265. fsp_validate(0);
  1266. fputs("Validation ok\n"
  1267. "---------------------------------------\n"
  1268. "END OF INNODB TABLESPACE MONITOR OUTPUT\n"
  1269. "=======================================\n",
  1270. stderr);
  1271. }
  1272. if (srv_print_innodb_table_monitor
  1273. && difftime(current_time, last_table_monitor_time) > 60) {
  1274. last_table_monitor_time = ut_time();
  1275. fprintf(stderr, "Warning: %s\n",
  1276. DEPRECATED_MSG_INNODB_TABLE_MONITOR);
  1277. fputs("===========================================\n",
  1278. stderr);
  1279. ut_print_timestamp(stderr);
  1280. fputs(" INNODB TABLE MONITOR OUTPUT\n"
  1281. "===========================================\n",
  1282. stderr);
  1283. dict_print();
  1284. fputs("-----------------------------------\n"
  1285. "END OF INNODB TABLE MONITOR OUTPUT\n"
  1286. "==================================\n",
  1287. stderr);
  1288. fprintf(stderr, "Warning: %s\n",
  1289. DEPRECATED_MSG_INNODB_TABLE_MONITOR);
  1290. }
  1291. }
  1292. if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
  1293. goto exit_func;
  1294. }
  1295. if (srv_print_innodb_monitor
  1296. || srv_print_innodb_lock_monitor
  1297. || srv_print_innodb_tablespace_monitor
  1298. || srv_print_innodb_table_monitor) {
  1299. goto loop;
  1300. }
  1301. goto loop;
  1302. exit_func:
  1303. srv_monitor_active = FALSE;
  1304. /* We count the number of threads in os_thread_exit(). A created
  1305. thread should always use that to exit and not use return() to exit. */
  1306. os_thread_exit(NULL);
  1307. OS_THREAD_DUMMY_RETURN;
  1308. }
  1309. /*********************************************************************//**
  1310. A thread which prints warnings about semaphore waits which have lasted
  1311. too long. These can be used to track bugs which cause hangs.
  1312. Note: In order to make sync_arr_wake_threads_if_sema_free work as expected,
  1313. we should avoid waiting any mutexes in this function!
  1314. @return a dummy parameter */
  1315. extern "C" UNIV_INTERN
  1316. os_thread_ret_t
  1317. DECLARE_THREAD(srv_error_monitor_thread)(
  1318. /*=====================================*/
  1319. void* arg __attribute__((unused)))
  1320. /*!< in: a dummy parameter required by
  1321. os_thread_create */
  1322. {
  1323. /* number of successive fatal timeouts observed */
  1324. ulint fatal_cnt = 0;
  1325. lsn_t old_lsn;
  1326. lsn_t new_lsn;
  1327. ib_int64_t sig_count;
  1328. /* longest waiting thread for a semaphore */
  1329. os_thread_id_t waiter = os_thread_get_curr_id();
  1330. os_thread_id_t old_waiter = waiter;
  1331. /* the semaphore that is being waited for */
  1332. const void* sema = NULL;
  1333. const void* old_sema = NULL;
  1334. ut_ad(!srv_read_only_mode);
  1335. old_lsn = srv_start_lsn;
  1336. #ifdef UNIV_DEBUG_THREAD_CREATION
  1337. fprintf(stderr, "Error monitor thread starts, id %lu\n",
  1338. os_thread_pf(os_thread_get_curr_id()));
  1339. #endif /* UNIV_DEBUG_THREAD_CREATION */
  1340. #ifdef UNIV_PFS_THREAD
  1341. pfs_register_thread(srv_error_monitor_thread_key);
  1342. #endif /* UNIV_PFS_THREAD */
  1343. srv_error_monitor_active = TRUE;
  1344. loop:
  1345. /* Try to track a strange bug reported by Harald Fuchs and others,
  1346. where the lsn seems to decrease at times */
  1347. if (log_peek_lsn(&new_lsn)) {
  1348. if (new_lsn < old_lsn) {
  1349. ut_print_timestamp(stderr);
  1350. fprintf(stderr,
  1351. " InnoDB: Error: old log sequence number " LSN_PF
  1352. " was greater\n"
  1353. "InnoDB: than the new log sequence number " LSN_PF "!\n"
  1354. "InnoDB: Please submit a bug report"
  1355. " to http://bugs.mysql.com\n",
  1356. old_lsn, new_lsn);
  1357. ut_ad(0);
  1358. }
  1359. old_lsn = new_lsn;
  1360. }
  1361. if (difftime(time(NULL), srv_last_monitor_time) > 60) {
  1362. /* We referesh InnoDB Monitor values so that averages are
  1363. printed from at most 60 last seconds */
  1364. srv_refresh_innodb_monitor_stats();
  1365. }
  1366. /* Update the statistics collected for deciding LRU
  1367. eviction policy. */
  1368. buf_LRU_stat_update();
  1369. /* In case mutex_exit is not a memory barrier, it is
  1370. theoretically possible some threads are left waiting though
  1371. the semaphore is already released. Wake up those threads: */
  1372. sync_arr_wake_threads_if_sema_free();
  1373. if (sync_array_print_long_waits(&waiter, &sema)
  1374. && sema == old_sema && os_thread_eq(waiter, old_waiter)) {
  1375. fatal_cnt++;
  1376. if (fatal_cnt > 10) {
  1377. fprintf(stderr,
  1378. "InnoDB: Error: semaphore wait has lasted"
  1379. " > %lu seconds\n"
  1380. "InnoDB: We intentionally crash the server,"
  1381. " because it appears to be hung.\n",
  1382. (ulong) srv_fatal_semaphore_wait_threshold);
  1383. ut_error;
  1384. }
  1385. } else {
  1386. fatal_cnt = 0;
  1387. old_waiter = waiter;
  1388. old_sema = sema;
  1389. }
  1390. /* Flush stderr so that a database user gets the output
  1391. to possible MySQL error file */
  1392. fflush(stderr);
  1393. sig_count = os_event_reset(srv_error_event);
  1394. os_event_wait_time_low(srv_error_event, 1000000, sig_count);
  1395. if (srv_shutdown_state < SRV_SHUTDOWN_CLEANUP) {
  1396. goto loop;
  1397. }
  1398. srv_error_monitor_active = FALSE;
  1399. /* We count the number of threads in os_thread_exit(). A created
  1400. thread should always use that to exit and not use return() to exit. */
  1401. os_thread_exit(NULL);
  1402. OS_THREAD_DUMMY_RETURN;
  1403. }
  1404. /******************************************************************//**
  1405. Increment the server activity count. */
  1406. UNIV_INTERN
  1407. void
  1408. srv_inc_activity_count(void)
  1409. /*========================*/
  1410. {
  1411. srv_sys->activity_count.inc();
  1412. }
  1413. /**********************************************************************//**
  1414. Check whether any background thread is active. If so return the thread
  1415. type.
  1416. @return SRV_NONE if all are suspended or have exited, thread
  1417. type if any are still active. */
  1418. UNIV_INTERN
  1419. srv_thread_type
  1420. srv_get_active_thread_type(void)
  1421. /*============================*/
  1422. {
  1423. srv_thread_type ret = SRV_NONE;
  1424. if (srv_read_only_mode) {
  1425. return(SRV_NONE);
  1426. }
  1427. srv_sys_mutex_enter();
  1428. for (ulint i = SRV_WORKER; i <= SRV_MASTER; ++i) {
  1429. if (srv_sys->n_threads_active[i] != 0) {
  1430. ret = static_cast<srv_thread_type>(i);
  1431. break;
  1432. }
  1433. }
  1434. srv_sys_mutex_exit();
  1435. /* Check only on shutdown. */
  1436. if (ret == SRV_NONE
  1437. && srv_shutdown_state != SRV_SHUTDOWN_NONE
  1438. && trx_purge_state() != PURGE_STATE_DISABLED
  1439. && trx_purge_state() != PURGE_STATE_EXIT) {
  1440. ret = SRV_PURGE;
  1441. }
  1442. return(ret);
  1443. }
  1444. /**********************************************************************//**
  1445. Check whether any background thread are active. If so print which thread
  1446. is active. Send the threads wakeup signal.
  1447. @return name of thread that is active or NULL */
  1448. UNIV_INTERN
  1449. const char*
  1450. srv_any_background_threads_are_active(void)
  1451. /*=======================================*/
  1452. {
  1453. const char* thread_active = NULL;
  1454. if (srv_read_only_mode) {
  1455. return(NULL);
  1456. } else if (srv_error_monitor_active) {
  1457. thread_active = "srv_error_monitor_thread";
  1458. } else if (lock_sys->timeout_thread_active) {
  1459. thread_active = "srv_lock_timeout thread";
  1460. } else if (srv_monitor_active) {
  1461. thread_active = "srv_monitor_thread";
  1462. } else if (srv_buf_dump_thread_active) {
  1463. thread_active = "buf_dump_thread";
  1464. } else if (srv_dict_stats_thread_active) {
  1465. thread_active = "dict_stats_thread";
  1466. }
  1467. os_event_set(srv_error_event);
  1468. os_event_set(srv_monitor_event);
  1469. os_event_set(srv_buf_dump_event);
  1470. os_event_set(lock_sys->timeout_event);
  1471. os_event_set(dict_stats_event);
  1472. return(thread_active);
  1473. }
  1474. /*******************************************************************//**
  1475. Tells the InnoDB server that there has been activity in the database
  1476. and wakes up the master thread if it is suspended (not sleeping). Used
  1477. in the MySQL interface. Note that there is a small chance that the master
  1478. thread stays suspended (we do not protect our operation with the
  1479. srv_sys_t->mutex, for performance reasons). */
  1480. UNIV_INTERN
  1481. void
  1482. srv_active_wake_master_thread(void)
  1483. /*===============================*/
  1484. {
  1485. if (srv_read_only_mode) {
  1486. return;
  1487. }
  1488. ut_ad(!srv_sys_mutex_own());
  1489. srv_inc_activity_count();
  1490. if (srv_sys->n_threads_active[SRV_MASTER] == 0) {
  1491. srv_slot_t* slot;
  1492. srv_sys_mutex_enter();
  1493. slot = &srv_sys->sys_threads[SRV_MASTER_SLOT];
  1494. /* Only if the master thread has been started. */
  1495. if (slot->in_use) {
  1496. ut_a(srv_slot_get_type(slot) == SRV_MASTER);
  1497. if (slot->suspended) {
  1498. slot->suspended = FALSE;
  1499. ++srv_sys->n_threads_active[SRV_MASTER];
  1500. os_event_set(slot->event);
  1501. }
  1502. }
  1503. srv_sys_mutex_exit();
  1504. }
  1505. }
  1506. /*******************************************************************//**
  1507. Tells the purge thread that there has been activity in the database
  1508. and wakes up the purge thread if it is suspended (not sleeping). Note
  1509. that there is a small chance that the purge thread stays suspended
  1510. (we do not protect our check with the srv_sys_t:mutex and the
  1511. purge_sys->latch, for performance reasons). */
  1512. UNIV_INTERN
  1513. void
  1514. srv_wake_purge_thread_if_not_active(void)
  1515. /*=====================================*/
  1516. {
  1517. ut_ad(!srv_sys_mutex_own());
  1518. if (purge_sys->state == PURGE_STATE_RUN
  1519. && srv_sys->n_threads_active[SRV_PURGE] == 0) {
  1520. srv_release_threads(SRV_PURGE, 1);
  1521. }
  1522. }
  1523. /*******************************************************************//**
  1524. Wakes up the master thread if it is suspended or being suspended. */
  1525. UNIV_INTERN
  1526. void
  1527. srv_wake_master_thread(void)
  1528. /*========================*/
  1529. {
  1530. ut_ad(!srv_sys_mutex_own());
  1531. srv_inc_activity_count();
  1532. srv_release_threads(SRV_MASTER, 1);
  1533. }
  1534. /*******************************************************************//**
  1535. Get current server activity count. We don't hold srv_sys::mutex while
  1536. reading this value as it is only used in heuristics.
  1537. @return activity count. */
  1538. UNIV_INTERN
  1539. ulint
  1540. srv_get_activity_count(void)
  1541. /*========================*/
  1542. {
  1543. return(srv_sys->activity_count);
  1544. }
  1545. /*******************************************************************//**
  1546. Check if there has been any activity.
  1547. @return FALSE if no change in activity counter. */
  1548. UNIV_INTERN
  1549. ibool
  1550. srv_check_activity(
  1551. /*===============*/
  1552. ulint old_activity_count) /*!< in: old activity count */
  1553. {
  1554. return(srv_sys->activity_count != old_activity_count);
  1555. }
  1556. /********************************************************************//**
  1557. The master thread is tasked to ensure that flush of log file happens
  1558. once every second in the background. This is to ensure that not more
  1559. than one second of trxs are lost in case of crash when
  1560. innodb_flush_logs_at_trx_commit != 1 */
  1561. static
  1562. void
  1563. srv_sync_log_buffer_in_background(void)
  1564. /*===================================*/
  1565. {
  1566. time_t current_time = time(NULL);
  1567. srv_main_thread_op_info = "flushing log";
  1568. if (difftime(current_time, srv_last_log_flush_time)
  1569. >= srv_flush_log_at_timeout) {
  1570. log_buffer_sync_in_background(TRUE);
  1571. srv_last_log_flush_time = current_time;
  1572. srv_log_writes_and_flush++;
  1573. }
  1574. }
  1575. /********************************************************************//**
  1576. Make room in the table cache by evicting an unused table.
  1577. @return number of tables evicted. */
  1578. static
  1579. ulint
  1580. srv_master_evict_from_table_cache(
  1581. /*==============================*/
  1582. ulint pct_check) /*!< in: max percent to check */
  1583. {
  1584. ulint n_tables_evicted = 0;
  1585. rw_lock_x_lock(&dict_operation_lock);
  1586. dict_mutex_enter_for_mysql();
  1587. n_tables_evicted = dict_make_room_in_cache(
  1588. innobase_get_table_cache_size(), pct_check);
  1589. dict_mutex_exit_for_mysql();
  1590. rw_lock_x_unlock(&dict_operation_lock);
  1591. return(n_tables_evicted);
  1592. }
  1593. /*********************************************************************//**
  1594. This function prints progress message every 60 seconds during server
  1595. shutdown, for any activities that master thread is pending on. */
  1596. static
  1597. void
  1598. srv_shutdown_print_master_pending(
  1599. /*==============================*/
  1600. ib_time_t* last_print_time, /*!< last time the function
  1601. print the message */
  1602. ulint n_tables_to_drop, /*!< number of tables to
  1603. be dropped */
  1604. ulint n_bytes_merged) /*!< number of change buffer
  1605. just merged */
  1606. {
  1607. ib_time_t current_time;
  1608. double time_elapsed;
  1609. current_time = ut_time();
  1610. time_elapsed = ut_difftime(current_time, *last_print_time);
  1611. if (time_elapsed > 60) {
  1612. *last_print_time = ut_time();
  1613. if (n_tables_to_drop) {
  1614. ut_print_timestamp(stderr);
  1615. fprintf(stderr, " InnoDB: Waiting for "
  1616. "%lu table(s) to be dropped\n",
  1617. (ulong) n_tables_to_drop);
  1618. }
  1619. /* Check change buffer merge, we only wait for change buffer
  1620. merge if it is a slow shutdown */
  1621. if (!srv_fast_shutdown && n_bytes_merged) {
  1622. ut_print_timestamp(stderr);
  1623. fprintf(stderr, " InnoDB: Waiting for change "
  1624. "buffer merge to complete\n"
  1625. " InnoDB: number of bytes of change buffer "
  1626. "just merged: %lu\n",
  1627. n_bytes_merged);
  1628. }
  1629. }
  1630. }
  1631. /*********************************************************************//**
  1632. Perform the tasks that the master thread is supposed to do when the
  1633. server is active. There are two types of tasks. The first category is
  1634. of such tasks which are performed at each inovcation of this function.
  1635. We assume that this function is called roughly every second when the
  1636. server is active. The second category is of such tasks which are
  1637. performed at some interval e.g.: purge, dict_LRU cleanup etc. */
  1638. static
  1639. void
  1640. srv_master_do_active_tasks(void)
  1641. /*============================*/
  1642. {
  1643. ib_time_t cur_time = ut_time();
  1644. ullint counter_time = ut_time_us(NULL);
  1645. /* First do the tasks that we are suppose to do at each
  1646. invocation of this function. */
  1647. ++srv_main_active_loops;
  1648. MONITOR_INC(MONITOR_MASTER_ACTIVE_LOOPS);
  1649. /* ALTER TABLE in MySQL requires on Unix that the table handler
  1650. can drop tables lazily after there no longer are SELECT
  1651. queries to them. */
  1652. srv_main_thread_op_info = "doing background drop tables";
  1653. row_drop_tables_for_mysql_in_background();
  1654. MONITOR_INC_TIME_IN_MICRO_SECS(
  1655. MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND, counter_time);
  1656. if (srv_shutdown_state > 0) {
  1657. return;
  1658. }
  1659. /* make sure that there is enough reusable space in the redo
  1660. log files */
  1661. srv_main_thread_op_info = "checking free log space";
  1662. log_free_check();
  1663. /* Do an ibuf merge */
  1664. srv_main_thread_op_info = "doing insert buffer merge";
  1665. counter_time = ut_time_us(NULL);
  1666. ibuf_contract_in_background(0, FALSE);
  1667. MONITOR_INC_TIME_IN_MICRO_SECS(
  1668. MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time);
  1669. /* Flush logs if needed */
  1670. srv_main_thread_op_info = "flushing log";
  1671. srv_sync_log_buffer_in_background();
  1672. MONITOR_INC_TIME_IN_MICRO_SECS(
  1673. MONITOR_SRV_LOG_FLUSH_MICROSECOND, counter_time);
  1674. /* Now see if various tasks that are performed at defined
  1675. intervals need to be performed. */
  1676. #ifdef MEM_PERIODIC_CHECK
  1677. /* Check magic numbers of every allocated mem block once in
  1678. SRV_MASTER_MEM_VALIDATE_INTERVAL seconds */
  1679. if (cur_time % SRV_MASTER_MEM_VALIDATE_INTERVAL == 0) {
  1680. mem_validate_all_blocks();
  1681. MONITOR_INC_TIME_IN_MICRO_SECS(
  1682. MONITOR_SRV_MEM_VALIDATE_MICROSECOND, counter_time);
  1683. }
  1684. #endif
  1685. if (srv_shutdown_state > 0) {
  1686. return;
  1687. }
  1688. if (srv_shutdown_state > 0) {
  1689. return;
  1690. }
  1691. if (cur_time % SRV_MASTER_DICT_LRU_INTERVAL == 0) {
  1692. srv_main_thread_op_info = "enforcing dict cache limit";
  1693. srv_master_evict_from_table_cache(50);
  1694. MONITOR_INC_TIME_IN_MICRO_SECS(
  1695. MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time);
  1696. }
  1697. if (srv_shutdown_state > 0) {
  1698. return;
  1699. }
  1700. /* Make a new checkpoint */
  1701. if (cur_time % SRV_MASTER_CHECKPOINT_INTERVAL == 0) {
  1702. srv_main_thread_op_info = "making checkpoint";
  1703. log_checkpoint(TRUE, FALSE);
  1704. MONITOR_INC_TIME_IN_MICRO_SECS(
  1705. MONITOR_SRV_CHECKPOINT_MICROSECOND, counter_time);
  1706. }
  1707. }
  1708. /*********************************************************************//**
  1709. Perform the tasks that the master thread is supposed to do whenever the
  1710. server is idle. We do check for the server state during this function
  1711. and if the server has entered the shutdown phase we may return from
  1712. the function without completing the required tasks.
  1713. Note that the server can move to active state when we are executing this
  1714. function but we don't check for that as we are suppose to perform more
  1715. or less same tasks when server is active. */
  1716. static
  1717. void
  1718. srv_master_do_idle_tasks(void)
  1719. /*==========================*/
  1720. {
  1721. ullint counter_time;
  1722. ++srv_main_idle_loops;
  1723. MONITOR_INC(MONITOR_MASTER_IDLE_LOOPS);
  1724. /* ALTER TABLE in MySQL requires on Unix that the table handler
  1725. can drop tables lazily after there no longer are SELECT
  1726. queries to them. */
  1727. counter_time = ut_time_us(NULL);
  1728. srv_main_thread_op_info = "doing background drop tables";
  1729. row_drop_tables_for_mysql_in_background();
  1730. MONITOR_INC_TIME_IN_MICRO_SECS(
  1731. MONITOR_SRV_BACKGROUND_DROP_TABLE_MICROSECOND,
  1732. counter_time);
  1733. if (srv_shutdown_state > 0) {
  1734. return;
  1735. }
  1736. /* make sure that there is enough reusable space in the redo
  1737. log files */
  1738. srv_main_thread_op_info = "checking free log space";
  1739. log_free_check();
  1740. /* Do an ibuf merge */
  1741. counter_time = ut_time_us(NULL);
  1742. srv_main_thread_op_info = "doing insert buffer merge";
  1743. ibuf_contract_in_background(0, TRUE);
  1744. MONITOR_INC_TIME_IN_MICRO_SECS(
  1745. MONITOR_SRV_IBUF_MERGE_MICROSECOND, counter_time);
  1746. if (srv_shutdown_state > 0) {
  1747. return;
  1748. }
  1749. srv_main_thread_op_info = "enforcing dict cache limit";
  1750. srv_master_evict_from_table_cache(100);
  1751. MONITOR_INC_TIME_IN_MICRO_SECS(
  1752. MONITOR_SRV_DICT_LRU_MICROSECOND, counter_time);
  1753. /* Flush logs if needed */
  1754. srv_sync_log_buffer_in_background();
  1755. MONITOR_INC_TIME_IN_MICRO_SECS(
  1756. MONITOR_SRV_LOG_FLUSH_MICROSECOND, counter_time);
  1757. if (srv_shutdown_state > 0) {
  1758. return;
  1759. }
  1760. /* Make a new checkpoint */
  1761. srv_main_thread_op_info = "making checkpoint";
  1762. log_checkpoint(TRUE, FALSE);
  1763. MONITOR_INC_TIME_IN_MICRO_SECS(MONITOR_SRV_CHECKPOINT_MICROSECOND,
  1764. counter_time);
  1765. }
  1766. /*********************************************************************//**
  1767. Perform the tasks during shutdown. The tasks that we do at shutdown
  1768. depend on srv_fast_shutdown:
  1769. 2 => very fast shutdown => do no book keeping
  1770. 1 => normal shutdown => clear drop table queue and make checkpoint
  1771. 0 => slow shutdown => in addition to above do complete purge and ibuf
  1772. merge
  1773. @return TRUE if some work was done. FALSE otherwise */
  1774. static
  1775. ibool
  1776. srv_master_do_shutdown_tasks(
  1777. /*=========================*/
  1778. ib_time_t* last_print_time)/*!< last time the function
  1779. print the message */
  1780. {
  1781. ulint n_bytes_merged = 0;
  1782. ulint n_tables_to_drop = 0;
  1783. ut_ad(!srv_read_only_mode);
  1784. ++srv_main_shutdown_loops;
  1785. ut_a(srv_shutdown_state > 0);
  1786. /* In very fast shutdown none of the following is necessary */
  1787. if (srv_fast_shutdown == 2) {
  1788. return(FALSE);
  1789. }
  1790. /* ALTER TABLE in MySQL requires on Unix that the table handler
  1791. can drop tables lazily after there no longer are SELECT
  1792. queries to them. */
  1793. srv_main_thread_op_info = "doing background drop tables";
  1794. n_tables_to_drop = row_drop_tables_for_mysql_in_background();
  1795. /* make sure that there is enough reusable space in the redo
  1796. log files */
  1797. srv_main_thread_op_info = "checking free log space";
  1798. log_free_check();
  1799. /* In case of normal shutdown we don't do ibuf merge or purge */
  1800. if (srv_fast_shutdown == 1) {
  1801. goto func_exit;
  1802. }
  1803. /* Do an ibuf merge */
  1804. srv_main_thread_op_info = "doing insert buffer merge";
  1805. n_bytes_merged = ibuf_contract_in_background(0, TRUE);
  1806. /* Flush logs if needed */
  1807. srv_sync_log_buffer_in_background();
  1808. func_exit:
  1809. /* Make a new checkpoint about once in 10 seconds */
  1810. srv_main_thread_op_info = "making checkpoint";
  1811. log_checkpoint(TRUE, FALSE);
  1812. /* Print progress message every 60 seconds during shutdown */
  1813. if (srv_shutdown_state > 0 && srv_print_verbose_log) {
  1814. srv_shutdown_print_master_pending(
  1815. last_print_time, n_tables_to_drop, n_bytes_merged);
  1816. }
  1817. return(n_bytes_merged || n_tables_to_drop);
  1818. }
  1819. /*********************************************************************//**
  1820. Puts master thread to sleep. At this point we are using polling to
  1821. service various activities. Master thread sleeps for one second before
  1822. checking the state of the server again */
  1823. static
  1824. void
  1825. srv_master_sleep(void)
  1826. /*==================*/
  1827. {
  1828. srv_main_thread_op_info = "sleeping";
  1829. os_thread_sleep(1000000);
  1830. srv_main_thread_op_info = "";
  1831. }
  1832. /*********************************************************************//**
  1833. The master thread controlling the server.
  1834. @return a dummy parameter */
  1835. extern "C" UNIV_INTERN
  1836. os_thread_ret_t
  1837. DECLARE_THREAD(srv_master_thread)(
  1838. /*==============================*/
  1839. void* arg __attribute__((unused)))
  1840. /*!< in: a dummy parameter required by
  1841. os_thread_create */
  1842. {
  1843. srv_slot_t* slot;
  1844. ulint old_activity_count = srv_get_activity_count();
  1845. ib_time_t last_print_time;
  1846. ut_ad(!srv_read_only_mode);
  1847. #ifdef UNIV_DEBUG_THREAD_CREATION
  1848. fprintf(stderr, "Master thread starts, id %lu\n",
  1849. os_thread_pf(os_thread_get_curr_id()));
  1850. #endif /* UNIV_DEBUG_THREAD_CREATION */
  1851. #ifdef UNIV_PFS_THREAD
  1852. pfs_register_thread(srv_master_thread_key);
  1853. #endif /* UNIV_PFS_THREAD */
  1854. srv_main_thread_process_no = os_proc_get_number();
  1855. srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());
  1856. slot = srv_reserve_slot(SRV_MASTER);
  1857. ut_a(slot == srv_sys->sys_threads);
  1858. last_print_time = ut_time();
  1859. loop:
  1860. if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
  1861. goto suspend_thread;
  1862. }
  1863. while (srv_shutdown_state == SRV_SHUTDOWN_NONE) {
  1864. srv_master_sleep();
  1865. MONITOR_INC(MONITOR_MASTER_THREAD_SLEEP);
  1866. if (srv_check_activity(old_activity_count)) {
  1867. old_activity_count = srv_get_activity_count();
  1868. srv_master_do_active_tasks();
  1869. } else {
  1870. srv_master_do_idle_tasks();
  1871. }
  1872. }
  1873. while (srv_master_do_shutdown_tasks(&last_print_time)) {
  1874. /* Shouldn't loop here in case of very fast shutdown */
  1875. ut_ad(srv_fast_shutdown < 2);
  1876. }
  1877. suspend_thread:
  1878. srv_main_thread_op_info = "suspending";
  1879. srv_suspend_thread(slot);
  1880. /* DO NOT CHANGE THIS STRING. innobase_start_or_create_for_mysql()
  1881. waits for database activity to die down when converting < 4.1.x
  1882. databases, and relies on this string being exactly as it is. InnoDB
  1883. manual also mentions this string in several places. */
  1884. srv_main_thread_op_info = "waiting for server activity";
  1885. os_event_wait(slot->event);
  1886. if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
  1887. os_thread_exit(NULL);
  1888. }
  1889. goto loop;
  1890. OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */
  1891. }
  1892. /*********************************************************************//**
  1893. Check if purge should stop.
  1894. @return true if it should shutdown. */
  1895. static
  1896. bool
  1897. srv_purge_should_exit(
  1898. /*==============*/
  1899. ulint n_purged) /*!< in: pages purged in last batch */
  1900. {
  1901. switch (srv_shutdown_state) {
  1902. case SRV_SHUTDOWN_NONE:
  1903. /* Normal operation. */
  1904. break;
  1905. case SRV_SHUTDOWN_CLEANUP:
  1906. case SRV_SHUTDOWN_EXIT_THREADS:
  1907. /* Exit unless slow shutdown requested or all done. */
  1908. return(srv_fast_shutdown != 0 || n_purged == 0);
  1909. case SRV_SHUTDOWN_LAST_PHASE:
  1910. case SRV_SHUTDOWN_FLUSH_PHASE:
  1911. ut_error;
  1912. }
  1913. return(false);
  1914. }
  1915. /*********************************************************************//**
  1916. Fetch and execute a task from the work queue.
  1917. @return true if a task was executed */
  1918. static
  1919. bool
  1920. srv_task_execute(void)
  1921. /*==================*/
  1922. {
  1923. que_thr_t* thr = NULL;
  1924. ut_ad(!srv_read_only_mode);
  1925. ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
  1926. mutex_enter(&srv_sys->tasks_mutex);
  1927. if (UT_LIST_GET_LEN(srv_sys->tasks) > 0) {
  1928. thr = UT_LIST_GET_FIRST(srv_sys->tasks);
  1929. ut_a(que_node_get_type(thr->child) == QUE_NODE_PURGE);
  1930. UT_LIST_REMOVE(queue, srv_sys->tasks, thr);
  1931. }
  1932. mutex_exit(&srv_sys->tasks_mutex);
  1933. if (thr != NULL) {
  1934. que_run_threads(thr);
  1935. os_atomic_inc_ulint(
  1936. &purge_sys->bh_mutex, &purge_sys->n_completed, 1);
  1937. }
  1938. return(thr != NULL);
  1939. }
  1940. /*********************************************************************//**
  1941. Worker thread that reads tasks from the work queue and executes them.
  1942. @return a dummy parameter */
  1943. extern "C" UNIV_INTERN
  1944. os_thread_ret_t
  1945. DECLARE_THREAD(srv_worker_thread)(
  1946. /*==============================*/
  1947. void* arg __attribute__((unused))) /*!< in: a dummy parameter
  1948. required by os_thread_create */
  1949. {
  1950. srv_slot_t* slot;
  1951. ut_ad(!srv_read_only_mode);
  1952. ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
  1953. #ifdef UNIV_DEBUG_THREAD_CREATION
  1954. ut_print_timestamp(stderr);
  1955. fprintf(stderr, " InnoDB: worker thread starting, id %lu\n",
  1956. os_thread_pf(os_thread_get_curr_id()));
  1957. #endif /* UNIV_DEBUG_THREAD_CREATION */
  1958. slot = srv_reserve_slot(SRV_WORKER);
  1959. ut_a(srv_n_purge_threads > 1);
  1960. srv_sys_mutex_enter();
  1961. ut_a(srv_sys->n_threads_active[SRV_WORKER] < srv_n_purge_threads);
  1962. srv_sys_mutex_exit();
  1963. /* We need to ensure that the worker threads exit after the
  1964. purge coordinator thread. Otherwise the purge coordinaor can
  1965. end up waiting forever in trx_purge_wait_for_workers_to_complete() */
  1966. do {
  1967. srv_suspend_thread(slot);
  1968. os_event_wait(slot->event);
  1969. if (srv_task_execute()) {
  1970. /* If there are tasks in the queue, wakeup
  1971. the purge coordinator thread. */
  1972. srv_wake_purge_thread_if_not_active();
  1973. }
  1974. /* Note: we are checking the state without holding the
  1975. purge_sys->latch here. */
  1976. } while (purge_sys->state != PURGE_STATE_EXIT);
  1977. srv_free_slot(slot);
  1978. rw_lock_x_lock(&purge_sys->latch);
  1979. ut_a(!purge_sys->running);
  1980. ut_a(purge_sys->state == PURGE_STATE_EXIT);
  1981. ut_a(srv_shutdown_state > SRV_SHUTDOWN_NONE);
  1982. rw_lock_x_unlock(&purge_sys->latch);
  1983. #ifdef UNIV_DEBUG_THREAD_CREATION
  1984. ut_print_timestamp(stderr);
  1985. fprintf(stderr, " InnoDB: Purge worker thread exiting, id %lu\n",
  1986. os_thread_pf(os_thread_get_curr_id()));
  1987. #endif /* UNIV_DEBUG_THREAD_CREATION */
  1988. /* We count the number of threads in os_thread_exit(). A created
  1989. thread should always use that to exit and not use return() to exit. */
  1990. os_thread_exit(NULL);
  1991. OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */
  1992. }
  1993. /*********************************************************************//**
  1994. Do the actual purge operation.
  1995. @return length of history list before the last purge batch. */
  1996. static
  1997. ulint
  1998. srv_do_purge(
  1999. /*=========*/
  2000. ulint n_threads, /*!< in: number of threads to use */
  2001. ulint* n_total_purged) /*!< in/out: total pages purged */
  2002. {
  2003. ulint n_pages_purged;
  2004. static ulint count = 0;
  2005. static ulint n_use_threads = 0;
  2006. static ulint rseg_history_len = 0;
  2007. ulint old_activity_count = srv_get_activity_count();
  2008. ut_a(n_threads > 0);
  2009. ut_ad(!srv_read_only_mode);
  2010. /* Purge until there are no more records to purge and there is
  2011. no change in configuration or server state. If the user has
  2012. configured more than one purge thread then we treat that as a
  2013. pool of threads and only use the extra threads if purge can't
  2014. keep up with updates. */
  2015. if (n_use_threads == 0) {
  2016. n_use_threads = n_threads;
  2017. }
  2018. do {
  2019. if (trx_sys->rseg_history_len > rseg_history_len
  2020. || (srv_max_purge_lag > 0
  2021. && rseg_history_len > srv_max_purge_lag)) {
  2022. /* History length is now longer than what it was
  2023. when we took the last snapshot. Use more threads. */
  2024. if (n_use_threads < n_threads) {
  2025. ++n_use_threads;
  2026. }
  2027. } else if (srv_check_activity(old_activity_count)
  2028. && n_use_threads > 1) {
  2029. /* History length same or smaller since last snapshot,
  2030. use fewer threads. */
  2031. --n_use_threads;
  2032. old_activity_count = srv_get_activity_count();
  2033. }
  2034. /* Ensure that the purge threads are less than what
  2035. was configured. */
  2036. ut_a(n_use_threads > 0);
  2037. ut_a(n_use_threads <= n_threads);
  2038. /* Take a snapshot of the history list before purge. */
  2039. if ((rseg_history_len = trx_sys->rseg_history_len) == 0) {
  2040. break;
  2041. }
  2042. n_pages_purged = trx_purge(
  2043. n_use_threads, srv_purge_batch_size,
  2044. (++count % TRX_SYS_N_RSEGS) == 0);
  2045. *n_total_purged += n_pages_purged;
  2046. } while (!srv_purge_should_exit(n_pages_purged)
  2047. && n_pages_purged > 0
  2048. && purge_sys->state == PURGE_STATE_RUN);
  2049. return(rseg_history_len);
  2050. }
  2051. /*********************************************************************//**
  2052. Suspend the purge coordinator thread. */
  2053. static
  2054. void
  2055. srv_purge_coordinator_suspend(
  2056. /*==========================*/
  2057. srv_slot_t* slot, /*!< in/out: Purge coordinator
  2058. thread slot */
  2059. ulint rseg_history_len) /*!< in: history list length
  2060. before last purge */
  2061. {
  2062. ut_ad(!srv_read_only_mode);
  2063. ut_a(slot->type == SRV_PURGE);
  2064. bool stop = false;
  2065. /** Maximum wait time on the purge event, in micro-seconds. */
  2066. static const ulint SRV_PURGE_MAX_TIMEOUT = 10000;
  2067. ib_int64_t sig_count = srv_suspend_thread(slot);
  2068. do {
  2069. ulint ret;
  2070. rw_lock_x_lock(&purge_sys->latch);
  2071. purge_sys->running = false;
  2072. rw_lock_x_unlock(&purge_sys->latch);
  2073. /* We don't wait right away on the the non-timed wait because
  2074. we want to signal the thread that wants to suspend purge. */
  2075. if (stop) {
  2076. os_event_wait_low(slot->event, sig_count);
  2077. ret = 0;
  2078. } else if (rseg_history_len <= trx_sys->rseg_history_len) {
  2079. ret = os_event_wait_time_low(
  2080. slot->event, SRV_PURGE_MAX_TIMEOUT, sig_count);
  2081. } else {
  2082. /* We don't want to waste time waiting, if the
  2083. history list increased by the time we got here,
  2084. unless purge has been stopped. */
  2085. ret = 0;
  2086. }
  2087. srv_sys_mutex_enter();
  2088. /* The thread can be in state !suspended after the timeout
  2089. but before this check if another thread sent a wakeup signal. */
  2090. if (slot->suspended) {
  2091. slot->suspended = FALSE;
  2092. ++srv_sys->n_threads_active[slot->type];
  2093. ut_a(srv_sys->n_threads_active[slot->type] == 1);
  2094. }
  2095. srv_sys_mutex_exit();
  2096. sig_count = srv_suspend_thread(slot);
  2097. rw_lock_x_lock(&purge_sys->latch);
  2098. stop = (srv_shutdown_state == SRV_SHUTDOWN_NONE
  2099. && purge_sys->state == PURGE_STATE_STOP);
  2100. if (!stop) {
  2101. ut_a(purge_sys->n_stop == 0);
  2102. purge_sys->running = true;
  2103. } else {
  2104. ut_a(purge_sys->n_stop > 0);
  2105. /* Signal that we are suspended. */
  2106. os_event_set(purge_sys->event);
  2107. }
  2108. rw_lock_x_unlock(&purge_sys->latch);
  2109. if (ret == OS_SYNC_TIME_EXCEEDED) {
  2110. /* No new records added since wait started then simply
  2111. wait for new records. The magic number 5000 is an
  2112. approximation for the case where we have cached UNDO
  2113. log records which prevent truncate of the UNDO
  2114. segments. */
  2115. if (rseg_history_len == trx_sys->rseg_history_len
  2116. && trx_sys->rseg_history_len < 5000) {
  2117. stop = true;
  2118. }
  2119. }
  2120. } while (stop);
  2121. srv_sys_mutex_enter();
  2122. if (slot->suspended) {
  2123. slot->suspended = FALSE;
  2124. ++srv_sys->n_threads_active[slot->type];
  2125. ut_a(srv_sys->n_threads_active[slot->type] == 1);
  2126. }
  2127. srv_sys_mutex_exit();
  2128. }
  2129. /*********************************************************************//**
  2130. Purge coordinator thread that schedules the purge tasks.
  2131. @return a dummy parameter */
  2132. extern "C" UNIV_INTERN
  2133. os_thread_ret_t
  2134. DECLARE_THREAD(srv_purge_coordinator_thread)(
  2135. /*=========================================*/
  2136. void* arg __attribute__((unused))) /*!< in: a dummy parameter
  2137. required by os_thread_create */
  2138. {
  2139. srv_slot_t* slot;
  2140. ulint n_total_purged = ULINT_UNDEFINED;
  2141. ut_ad(!srv_read_only_mode);
  2142. ut_a(srv_n_purge_threads >= 1);
  2143. ut_a(trx_purge_state() == PURGE_STATE_INIT);
  2144. ut_a(srv_force_recovery < SRV_FORCE_NO_BACKGROUND);
  2145. rw_lock_x_lock(&purge_sys->latch);
  2146. purge_sys->running = true;
  2147. purge_sys->state = PURGE_STATE_RUN;
  2148. rw_lock_x_unlock(&purge_sys->latch);
  2149. #ifdef UNIV_PFS_THREAD
  2150. pfs_register_thread(srv_purge_thread_key);
  2151. #endif /* UNIV_PFS_THREAD */
  2152. #ifdef UNIV_DEBUG_THREAD_CREATION
  2153. ut_print_timestamp(stderr);
  2154. fprintf(stderr, " InnoDB: Purge coordinator thread created, id %lu\n",
  2155. os_thread_pf(os_thread_get_curr_id()));
  2156. #endif /* UNIV_DEBUG_THREAD_CREATION */
  2157. slot = srv_reserve_slot(SRV_PURGE);
  2158. ulint rseg_history_len = trx_sys->rseg_history_len;
  2159. do {
  2160. /* If there are no records to purge or the last
  2161. purge didn't purge any records then wait for activity. */
  2162. if (srv_shutdown_state == SRV_SHUTDOWN_NONE
  2163. && (purge_sys->state == PURGE_STATE_STOP
  2164. || n_total_purged == 0)) {
  2165. srv_purge_coordinator_suspend(slot, rseg_history_len);
  2166. }
  2167. if (srv_purge_should_exit(n_total_purged)) {
  2168. ut_a(!slot->suspended);
  2169. break;
  2170. }
  2171. n_total_purged = 0;
  2172. rseg_history_len = srv_do_purge(
  2173. srv_n_purge_threads, &n_total_purged);
  2174. } while (!srv_purge_should_exit(n_total_purged));
  2175. /* Ensure that we don't jump out of the loop unless the
  2176. exit condition is satisfied. */
  2177. ut_a(srv_purge_should_exit(n_total_purged));
  2178. ulint n_pages_purged = ULINT_MAX;
  2179. /* Ensure that all records are purged if it is not a fast shutdown.
  2180. This covers the case where a record can be added after we exit the
  2181. loop above. */
  2182. while (srv_fast_shutdown == 0 && n_pages_purged > 0) {
  2183. n_pages_purged = trx_purge(1, srv_purge_batch_size, false);
  2184. }
  2185. /* This trx_purge is called to remove any undo records (added by
  2186. background threads) after completion of the above loop. When
  2187. srv_fast_shutdown != 0, a large batch size can cause significant
  2188. delay in shutdown ,so reducing the batch size to magic number 20
  2189. (which was default in 5.5), which we hope will be sufficient to
  2190. remove all the undo records */
  2191. const uint temp_batch_size = 20;
  2192. n_pages_purged = trx_purge(1, srv_purge_batch_size <= temp_batch_size
  2193. ? srv_purge_batch_size : temp_batch_size,
  2194. true);
  2195. ut_a(n_pages_purged == 0 || srv_fast_shutdown != 0);
  2196. /* The task queue should always be empty, independent of fast
  2197. shutdown state. */
  2198. ut_a(srv_get_task_queue_length() == 0);
  2199. srv_free_slot(slot);
  2200. /* Note that we are shutting down. */
  2201. rw_lock_x_lock(&purge_sys->latch);
  2202. purge_sys->state = PURGE_STATE_EXIT;
  2203. purge_sys->running = false;
  2204. rw_lock_x_unlock(&purge_sys->latch);
  2205. #ifdef UNIV_DEBUG_THREAD_CREATION
  2206. ut_print_timestamp(stderr);
  2207. fprintf(stderr, " InnoDB: Purge coordinator exiting, id %lu\n",
  2208. os_thread_pf(os_thread_get_curr_id()));
  2209. #endif /* UNIV_DEBUG_THREAD_CREATION */
  2210. /* Ensure that all the worker threads quit. */
  2211. if (srv_n_purge_threads > 1) {
  2212. srv_release_threads(SRV_WORKER, srv_n_purge_threads - 1);
  2213. }
  2214. /* We count the number of threads in os_thread_exit(). A created
  2215. thread should always use that to exit and not use return() to exit. */
  2216. os_thread_exit(NULL);
  2217. OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */
  2218. }
  2219. /**********************************************************************//**
  2220. Enqueues a task to server task queue and releases a worker thread, if there
  2221. is a suspended one. */
  2222. UNIV_INTERN
  2223. void
  2224. srv_que_task_enqueue_low(
  2225. /*=====================*/
  2226. que_thr_t* thr) /*!< in: query thread */
  2227. {
  2228. ut_ad(!srv_read_only_mode);
  2229. mutex_enter(&srv_sys->tasks_mutex);
  2230. UT_LIST_ADD_LAST(queue, srv_sys->tasks, thr);
  2231. mutex_exit(&srv_sys->tasks_mutex);
  2232. srv_release_threads(SRV_WORKER, 1);
  2233. }
  2234. /**********************************************************************//**
  2235. Get count of tasks in the queue.
  2236. @return number of tasks in queue */
  2237. UNIV_INTERN
  2238. ulint
  2239. srv_get_task_queue_length(void)
  2240. /*===========================*/
  2241. {
  2242. ulint n_tasks;
  2243. ut_ad(!srv_read_only_mode);
  2244. mutex_enter(&srv_sys->tasks_mutex);
  2245. n_tasks = UT_LIST_GET_LEN(srv_sys->tasks);
  2246. mutex_exit(&srv_sys->tasks_mutex);
  2247. return(n_tasks);
  2248. }
  2249. /**********************************************************************//**
  2250. Wakeup the purge threads. */
  2251. UNIV_INTERN
  2252. void
  2253. srv_purge_wakeup(void)
  2254. /*==================*/
  2255. {
  2256. ut_ad(!srv_read_only_mode);
  2257. if (srv_force_recovery < SRV_FORCE_NO_BACKGROUND) {
  2258. srv_release_threads(SRV_PURGE, 1);
  2259. if (srv_n_purge_threads > 1) {
  2260. ulint n_workers = srv_n_purge_threads - 1;
  2261. srv_release_threads(SRV_WORKER, n_workers);
  2262. }
  2263. }
  2264. }