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.

2581 lines
72 KiB

20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
20 years ago
  1. /******************************************************
  2. The database server main program
  3. NOTE: SQL Server 7 uses something which the documentation
  4. calls user mode scheduled threads (UMS threads). One such
  5. thread is usually allocated per processor. Win32
  6. documentation does not know any UMS threads, which suggests
  7. that the concept is internal to SQL Server 7. It may mean that
  8. SQL Server 7 does all the scheduling of threads itself, even
  9. in i/o waits. We should maybe modify InnoDB to use the same
  10. technique, because thread switches within NT may be too slow.
  11. SQL Server 7 also mentions fibers, which are cooperatively
  12. scheduled threads. They can boost performance by 5 %,
  13. according to the Delaney and Soukup's book.
  14. Windows 2000 will have something called thread pooling
  15. (see msdn website), which we could possibly use.
  16. Another possibility could be to use some very fast user space
  17. thread library. This might confuse NT though.
  18. (c) 1995 Innobase Oy
  19. Created 10/8/1995 Heikki Tuuri
  20. *******************************************************/
  21. /* Dummy comment */
  22. #include "srv0srv.h"
  23. #include "ut0mem.h"
  24. #include "os0proc.h"
  25. #include "mem0mem.h"
  26. #include "mem0pool.h"
  27. #include "sync0sync.h"
  28. #include "thr0loc.h"
  29. #include "que0que.h"
  30. #include "srv0que.h"
  31. #include "log0recv.h"
  32. #include "pars0pars.h"
  33. #include "usr0sess.h"
  34. #include "lock0lock.h"
  35. #include "trx0purge.h"
  36. #include "ibuf0ibuf.h"
  37. #include "buf0flu.h"
  38. #include "btr0sea.h"
  39. #include "dict0load.h"
  40. #include "dict0boot.h"
  41. #include "srv0start.h"
  42. #include "row0mysql.h"
  43. /* This is set to TRUE if the MySQL user has set it in MySQL; currently
  44. affects only FOREIGN KEY definition parsing */
  45. ibool srv_lower_case_table_names = FALSE;
  46. /* The following counter is incremented whenever there is some user activity
  47. in the server */
  48. ulint srv_activity_count = 0;
  49. /* The following is the maximum allowed duration of a lock wait. */
  50. ulint srv_fatal_semaphore_wait_threshold = 600;
  51. /* How much data manipulation language (DML) statements need to be delayed,
  52. in microseconds, in order to reduce the lagging of the purge thread. */
  53. ulint srv_dml_needed_delay = 0;
  54. ibool srv_lock_timeout_and_monitor_active = FALSE;
  55. ibool srv_error_monitor_active = FALSE;
  56. const char* srv_main_thread_op_info = "";
  57. /* Prefix used by MySQL to indicate pre-5.1 table name encoding */
  58. const char srv_mysql50_table_name_prefix[9] = "#mysql50#";
  59. /* Server parameters which are read from the initfile */
  60. /* The following three are dir paths which are catenated before file
  61. names, where the file name itself may also contain a path */
  62. char* srv_data_home = NULL;
  63. #ifdef UNIV_LOG_ARCHIVE
  64. char* srv_arch_dir = NULL;
  65. #endif /* UNIV_LOG_ARCHIVE */
  66. ibool srv_file_per_table = FALSE; /* store to its own file each table
  67. created by an user; data dictionary
  68. tables are in the system tablespace
  69. 0 */
  70. ibool srv_locks_unsafe_for_binlog = FALSE; /* Place locks to
  71. records only i.e. do
  72. not use next-key
  73. locking except on
  74. duplicate key checking
  75. and foreign key
  76. checking */
  77. ulint srv_n_data_files = 0;
  78. char** srv_data_file_names = NULL;
  79. ulint* srv_data_file_sizes = NULL; /* size in database pages */
  80. ibool srv_auto_extend_last_data_file = FALSE; /* if TRUE, then we
  81. auto-extend the last data
  82. file */
  83. ulint srv_last_file_size_max = 0; /* if != 0, this tells
  84. the max size auto-extending
  85. may increase the last data
  86. file size */
  87. ulong srv_auto_extend_increment = 8; /* If the last data file is
  88. auto-extended, we add this
  89. many pages to it at a time */
  90. ulint* srv_data_file_is_raw_partition = NULL;
  91. /* If the following is TRUE we do not allow inserts etc. This protects
  92. the user from forgetting the 'newraw' keyword to my.cnf */
  93. ibool srv_created_new_raw = FALSE;
  94. char** srv_log_group_home_dirs = NULL;
  95. ulint srv_n_log_groups = ULINT_MAX;
  96. ulint srv_n_log_files = ULINT_MAX;
  97. ulint srv_log_file_size = ULINT_MAX; /* size in database pages */
  98. ulint srv_log_buffer_size = ULINT_MAX; /* size in database pages */
  99. ulong srv_flush_log_at_trx_commit = 1;
  100. byte srv_latin1_ordering[256] /* The sort order table of the latin1
  101. character set. The following table is
  102. the MySQL order as of Feb 10th, 2002 */
  103. = {
  104. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
  105. , 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
  106. , 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17
  107. , 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
  108. , 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27
  109. , 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F
  110. , 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37
  111. , 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
  112. , 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
  113. , 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F
  114. , 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57
  115. , 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F
  116. , 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
  117. , 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F
  118. , 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57
  119. , 0x58, 0x59, 0x5A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F
  120. , 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87
  121. , 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F
  122. , 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97
  123. , 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F
  124. , 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7
  125. , 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF
  126. , 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7
  127. , 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF
  128. , 0x41, 0x41, 0x41, 0x41, 0x5C, 0x5B, 0x5C, 0x43
  129. , 0x45, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x49
  130. , 0x44, 0x4E, 0x4F, 0x4F, 0x4F, 0x4F, 0x5D, 0xD7
  131. , 0xD8, 0x55, 0x55, 0x55, 0x59, 0x59, 0xDE, 0xDF
  132. , 0x41, 0x41, 0x41, 0x41, 0x5C, 0x5B, 0x5C, 0x43
  133. , 0x45, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x49
  134. , 0x44, 0x4E, 0x4F, 0x4F, 0x4F, 0x4F, 0x5D, 0xF7
  135. , 0xD8, 0x55, 0x55, 0x55, 0x59, 0x59, 0xDE, 0xFF
  136. };
  137. ulong srv_buf_pool_size = ULINT_MAX; /* requested size
  138. in kilobytes */
  139. ulong srv_buf_pool_old_size; /* previously requested size */
  140. ulong srv_buf_pool_curr_size = 0; /* current size
  141. in kilobytes */
  142. ulint srv_mem_pool_size = ULINT_MAX; /* size in bytes */
  143. ulint srv_lock_table_size = ULINT_MAX;
  144. ulint srv_n_file_io_threads = ULINT_MAX;
  145. #ifdef UNIV_LOG_ARCHIVE
  146. ibool srv_log_archive_on = FALSE;
  147. ibool srv_archive_recovery = 0;
  148. dulint srv_archive_recovery_limit_lsn;
  149. #endif /* UNIV_LOG_ARCHIVE */
  150. ulint srv_lock_wait_timeout = 1024 * 1024 * 1024;
  151. char* srv_file_flush_method_str = NULL;
  152. ulint srv_unix_file_flush_method = SRV_UNIX_FDATASYNC;
  153. ulint srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;
  154. ulint srv_max_n_open_files = 300;
  155. /* The InnoDB main thread tries to keep the ratio of modified pages
  156. in the buffer pool to all database pages in the buffer pool smaller than
  157. the following number. But it is not guaranteed that the value stays below
  158. that during a time of heavy update/insert activity. */
  159. ulong srv_max_buf_pool_modified_pct = 90;
  160. /* variable counts amount of data read in total (in bytes) */
  161. ulint srv_data_read = 0;
  162. /* here we count the amount of data written in total (in bytes) */
  163. ulint srv_data_written = 0;
  164. /* the number of the log write requests done */
  165. ulint srv_log_write_requests = 0;
  166. /* the number of physical writes to the log performed */
  167. ulint srv_log_writes = 0;
  168. /* amount of data written to the log files in bytes */
  169. ulint srv_os_log_written = 0;
  170. /* amount of writes being done to the log files */
  171. ulint srv_os_log_pending_writes = 0;
  172. /* we increase this counter, when there we don't have enough space in the
  173. log buffer and have to flush it */
  174. ulint srv_log_waits = 0;
  175. /* this variable counts the amount of times, when the doublewrite buffer
  176. was flushed */
  177. ulint srv_dblwr_writes = 0;
  178. /* here we store the number of pages that have been flushed to the
  179. doublewrite buffer */
  180. ulint srv_dblwr_pages_written = 0;
  181. /* in this variable we store the number of write requests issued */
  182. ulint srv_buf_pool_write_requests = 0;
  183. /* here we store the number of times when we had to wait for a free page
  184. in the buffer pool. It happens when the buffer pool is full and we need
  185. to make a flush, in order to be able to read or create a page. */
  186. ulint srv_buf_pool_wait_free = 0;
  187. /* variable to count the number of pages that were written from buffer
  188. pool to the disk */
  189. ulint srv_buf_pool_flushed = 0;
  190. /* variable to count the number of buffer pool reads that led to the
  191. reading of a disk page */
  192. ulint srv_buf_pool_reads = 0;
  193. /* variable to count the number of sequential read-aheads */
  194. ulint srv_read_ahead_seq = 0;
  195. /* variable to count the number of random read-aheads */
  196. ulint srv_read_ahead_rnd = 0;
  197. /* structure to pass status variables to MySQL */
  198. export_struc export_vars;
  199. /* If the following is != 0 we do not allow inserts etc. This protects
  200. the user from forgetting the innodb_force_recovery keyword to my.cnf */
  201. ulint srv_force_recovery = 0;
  202. /*-----------------------*/
  203. /* We are prepared for a situation that we have this many threads waiting for
  204. a semaphore inside InnoDB. innobase_start_or_create_for_mysql() sets the
  205. value. */
  206. ulint srv_max_n_threads = 0;
  207. /* The following controls how many threads we let inside InnoDB concurrently:
  208. threads waiting for locks are not counted into the number because otherwise
  209. we could get a deadlock. MySQL creates a thread for each user session, and
  210. semaphore contention and convoy problems can occur withput this restriction.
  211. Value 10 should be good if there are less than 4 processors + 4 disks in the
  212. computer. Bigger computers need bigger values. Value 0 will disable the
  213. concurrency check. */
  214. ulong srv_thread_concurrency = 0;
  215. ulong srv_commit_concurrency = 0;
  216. os_fast_mutex_t srv_conc_mutex; /* this mutex protects srv_conc data
  217. structures */
  218. lint srv_conc_n_threads = 0; /* number of OS threads currently
  219. inside InnoDB; it is not an error
  220. if this drops temporarily below zero
  221. because we do not demand that every
  222. thread increments this, but a thread
  223. waiting for a lock decrements this
  224. temporarily */
  225. ulint srv_conc_n_waiting_threads = 0; /* number of OS threads waiting in the
  226. FIFO for a permission to enter InnoDB
  227. */
  228. typedef struct srv_conc_slot_struct srv_conc_slot_t;
  229. struct srv_conc_slot_struct{
  230. os_event_t event; /* event to wait */
  231. ibool reserved; /* TRUE if slot
  232. reserved */
  233. ibool wait_ended; /* TRUE when another
  234. thread has already set
  235. the event and the
  236. thread in this slot is
  237. free to proceed; but
  238. reserved may still be
  239. TRUE at that point */
  240. UT_LIST_NODE_T(srv_conc_slot_t) srv_conc_queue; /* queue node */
  241. };
  242. UT_LIST_BASE_NODE_T(srv_conc_slot_t) srv_conc_queue; /* queue of threads
  243. waiting to get in */
  244. srv_conc_slot_t* srv_conc_slots; /* array of wait
  245. slots */
  246. /* Number of times a thread is allowed to enter InnoDB within the same
  247. SQL query after it has once got the ticket at srv_conc_enter_innodb */
  248. #define SRV_FREE_TICKETS_TO_ENTER srv_n_free_tickets_to_enter
  249. #define SRV_THREAD_SLEEP_DELAY srv_thread_sleep_delay
  250. /*-----------------------*/
  251. /* If the following is set to 1 then we do not run purge and insert buffer
  252. merge to completion before shutdown. If it is set to 2, do not even flush the
  253. buffer pool to data files at the shutdown: we effectively 'crash'
  254. InnoDB (but lose no committed transactions). */
  255. ulint srv_fast_shutdown = 0;
  256. /* Generate a innodb_status.<pid> file */
  257. ibool srv_innodb_status = FALSE;
  258. ibool srv_use_doublewrite_buf = TRUE;
  259. ibool srv_use_checksums = TRUE;
  260. ibool srv_set_thread_priorities = TRUE;
  261. int srv_query_thread_priority = 0;
  262. /*-------------------------------------------*/
  263. ulong srv_n_spin_wait_rounds = 20;
  264. ulong srv_n_free_tickets_to_enter = 500;
  265. ulong srv_thread_sleep_delay = 10000;
  266. ulint srv_spin_wait_delay = 5;
  267. ibool srv_priority_boost = TRUE;
  268. ibool srv_print_thread_releases = FALSE;
  269. ibool srv_print_lock_waits = FALSE;
  270. ibool srv_print_buf_io = FALSE;
  271. ibool srv_print_log_io = FALSE;
  272. ibool srv_print_latch_waits = FALSE;
  273. ulint srv_n_rows_inserted = 0;
  274. ulint srv_n_rows_updated = 0;
  275. ulint srv_n_rows_deleted = 0;
  276. ulint srv_n_rows_read = 0;
  277. #ifndef UNIV_HOTBACKUP
  278. static ulint srv_n_rows_inserted_old = 0;
  279. static ulint srv_n_rows_updated_old = 0;
  280. static ulint srv_n_rows_deleted_old = 0;
  281. static ulint srv_n_rows_read_old = 0;
  282. #endif /* !UNIV_HOTBACKUP */
  283. ulint srv_n_lock_wait_count = 0;
  284. ulint srv_n_lock_wait_current_count = 0;
  285. ib_longlong srv_n_lock_wait_time = 0;
  286. ulint srv_n_lock_max_wait_time = 0;
  287. /*
  288. Set the following to 0 if you want InnoDB to write messages on
  289. stderr on startup/shutdown
  290. */
  291. ibool srv_print_verbose_log = TRUE;
  292. ibool srv_print_innodb_monitor = FALSE;
  293. ibool srv_print_innodb_lock_monitor = FALSE;
  294. ibool srv_print_innodb_tablespace_monitor = FALSE;
  295. ibool srv_print_innodb_table_monitor = FALSE;
  296. /* Array of English strings describing the current state of an
  297. i/o handler thread */
  298. const char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
  299. const char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
  300. time_t srv_last_monitor_time;
  301. mutex_t srv_innodb_monitor_mutex;
  302. /* Mutex for locking srv_monitor_file */
  303. mutex_t srv_monitor_file_mutex;
  304. /* Temporary file for innodb monitor output */
  305. FILE* srv_monitor_file;
  306. /* Mutex for locking srv_dict_tmpfile.
  307. This mutex has a very high rank; threads reserving it should not
  308. be holding any InnoDB latches. */
  309. mutex_t srv_dict_tmpfile_mutex;
  310. /* Temporary file for output from the data dictionary */
  311. FILE* srv_dict_tmpfile;
  312. /* Mutex for locking srv_misc_tmpfile.
  313. This mutex has a very low rank; threads reserving it should not
  314. acquire any further latches or sleep before releasing this one. */
  315. mutex_t srv_misc_tmpfile_mutex;
  316. /* Temporary file for miscellanous diagnostic output */
  317. FILE* srv_misc_tmpfile;
  318. ulint srv_main_thread_process_no = 0;
  319. ulint srv_main_thread_id = 0;
  320. /*
  321. IMPLEMENTATION OF THE SERVER MAIN PROGRAM
  322. =========================================
  323. There is the following analogue between this database
  324. server and an operating system kernel:
  325. DB concept equivalent OS concept
  326. ---------- ---------------------
  327. transaction -- process;
  328. query thread -- thread;
  329. lock -- semaphore;
  330. transaction set to
  331. the rollback state -- kill signal delivered to a process;
  332. kernel -- kernel;
  333. query thread execution:
  334. (a) without kernel mutex
  335. reserved -- process executing in user mode;
  336. (b) with kernel mutex reserved
  337. -- process executing in kernel mode;
  338. The server is controlled by a master thread which runs at
  339. a priority higher than normal, that is, higher than user threads.
  340. It sleeps most of the time, and wakes up, say, every 300 milliseconds,
  341. to check whether there is anything happening in the server which
  342. requires intervention of the master thread. Such situations may be,
  343. for example, when flushing of dirty blocks is needed in the buffer
  344. pool or old version of database rows have to be cleaned away.
  345. The threads which we call user threads serve the queries of
  346. the clients and input from the console of the server.
  347. They run at normal priority. The server may have several
  348. communications endpoints. A dedicated set of user threads waits
  349. at each of these endpoints ready to receive a client request.
  350. Each request is taken by a single user thread, which then starts
  351. processing and, when the result is ready, sends it to the client
  352. and returns to wait at the same endpoint the thread started from.
  353. So, we do not have dedicated communication threads listening at
  354. the endpoints and dealing the jobs to dedicated worker threads.
  355. Our architecture saves one thread swithch per request, compared
  356. to the solution with dedicated communication threads
  357. which amounts to 15 microseconds on 100 MHz Pentium
  358. running NT. If the client
  359. is communicating over a network, this saving is negligible, but
  360. if the client resides in the same machine, maybe in an SMP machine
  361. on a different processor from the server thread, the saving
  362. can be important as the threads can communicate over shared
  363. memory with an overhead of a few microseconds.
  364. We may later implement a dedicated communication thread solution
  365. for those endpoints which communicate over a network.
  366. Our solution with user threads has two problems: for each endpoint
  367. there has to be a number of listening threads. If there are many
  368. communication endpoints, it may be difficult to set the right number
  369. of concurrent threads in the system, as many of the threads
  370. may always be waiting at less busy endpoints. Another problem
  371. is queuing of the messages, as the server internally does not
  372. offer any queue for jobs.
  373. Another group of user threads is intended for splitting the
  374. queries and processing them in parallel. Let us call these
  375. parallel communication threads. These threads are waiting for
  376. parallelized tasks, suspended on event semaphores.
  377. A single user thread waits for input from the console,
  378. like a command to shut the database.
  379. Utility threads are a different group of threads which takes
  380. care of the buffer pool flushing and other, mainly background
  381. operations, in the server.
  382. Some of these utility threads always run at a lower than normal
  383. priority, so that they are always in background. Some of them
  384. may dynamically boost their priority by the pri_adjust function,
  385. even to higher than normal priority, if their task becomes urgent.
  386. The running of utilities is controlled by high- and low-water marks
  387. of urgency. The urgency may be measured by the number of dirty blocks
  388. in the buffer pool, in the case of the flush thread, for example.
  389. When the high-water mark is exceeded, an utility starts running, until
  390. the urgency drops under the low-water mark. Then the utility thread
  391. suspend itself to wait for an event. The master thread is
  392. responsible of signaling this event when the utility thread is
  393. again needed.
  394. For each individual type of utility, some threads always remain
  395. at lower than normal priority. This is because pri_adjust is implemented
  396. so that the threads at normal or higher priority control their
  397. share of running time by calling sleep. Thus, if the load of the
  398. system sudenly drops, these threads cannot necessarily utilize
  399. the system fully. The background priority threads make up for this,
  400. starting to run when the load drops.
  401. When there is no activity in the system, also the master thread
  402. suspends itself to wait for an event making
  403. the server totally silent. The responsibility to signal this
  404. event is on the user thread which again receives a message
  405. from a client.
  406. There is still one complication in our server design. If a
  407. background utility thread obtains a resource (e.g., mutex) needed by a user
  408. thread, and there is also some other user activity in the system,
  409. the user thread may have to wait indefinitely long for the
  410. resource, as the OS does not schedule a background thread if
  411. there is some other runnable user thread. This problem is called
  412. priority inversion in real-time programming.
  413. One solution to the priority inversion problem would be to
  414. keep record of which thread owns which resource and
  415. in the above case boost the priority of the background thread
  416. so that it will be scheduled and it can release the resource.
  417. This solution is called priority inheritance in real-time programming.
  418. A drawback of this solution is that the overhead of acquiring a mutex
  419. increases slightly, maybe 0.2 microseconds on a 100 MHz Pentium, because
  420. the thread has to call os_thread_get_curr_id.
  421. This may be compared to 0.5 microsecond overhead for a mutex lock-unlock
  422. pair. Note that the thread
  423. cannot store the information in the resource, say mutex, itself,
  424. because competing threads could wipe out the information if it is
  425. stored before acquiring the mutex, and if it stored afterwards,
  426. the information is outdated for the time of one machine instruction,
  427. at least. (To be precise, the information could be stored to
  428. lock_word in mutex if the machine supports atomic swap.)
  429. The above solution with priority inheritance may become actual in the
  430. future, but at the moment we plan to implement a more coarse solution,
  431. which could be called a global priority inheritance. If a thread
  432. has to wait for a long time, say 300 milliseconds, for a resource,
  433. we just guess that it may be waiting for a resource owned by a background
  434. thread, and boost the the priority of all runnable background threads
  435. to the normal level. The background threads then themselves adjust
  436. their fixed priority back to background after releasing all resources
  437. they had (or, at some fixed points in their program code).
  438. What is the performance of the global priority inheritance solution?
  439. We may weigh the length of the wait time 300 milliseconds, during
  440. which the system processes some other thread
  441. to the cost of boosting the priority of each runnable background
  442. thread, rescheduling it, and lowering the priority again.
  443. On 100 MHz Pentium + NT this overhead may be of the order 100
  444. microseconds per thread. So, if the number of runnable background
  445. threads is not very big, say < 100, the cost is tolerable.
  446. Utility threads probably will access resources used by
  447. user threads not very often, so collisions of user threads
  448. to preempted utility threads should not happen very often.
  449. The thread table contains
  450. information of the current status of each thread existing in the system,
  451. and also the event semaphores used in suspending the master thread
  452. and utility and parallel communication threads when they have nothing to do.
  453. The thread table can be seen as an analogue to the process table
  454. in a traditional Unix implementation.
  455. The thread table is also used in the global priority inheritance
  456. scheme. This brings in one additional complication: threads accessing
  457. the thread table must have at least normal fixed priority,
  458. because the priority inheritance solution does not work if a background
  459. thread is preempted while possessing the mutex protecting the thread table.
  460. So, if a thread accesses the thread table, its priority has to be
  461. boosted at least to normal. This priority requirement can be seen similar to
  462. the privileged mode used when processing the kernel calls in traditional
  463. Unix.*/
  464. /* Thread slot in the thread table */
  465. struct srv_slot_struct{
  466. os_thread_id_t id; /* thread id */
  467. os_thread_t handle; /* thread handle */
  468. ulint type; /* thread type: user, utility etc. */
  469. ibool in_use; /* TRUE if this slot is in use */
  470. ibool suspended; /* TRUE if the thread is waiting
  471. for the event of this slot */
  472. ib_time_t suspend_time; /* time when the thread was
  473. suspended */
  474. os_event_t event; /* event used in suspending the
  475. thread when it has nothing to do */
  476. que_thr_t* thr; /* suspended query thread (only
  477. used for MySQL threads) */
  478. };
  479. /* Table for MySQL threads where they will be suspended to wait for locks */
  480. srv_slot_t* srv_mysql_table = NULL;
  481. os_event_t srv_lock_timeout_thread_event;
  482. srv_sys_t* srv_sys = NULL;
  483. byte srv_pad1[64]; /* padding to prevent other memory update
  484. hotspots from residing on the same memory
  485. cache line */
  486. mutex_t* kernel_mutex_temp;/* mutex protecting the server, trx structs,
  487. query threads, and lock table */
  488. byte srv_pad2[64]; /* padding to prevent other memory update
  489. hotspots from residing on the same memory
  490. cache line */
  491. /* The following three values measure the urgency of the jobs of
  492. buffer, version, and insert threads. They may vary from 0 - 1000.
  493. The server mutex protects all these variables. The low-water values
  494. tell that the server can acquiesce the utility when the value
  495. drops below this low-water mark. */
  496. ulint srv_meter[SRV_MASTER + 1];
  497. ulint srv_meter_low_water[SRV_MASTER + 1];
  498. ulint srv_meter_high_water[SRV_MASTER + 1];
  499. ulint srv_meter_high_water2[SRV_MASTER + 1];
  500. ulint srv_meter_foreground[SRV_MASTER + 1];
  501. /* The following values give info about the activity going on in
  502. the database. They are protected by the server mutex. The arrays
  503. are indexed by the type of the thread. */
  504. ulint srv_n_threads_active[SRV_MASTER + 1];
  505. ulint srv_n_threads[SRV_MASTER + 1];
  506. /*************************************************************************
  507. Sets the info describing an i/o thread current state. */
  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. Accessor function to get pointer to n'th slot in the server thread
  520. table. */
  521. static
  522. srv_slot_t*
  523. srv_table_get_nth_slot(
  524. /*===================*/
  525. /* out: pointer to the slot */
  526. ulint index) /* in: index of the slot */
  527. {
  528. ut_a(index < OS_THREAD_MAX_N);
  529. return(srv_sys->threads + index);
  530. }
  531. #ifndef UNIV_HOTBACKUP
  532. /*************************************************************************
  533. Gets the number of threads in the system. */
  534. ulint
  535. srv_get_n_threads(void)
  536. /*===================*/
  537. {
  538. ulint i;
  539. ulint n_threads = 0;
  540. mutex_enter(&kernel_mutex);
  541. for (i = SRV_COM; i < SRV_MASTER + 1; i++) {
  542. n_threads += srv_n_threads[i];
  543. }
  544. mutex_exit(&kernel_mutex);
  545. return(n_threads);
  546. }
  547. /*************************************************************************
  548. Reserves a slot in the thread table for the current thread. Also creates the
  549. thread local storage struct for the current thread. NOTE! The server mutex
  550. has to be reserved by the caller! */
  551. static
  552. ulint
  553. srv_table_reserve_slot(
  554. /*===================*/
  555. /* out: reserved slot index */
  556. ulint type) /* in: type of the thread: one of SRV_COM, ... */
  557. {
  558. srv_slot_t* slot;
  559. ulint i;
  560. ut_a(type > 0);
  561. ut_a(type <= SRV_MASTER);
  562. i = 0;
  563. slot = srv_table_get_nth_slot(i);
  564. while (slot->in_use) {
  565. i++;
  566. slot = srv_table_get_nth_slot(i);
  567. }
  568. ut_a(slot->in_use == FALSE);
  569. slot->in_use = TRUE;
  570. slot->suspended = FALSE;
  571. slot->id = os_thread_get_curr_id();
  572. slot->handle = os_thread_get_curr();
  573. slot->type = type;
  574. thr_local_create();
  575. thr_local_set_slot_no(os_thread_get_curr_id(), i);
  576. return(i);
  577. }
  578. /*************************************************************************
  579. Suspends the calling thread to wait for the event in its thread slot.
  580. NOTE! The server mutex has to be reserved by the caller! */
  581. static
  582. os_event_t
  583. srv_suspend_thread(void)
  584. /*====================*/
  585. /* out: event for the calling thread to wait */
  586. {
  587. srv_slot_t* slot;
  588. os_event_t event;
  589. ulint slot_no;
  590. ulint type;
  591. #ifdef UNIV_SYNC_DEBUG
  592. ut_ad(mutex_own(&kernel_mutex));
  593. #endif /* UNIV_SYNC_DEBUG */
  594. slot_no = thr_local_get_slot_no(os_thread_get_curr_id());
  595. if (srv_print_thread_releases) {
  596. fprintf(stderr,
  597. "Suspending thread %lu to slot %lu meter %lu\n",
  598. (ulong) os_thread_get_curr_id(), (ulong) slot_no,
  599. (ulong) srv_meter[SRV_RECOVERY]);
  600. }
  601. slot = srv_table_get_nth_slot(slot_no);
  602. type = slot->type;
  603. ut_ad(type >= SRV_WORKER);
  604. ut_ad(type <= SRV_MASTER);
  605. event = slot->event;
  606. slot->suspended = TRUE;
  607. ut_ad(srv_n_threads_active[type] > 0);
  608. srv_n_threads_active[type]--;
  609. os_event_reset(event);
  610. return(event);
  611. }
  612. #endif /* !UNIV_HOTBACKUP */
  613. /*************************************************************************
  614. Releases threads of the type given from suspension in the thread table.
  615. NOTE! The server mutex has to be reserved by the caller! */
  616. ulint
  617. srv_release_threads(
  618. /*================*/
  619. /* out: number of threads released: this may be
  620. < n if not enough threads were suspended at the
  621. moment */
  622. ulint type, /* in: thread type */
  623. ulint n) /* in: number of threads to release */
  624. {
  625. srv_slot_t* slot;
  626. ulint i;
  627. ulint count = 0;
  628. ut_ad(type >= SRV_WORKER);
  629. ut_ad(type <= SRV_MASTER);
  630. ut_ad(n > 0);
  631. #ifdef UNIV_SYNC_DEBUG
  632. ut_ad(mutex_own(&kernel_mutex));
  633. #endif /* UNIV_SYNC_DEBUG */
  634. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  635. slot = srv_table_get_nth_slot(i);
  636. if (slot->in_use && slot->type == type && slot->suspended) {
  637. slot->suspended = FALSE;
  638. srv_n_threads_active[type]++;
  639. os_event_set(slot->event);
  640. if (srv_print_thread_releases) {
  641. fprintf(stderr,
  642. "Releasing thread %lu type %lu"
  643. " from slot %lu meter %lu\n",
  644. (ulong) slot->id, (ulong) type,
  645. (ulong) i,
  646. (ulong) srv_meter[SRV_RECOVERY]);
  647. }
  648. count++;
  649. if (count == n) {
  650. break;
  651. }
  652. }
  653. }
  654. return(count);
  655. }
  656. /*************************************************************************
  657. Returns the calling thread type. */
  658. ulint
  659. srv_get_thread_type(void)
  660. /*=====================*/
  661. /* out: SRV_COM, ... */
  662. {
  663. ulint slot_no;
  664. srv_slot_t* slot;
  665. ulint type;
  666. mutex_enter(&kernel_mutex);
  667. slot_no = thr_local_get_slot_no(os_thread_get_curr_id());
  668. slot = srv_table_get_nth_slot(slot_no);
  669. type = slot->type;
  670. ut_ad(type >= SRV_WORKER);
  671. ut_ad(type <= SRV_MASTER);
  672. mutex_exit(&kernel_mutex);
  673. return(type);
  674. }
  675. /*************************************************************************
  676. Initializes the server. */
  677. void
  678. srv_init(void)
  679. /*==========*/
  680. {
  681. srv_conc_slot_t* conc_slot;
  682. srv_slot_t* slot;
  683. dict_table_t* table;
  684. ulint i;
  685. srv_sys = mem_alloc(sizeof(srv_sys_t));
  686. kernel_mutex_temp = mem_alloc(sizeof(mutex_t));
  687. mutex_create(&kernel_mutex, SYNC_KERNEL);
  688. mutex_create(&srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
  689. srv_sys->threads = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));
  690. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  691. slot = srv_table_get_nth_slot(i);
  692. slot->in_use = FALSE;
  693. slot->type=0; /* Avoid purify errors */
  694. slot->event = os_event_create(NULL);
  695. ut_a(slot->event);
  696. }
  697. srv_mysql_table = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));
  698. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  699. slot = srv_mysql_table + i;
  700. slot->in_use = FALSE;
  701. slot->type = 0;
  702. slot->event = os_event_create(NULL);
  703. ut_a(slot->event);
  704. }
  705. srv_lock_timeout_thread_event = os_event_create(NULL);
  706. for (i = 0; i < SRV_MASTER + 1; i++) {
  707. srv_n_threads_active[i] = 0;
  708. srv_n_threads[i] = 0;
  709. srv_meter[i] = 30;
  710. srv_meter_low_water[i] = 50;
  711. srv_meter_high_water[i] = 100;
  712. srv_meter_high_water2[i] = 200;
  713. srv_meter_foreground[i] = 250;
  714. }
  715. UT_LIST_INIT(srv_sys->tasks);
  716. /* create dummy table and index for old-style infimum and supremum */
  717. table = dict_mem_table_create("SYS_DUMMY1",
  718. DICT_HDR_SPACE, 1, 0);
  719. dict_mem_table_add_col(table, "DUMMY", DATA_CHAR,
  720. DATA_ENGLISH | DATA_NOT_NULL, 8);
  721. srv_sys->dummy_ind1 = dict_mem_index_create(
  722. "SYS_DUMMY1", "SYS_DUMMY1", DICT_HDR_SPACE, 0, 1);
  723. dict_index_add_col(srv_sys->dummy_ind1, table,
  724. dict_table_get_nth_col(table, 0), 0);
  725. srv_sys->dummy_ind1->table = table;
  726. /* create dummy table and index for new-style infimum and supremum */
  727. table = dict_mem_table_create("SYS_DUMMY2",
  728. DICT_HDR_SPACE, 1, DICT_TF_COMPACT);
  729. dict_mem_table_add_col(table, "DUMMY", DATA_CHAR,
  730. DATA_ENGLISH | DATA_NOT_NULL, 8);
  731. srv_sys->dummy_ind2 = dict_mem_index_create(
  732. "SYS_DUMMY2", "SYS_DUMMY2", DICT_HDR_SPACE, 0, 1);
  733. dict_index_add_col(srv_sys->dummy_ind2, table,
  734. dict_table_get_nth_col(table, 0), 0);
  735. srv_sys->dummy_ind2->table = table;
  736. /* avoid ut_ad(index->cached) in dict_index_get_n_unique_in_tree */
  737. srv_sys->dummy_ind1->cached = srv_sys->dummy_ind2->cached = TRUE;
  738. /* Init the server concurrency restriction data structures */
  739. os_fast_mutex_init(&srv_conc_mutex);
  740. UT_LIST_INIT(srv_conc_queue);
  741. srv_conc_slots = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_conc_slot_t));
  742. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  743. conc_slot = srv_conc_slots + i;
  744. conc_slot->reserved = FALSE;
  745. conc_slot->event = os_event_create(NULL);
  746. ut_a(conc_slot->event);
  747. }
  748. }
  749. /*************************************************************************
  750. Frees the OS fast mutex created in srv_init(). */
  751. void
  752. srv_free(void)
  753. /*==========*/
  754. {
  755. os_fast_mutex_free(&srv_conc_mutex);
  756. }
  757. /*************************************************************************
  758. Initializes the synchronization primitives, memory system, and the thread
  759. local storage. */
  760. void
  761. srv_general_init(void)
  762. /*==================*/
  763. {
  764. os_sync_init();
  765. sync_init();
  766. mem_init(srv_mem_pool_size);
  767. thr_local_init();
  768. }
  769. /*======================= InnoDB Server FIFO queue =======================*/
  770. /* Maximum allowable purge history length. <=0 means 'infinite'. */
  771. ulong srv_max_purge_lag = 0;
  772. /*************************************************************************
  773. Puts an OS thread to wait if there are too many concurrent threads
  774. (>= srv_thread_concurrency) inside InnoDB. The threads wait in a FIFO queue. */
  775. void
  776. srv_conc_enter_innodb(
  777. /*==================*/
  778. trx_t* trx) /* in: transaction object associated with the
  779. thread */
  780. {
  781. ibool has_slept = FALSE;
  782. srv_conc_slot_t* slot = NULL;
  783. ulint i;
  784. /* If trx has 'free tickets' to enter the engine left, then use one
  785. such ticket */
  786. if (trx->n_tickets_to_enter_innodb > 0) {
  787. trx->n_tickets_to_enter_innodb--;
  788. return;
  789. }
  790. os_fast_mutex_lock(&srv_conc_mutex);
  791. retry:
  792. if (trx->declared_to_be_inside_innodb) {
  793. ut_print_timestamp(stderr);
  794. fputs(" InnoDB: Error: trying to declare trx"
  795. " to enter InnoDB, but\n"
  796. "InnoDB: it already is declared.\n", stderr);
  797. trx_print(stderr, trx, 0);
  798. putc('\n', stderr);
  799. os_fast_mutex_unlock(&srv_conc_mutex);
  800. return;
  801. }
  802. if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
  803. srv_conc_n_threads++;
  804. trx->declared_to_be_inside_innodb = TRUE;
  805. trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
  806. os_fast_mutex_unlock(&srv_conc_mutex);
  807. return;
  808. }
  809. /* If the transaction is not holding resources, let it sleep
  810. for SRV_THREAD_SLEEP_DELAY microseconds, and try again then */
  811. if (!has_slept && !trx->has_search_latch
  812. && NULL == UT_LIST_GET_FIRST(trx->trx_locks)) {
  813. has_slept = TRUE; /* We let is sleep only once to avoid
  814. starvation */
  815. srv_conc_n_waiting_threads++;
  816. os_fast_mutex_unlock(&srv_conc_mutex);
  817. trx->op_info = "sleeping before joining InnoDB queue";
  818. /* Peter Zaitsev suggested that we take the sleep away
  819. altogether. But the sleep may be good in pathological
  820. situations of lots of thread switches. Simply put some
  821. threads aside for a while to reduce the number of thread
  822. switches. */
  823. if (SRV_THREAD_SLEEP_DELAY > 0) {
  824. os_thread_sleep(SRV_THREAD_SLEEP_DELAY);
  825. }
  826. trx->op_info = "";
  827. os_fast_mutex_lock(&srv_conc_mutex);
  828. srv_conc_n_waiting_threads--;
  829. goto retry;
  830. }
  831. /* Too many threads inside: put the current thread to a queue */
  832. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  833. slot = srv_conc_slots + i;
  834. if (!slot->reserved) {
  835. break;
  836. }
  837. }
  838. if (i == OS_THREAD_MAX_N) {
  839. /* Could not find a free wait slot, we must let the
  840. thread enter */
  841. srv_conc_n_threads++;
  842. trx->declared_to_be_inside_innodb = TRUE;
  843. trx->n_tickets_to_enter_innodb = 0;
  844. os_fast_mutex_unlock(&srv_conc_mutex);
  845. return;
  846. }
  847. /* Release possible search system latch this thread has */
  848. if (trx->has_search_latch) {
  849. trx_search_latch_release_if_reserved(trx);
  850. }
  851. /* Add to the queue */
  852. slot->reserved = TRUE;
  853. slot->wait_ended = FALSE;
  854. UT_LIST_ADD_LAST(srv_conc_queue, srv_conc_queue, slot);
  855. os_event_reset(slot->event);
  856. srv_conc_n_waiting_threads++;
  857. os_fast_mutex_unlock(&srv_conc_mutex);
  858. /* Go to wait for the event; when a thread leaves InnoDB it will
  859. release this thread */
  860. trx->op_info = "waiting in InnoDB queue";
  861. os_event_wait(slot->event);
  862. trx->op_info = "";
  863. os_fast_mutex_lock(&srv_conc_mutex);
  864. srv_conc_n_waiting_threads--;
  865. /* NOTE that the thread which released this thread already
  866. incremented the thread counter on behalf of this thread */
  867. slot->reserved = FALSE;
  868. UT_LIST_REMOVE(srv_conc_queue, srv_conc_queue, slot);
  869. trx->declared_to_be_inside_innodb = TRUE;
  870. trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
  871. os_fast_mutex_unlock(&srv_conc_mutex);
  872. }
  873. /*************************************************************************
  874. This lets a thread enter InnoDB regardless of the number of threads inside
  875. InnoDB. This must be called when a thread ends a lock wait. */
  876. void
  877. srv_conc_force_enter_innodb(
  878. /*========================*/
  879. trx_t* trx) /* in: transaction object associated with the
  880. thread */
  881. {
  882. if (UNIV_LIKELY(!srv_thread_concurrency)) {
  883. return;
  884. }
  885. os_fast_mutex_lock(&srv_conc_mutex);
  886. srv_conc_n_threads++;
  887. trx->declared_to_be_inside_innodb = TRUE;
  888. trx->n_tickets_to_enter_innodb = 0;
  889. os_fast_mutex_unlock(&srv_conc_mutex);
  890. }
  891. /*************************************************************************
  892. This must be called when a thread exits InnoDB in a lock wait or at the
  893. end of an SQL statement. */
  894. void
  895. srv_conc_force_exit_innodb(
  896. /*=======================*/
  897. trx_t* trx) /* in: transaction object associated with the
  898. thread */
  899. {
  900. srv_conc_slot_t* slot = NULL;
  901. if (UNIV_LIKELY(!srv_thread_concurrency)) {
  902. return;
  903. }
  904. if (trx->declared_to_be_inside_innodb == FALSE) {
  905. return;
  906. }
  907. os_fast_mutex_lock(&srv_conc_mutex);
  908. srv_conc_n_threads--;
  909. trx->declared_to_be_inside_innodb = FALSE;
  910. trx->n_tickets_to_enter_innodb = 0;
  911. if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
  912. /* Look for a slot where a thread is waiting and no other
  913. thread has yet released the thread */
  914. slot = UT_LIST_GET_FIRST(srv_conc_queue);
  915. while (slot && slot->wait_ended == TRUE) {
  916. slot = UT_LIST_GET_NEXT(srv_conc_queue, slot);
  917. }
  918. if (slot != NULL) {
  919. slot->wait_ended = TRUE;
  920. /* We increment the count on behalf of the released
  921. thread */
  922. srv_conc_n_threads++;
  923. }
  924. }
  925. os_fast_mutex_unlock(&srv_conc_mutex);
  926. if (slot != NULL) {
  927. os_event_set(slot->event);
  928. }
  929. }
  930. /*************************************************************************
  931. This must be called when a thread exits InnoDB. */
  932. void
  933. srv_conc_exit_innodb(
  934. /*=================*/
  935. trx_t* trx) /* in: transaction object associated with the
  936. thread */
  937. {
  938. if (trx->n_tickets_to_enter_innodb > 0) {
  939. /* We will pretend the thread is still inside InnoDB though it
  940. now leaves the InnoDB engine. In this way we save
  941. a lot of semaphore operations. srv_conc_force_exit_innodb is
  942. used to declare the thread definitely outside InnoDB. It
  943. should be called when there is a lock wait or an SQL statement
  944. ends. */
  945. return;
  946. }
  947. srv_conc_force_exit_innodb(trx);
  948. }
  949. /*========================================================================*/
  950. /*************************************************************************
  951. Normalizes init parameter values to use units we use inside InnoDB. */
  952. static
  953. ulint
  954. srv_normalize_init_values(void)
  955. /*===========================*/
  956. /* out: DB_SUCCESS or error code */
  957. {
  958. ulint n;
  959. ulint i;
  960. n = srv_n_data_files;
  961. for (i = 0; i < n; i++) {
  962. srv_data_file_sizes[i] = srv_data_file_sizes[i]
  963. * ((1024 * 1024) / UNIV_PAGE_SIZE);
  964. }
  965. srv_last_file_size_max = srv_last_file_size_max
  966. * ((1024 * 1024) / UNIV_PAGE_SIZE);
  967. srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;
  968. srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;
  969. srv_lock_table_size = 5 * (srv_buf_pool_size / UNIV_PAGE_SIZE);
  970. return(DB_SUCCESS);
  971. }
  972. /*************************************************************************
  973. Boots the InnoDB server. */
  974. ulint
  975. srv_boot(void)
  976. /*==========*/
  977. /* out: DB_SUCCESS or error code */
  978. {
  979. ulint err;
  980. /* Transform the init parameter values given by MySQL to
  981. use units we use inside InnoDB: */
  982. err = srv_normalize_init_values();
  983. if (err != DB_SUCCESS) {
  984. return(err);
  985. }
  986. /* Initialize synchronization primitives, memory management, and thread
  987. local storage */
  988. srv_general_init();
  989. /* Initialize this module */
  990. srv_init();
  991. return(DB_SUCCESS);
  992. }
  993. #ifndef UNIV_HOTBACKUP
  994. /*************************************************************************
  995. Reserves a slot in the thread table for the current MySQL OS thread.
  996. NOTE! The kernel mutex has to be reserved by the caller! */
  997. static
  998. srv_slot_t*
  999. srv_table_reserve_slot_for_mysql(void)
  1000. /*==================================*/
  1001. /* out: reserved slot */
  1002. {
  1003. srv_slot_t* slot;
  1004. ulint i;
  1005. #ifdef UNIV_SYNC_DEBUG
  1006. ut_ad(mutex_own(&kernel_mutex));
  1007. #endif /* UNIV_SYNC_DEBUG */
  1008. i = 0;
  1009. slot = srv_mysql_table + i;
  1010. while (slot->in_use) {
  1011. i++;
  1012. if (i >= OS_THREAD_MAX_N) {
  1013. ut_print_timestamp(stderr);
  1014. fprintf(stderr,
  1015. " InnoDB: There appear to be %lu MySQL"
  1016. " threads currently waiting\n"
  1017. "InnoDB: inside InnoDB, which is the"
  1018. " upper limit. Cannot continue operation.\n"
  1019. "InnoDB: We intentionally generate"
  1020. " a seg fault to print a stack trace\n"
  1021. "InnoDB: on Linux. But first we print"
  1022. " a list of waiting threads.\n", (ulong) i);
  1023. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  1024. slot = srv_mysql_table + i;
  1025. fprintf(stderr,
  1026. "Slot %lu: thread id %lu, type %lu,"
  1027. " in use %lu, susp %lu, time %lu\n",
  1028. (ulong) i,
  1029. (ulong) os_thread_pf(slot->id),
  1030. (ulong) slot->type,
  1031. (ulong) slot->in_use,
  1032. (ulong) slot->suspended,
  1033. (ulong) difftime(ut_time(),
  1034. slot->suspend_time));
  1035. }
  1036. ut_error;
  1037. }
  1038. slot = srv_mysql_table + i;
  1039. }
  1040. ut_a(slot->in_use == FALSE);
  1041. slot->in_use = TRUE;
  1042. slot->id = os_thread_get_curr_id();
  1043. slot->handle = os_thread_get_curr();
  1044. return(slot);
  1045. }
  1046. #endif /* !UNIV_HOTBACKUP */
  1047. /*******************************************************************
  1048. Puts a MySQL OS thread to wait for a lock to be released. If an error
  1049. occurs during the wait trx->error_state associated with thr is
  1050. != DB_SUCCESS when we return. DB_LOCK_WAIT_TIMEOUT and DB_DEADLOCK
  1051. are possible errors. DB_DEADLOCK is returned if selective deadlock
  1052. resolution chose this transaction as a victim. */
  1053. void
  1054. srv_suspend_mysql_thread(
  1055. /*=====================*/
  1056. que_thr_t* thr) /* in: query thread associated with the MySQL
  1057. OS thread */
  1058. {
  1059. #ifndef UNIV_HOTBACKUP
  1060. srv_slot_t* slot;
  1061. os_event_t event;
  1062. double wait_time;
  1063. trx_t* trx;
  1064. ibool had_dict_lock = FALSE;
  1065. ibool was_declared_inside_innodb = FALSE;
  1066. ib_longlong start_time = 0;
  1067. ib_longlong finish_time;
  1068. ulint diff_time;
  1069. ulint sec;
  1070. ulint ms;
  1071. #ifdef UNIV_SYNC_DEBUG
  1072. ut_ad(!mutex_own(&kernel_mutex));
  1073. #endif /* UNIV_SYNC_DEBUG */
  1074. trx = thr_get_trx(thr);
  1075. os_event_set(srv_lock_timeout_thread_event);
  1076. mutex_enter(&kernel_mutex);
  1077. trx->error_state = DB_SUCCESS;
  1078. if (thr->state == QUE_THR_RUNNING) {
  1079. ut_ad(thr->is_active == TRUE);
  1080. /* The lock has already been released or this transaction
  1081. was chosen as a deadlock victim: no need to suspend */
  1082. if (trx->was_chosen_as_deadlock_victim) {
  1083. trx->error_state = DB_DEADLOCK;
  1084. trx->was_chosen_as_deadlock_victim = FALSE;
  1085. }
  1086. mutex_exit(&kernel_mutex);
  1087. return;
  1088. }
  1089. ut_ad(thr->is_active == FALSE);
  1090. slot = srv_table_reserve_slot_for_mysql();
  1091. event = slot->event;
  1092. slot->thr = thr;
  1093. os_event_reset(event);
  1094. slot->suspend_time = ut_time();
  1095. if (thr->lock_state == QUE_THR_LOCK_ROW) {
  1096. srv_n_lock_wait_count++;
  1097. srv_n_lock_wait_current_count++;
  1098. ut_usectime(&sec, &ms);
  1099. start_time = (ib_longlong)sec * 1000000 + ms;
  1100. }
  1101. /* Wake the lock timeout monitor thread, if it is suspended */
  1102. os_event_set(srv_lock_timeout_thread_event);
  1103. mutex_exit(&kernel_mutex);
  1104. if (trx->declared_to_be_inside_innodb) {
  1105. was_declared_inside_innodb = TRUE;
  1106. /* We must declare this OS thread to exit InnoDB, since a
  1107. possible other thread holding a lock which this thread waits
  1108. for must be allowed to enter, sooner or later */
  1109. srv_conc_force_exit_innodb(trx);
  1110. }
  1111. /* Release possible foreign key check latch */
  1112. if (trx->dict_operation_lock_mode == RW_S_LATCH) {
  1113. had_dict_lock = TRUE;
  1114. row_mysql_unfreeze_data_dictionary(trx);
  1115. }
  1116. ut_a(trx->dict_operation_lock_mode == 0);
  1117. /* Wait for the release */
  1118. os_event_wait(event);
  1119. if (had_dict_lock) {
  1120. row_mysql_freeze_data_dictionary(trx);
  1121. }
  1122. if (was_declared_inside_innodb) {
  1123. /* Return back inside InnoDB */
  1124. srv_conc_force_enter_innodb(trx);
  1125. }
  1126. mutex_enter(&kernel_mutex);
  1127. /* Release the slot for others to use */
  1128. slot->in_use = FALSE;
  1129. wait_time = ut_difftime(ut_time(), slot->suspend_time);
  1130. if (thr->lock_state == QUE_THR_LOCK_ROW) {
  1131. ut_usectime(&sec, &ms);
  1132. finish_time = (ib_longlong)sec * 1000000 + ms;
  1133. diff_time = (ulint) (finish_time - start_time);
  1134. srv_n_lock_wait_current_count--;
  1135. srv_n_lock_wait_time = srv_n_lock_wait_time + diff_time;
  1136. if (diff_time > srv_n_lock_max_wait_time) {
  1137. srv_n_lock_max_wait_time = diff_time;
  1138. }
  1139. }
  1140. if (trx->was_chosen_as_deadlock_victim) {
  1141. trx->error_state = DB_DEADLOCK;
  1142. trx->was_chosen_as_deadlock_victim = FALSE;
  1143. }
  1144. mutex_exit(&kernel_mutex);
  1145. if (srv_lock_wait_timeout < 100000000
  1146. && wait_time > (double)srv_lock_wait_timeout) {
  1147. trx->error_state = DB_LOCK_WAIT_TIMEOUT;
  1148. }
  1149. #else /* UNIV_HOTBACKUP */
  1150. /* This function depends on MySQL code that is not included in
  1151. InnoDB Hot Backup builds. Besides, this function should never
  1152. be called in InnoDB Hot Backup. */
  1153. ut_error;
  1154. #endif /* UNIV_HOTBACKUP */
  1155. }
  1156. /************************************************************************
  1157. Releases a MySQL OS thread waiting for a lock to be released, if the
  1158. thread is already suspended. */
  1159. void
  1160. srv_release_mysql_thread_if_suspended(
  1161. /*==================================*/
  1162. que_thr_t* thr) /* in: query thread associated with the
  1163. MySQL OS thread */
  1164. {
  1165. #ifndef UNIV_HOTBACKUP
  1166. srv_slot_t* slot;
  1167. ulint i;
  1168. #ifdef UNIV_SYNC_DEBUG
  1169. ut_ad(mutex_own(&kernel_mutex));
  1170. #endif /* UNIV_SYNC_DEBUG */
  1171. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  1172. slot = srv_mysql_table + i;
  1173. if (slot->in_use && slot->thr == thr) {
  1174. /* Found */
  1175. os_event_set(slot->event);
  1176. return;
  1177. }
  1178. }
  1179. /* not found */
  1180. #else /* UNIV_HOTBACKUP */
  1181. /* This function depends on MySQL code that is not included in
  1182. InnoDB Hot Backup builds. Besides, this function should never
  1183. be called in InnoDB Hot Backup. */
  1184. ut_error;
  1185. #endif /* UNIV_HOTBACKUP */
  1186. }
  1187. #ifndef UNIV_HOTBACKUP
  1188. /**********************************************************************
  1189. Refreshes the values used to calculate per-second averages. */
  1190. static
  1191. void
  1192. srv_refresh_innodb_monitor_stats(void)
  1193. /*==================================*/
  1194. {
  1195. mutex_enter(&srv_innodb_monitor_mutex);
  1196. srv_last_monitor_time = time(NULL);
  1197. os_aio_refresh_stats();
  1198. btr_cur_n_sea_old = btr_cur_n_sea;
  1199. btr_cur_n_non_sea_old = btr_cur_n_non_sea;
  1200. log_refresh_stats();
  1201. buf_refresh_io_stats();
  1202. srv_n_rows_inserted_old = srv_n_rows_inserted;
  1203. srv_n_rows_updated_old = srv_n_rows_updated;
  1204. srv_n_rows_deleted_old = srv_n_rows_deleted;
  1205. srv_n_rows_read_old = srv_n_rows_read;
  1206. mutex_exit(&srv_innodb_monitor_mutex);
  1207. }
  1208. /**********************************************************************
  1209. Outputs to a file the output of the InnoDB Monitor. */
  1210. void
  1211. srv_printf_innodb_monitor(
  1212. /*======================*/
  1213. FILE* file, /* in: output stream */
  1214. ulint* trx_start, /* out: file position of the start of
  1215. the list of active transactions */
  1216. ulint* trx_end) /* out: file position of the end of
  1217. the list of active transactions */
  1218. {
  1219. double time_elapsed;
  1220. time_t current_time;
  1221. ulint n_reserved;
  1222. mutex_enter(&srv_innodb_monitor_mutex);
  1223. current_time = time(NULL);
  1224. /* We add 0.001 seconds to time_elapsed to prevent division
  1225. by zero if two users happen to call SHOW INNODB STATUS at the same
  1226. time */
  1227. time_elapsed = difftime(current_time, srv_last_monitor_time)
  1228. + 0.001;
  1229. srv_last_monitor_time = time(NULL);
  1230. fputs("\n=====================================\n", file);
  1231. ut_print_timestamp(file);
  1232. fprintf(file,
  1233. " INNODB MONITOR OUTPUT\n"
  1234. "=====================================\n"
  1235. "Per second averages calculated from the last %lu seconds\n",
  1236. (ulong)time_elapsed);
  1237. fputs("----------\n"
  1238. "SEMAPHORES\n"
  1239. "----------\n", file);
  1240. sync_print(file);
  1241. /* Conceptually, srv_innodb_monitor_mutex has a very high latching
  1242. order level in sync0sync.h, while dict_foreign_err_mutex has a very
  1243. low level 135. Therefore we can reserve the latter mutex here without
  1244. a danger of a deadlock of threads. */
  1245. mutex_enter(&dict_foreign_err_mutex);
  1246. if (ftell(dict_foreign_err_file) != 0L) {
  1247. fputs("------------------------\n"
  1248. "LATEST FOREIGN KEY ERROR\n"
  1249. "------------------------\n", file);
  1250. ut_copy_file(file, dict_foreign_err_file);
  1251. }
  1252. mutex_exit(&dict_foreign_err_mutex);
  1253. lock_print_info_summary(file);
  1254. if (trx_start) {
  1255. long t = ftell(file);
  1256. if (t < 0) {
  1257. *trx_start = ULINT_UNDEFINED;
  1258. } else {
  1259. *trx_start = (ulint) t;
  1260. }
  1261. }
  1262. lock_print_info_all_transactions(file);
  1263. if (trx_end) {
  1264. long t = ftell(file);
  1265. if (t < 0) {
  1266. *trx_end = ULINT_UNDEFINED;
  1267. } else {
  1268. *trx_end = (ulint) t;
  1269. }
  1270. }
  1271. fputs("--------\n"
  1272. "FILE I/O\n"
  1273. "--------\n", file);
  1274. os_aio_print(file);
  1275. fputs("-------------------------------------\n"
  1276. "INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
  1277. "-------------------------------------\n", file);
  1278. ibuf_print(file);
  1279. ha_print_info(file, btr_search_sys->hash_index);
  1280. fprintf(file,
  1281. "%.2f hash searches/s, %.2f non-hash searches/s\n",
  1282. (btr_cur_n_sea - btr_cur_n_sea_old)
  1283. / time_elapsed,
  1284. (btr_cur_n_non_sea - btr_cur_n_non_sea_old)
  1285. / time_elapsed);
  1286. btr_cur_n_sea_old = btr_cur_n_sea;
  1287. btr_cur_n_non_sea_old = btr_cur_n_non_sea;
  1288. fputs("---\n"
  1289. "LOG\n"
  1290. "---\n", file);
  1291. log_print(file);
  1292. fputs("----------------------\n"
  1293. "BUFFER POOL AND MEMORY\n"
  1294. "----------------------\n", file);
  1295. fprintf(file,
  1296. "Total memory allocated " ULINTPF
  1297. "; in additional pool allocated " ULINTPF "\n",
  1298. ut_total_allocated_memory,
  1299. mem_pool_get_reserved(mem_comm_pool));
  1300. fprintf(file, "Dictionary memory allocated " ULINTPF "\n",
  1301. dict_sys->size);
  1302. buf_print_io(file);
  1303. fputs("--------------\n"
  1304. "ROW OPERATIONS\n"
  1305. "--------------\n", file);
  1306. fprintf(file, "%ld queries inside InnoDB, %lu queries in queue\n",
  1307. (long) srv_conc_n_threads,
  1308. (ulong) srv_conc_n_waiting_threads);
  1309. fprintf(file, "%lu read views open inside InnoDB\n",
  1310. UT_LIST_GET_LEN(trx_sys->view_list));
  1311. n_reserved = fil_space_get_n_reserved_extents(0);
  1312. if (n_reserved > 0) {
  1313. fprintf(file,
  1314. "%lu tablespace extents now reserved for"
  1315. " B-tree split operations\n",
  1316. (ulong) n_reserved);
  1317. }
  1318. #ifdef UNIV_LINUX
  1319. fprintf(file, "Main thread process no. %lu, id %lu, state: %s\n",
  1320. (ulong) srv_main_thread_process_no,
  1321. (ulong) srv_main_thread_id,
  1322. srv_main_thread_op_info);
  1323. #else
  1324. fprintf(file, "Main thread id %lu, state: %s\n",
  1325. (ulong) srv_main_thread_id,
  1326. srv_main_thread_op_info);
  1327. #endif
  1328. fprintf(file,
  1329. "Number of rows inserted " ULINTPF
  1330. ", updated " ULINTPF ", deleted " ULINTPF
  1331. ", read " ULINTPF "\n",
  1332. srv_n_rows_inserted,
  1333. srv_n_rows_updated,
  1334. srv_n_rows_deleted,
  1335. srv_n_rows_read);
  1336. fprintf(file,
  1337. "%.2f inserts/s, %.2f updates/s,"
  1338. " %.2f deletes/s, %.2f reads/s\n",
  1339. (srv_n_rows_inserted - srv_n_rows_inserted_old)
  1340. / time_elapsed,
  1341. (srv_n_rows_updated - srv_n_rows_updated_old)
  1342. / time_elapsed,
  1343. (srv_n_rows_deleted - srv_n_rows_deleted_old)
  1344. / time_elapsed,
  1345. (srv_n_rows_read - srv_n_rows_read_old)
  1346. / time_elapsed);
  1347. srv_n_rows_inserted_old = srv_n_rows_inserted;
  1348. srv_n_rows_updated_old = srv_n_rows_updated;
  1349. srv_n_rows_deleted_old = srv_n_rows_deleted;
  1350. srv_n_rows_read_old = srv_n_rows_read;
  1351. fputs("----------------------------\n"
  1352. "END OF INNODB MONITOR OUTPUT\n"
  1353. "============================\n", file);
  1354. mutex_exit(&srv_innodb_monitor_mutex);
  1355. fflush(file);
  1356. }
  1357. /**********************************************************************
  1358. Function to pass InnoDB status variables to MySQL */
  1359. void
  1360. srv_export_innodb_status(void)
  1361. {
  1362. mutex_enter(&srv_innodb_monitor_mutex);
  1363. export_vars.innodb_data_pending_reads
  1364. = os_n_pending_reads;
  1365. export_vars.innodb_data_pending_writes
  1366. = os_n_pending_writes;
  1367. export_vars.innodb_data_pending_fsyncs
  1368. = fil_n_pending_log_flushes
  1369. + fil_n_pending_tablespace_flushes;
  1370. export_vars.innodb_data_fsyncs = os_n_fsyncs;
  1371. export_vars.innodb_data_read = srv_data_read;
  1372. export_vars.innodb_data_reads = os_n_file_reads;
  1373. export_vars.innodb_data_writes = os_n_file_writes;
  1374. export_vars.innodb_data_written = srv_data_written;
  1375. export_vars.innodb_buffer_pool_read_requests = buf_pool->n_page_gets;
  1376. export_vars.innodb_buffer_pool_write_requests
  1377. = srv_buf_pool_write_requests;
  1378. export_vars.innodb_buffer_pool_wait_free = srv_buf_pool_wait_free;
  1379. export_vars.innodb_buffer_pool_pages_flushed = srv_buf_pool_flushed;
  1380. export_vars.innodb_buffer_pool_reads = srv_buf_pool_reads;
  1381. export_vars.innodb_buffer_pool_read_ahead_rnd = srv_read_ahead_rnd;
  1382. export_vars.innodb_buffer_pool_read_ahead_seq = srv_read_ahead_seq;
  1383. export_vars.innodb_buffer_pool_pages_data
  1384. = UT_LIST_GET_LEN(buf_pool->LRU);
  1385. export_vars.innodb_buffer_pool_pages_dirty
  1386. = UT_LIST_GET_LEN(buf_pool->flush_list);
  1387. export_vars.innodb_buffer_pool_pages_free
  1388. = UT_LIST_GET_LEN(buf_pool->free);
  1389. export_vars.innodb_buffer_pool_pages_latched
  1390. = buf_get_latched_pages_number();
  1391. export_vars.innodb_buffer_pool_pages_total = buf_pool->curr_size;
  1392. export_vars.innodb_buffer_pool_pages_misc = buf_pool->curr_size
  1393. - UT_LIST_GET_LEN(buf_pool->LRU)
  1394. - UT_LIST_GET_LEN(buf_pool->free);
  1395. export_vars.innodb_page_size = UNIV_PAGE_SIZE;
  1396. export_vars.innodb_log_waits = srv_log_waits;
  1397. export_vars.innodb_os_log_written = srv_os_log_written;
  1398. export_vars.innodb_os_log_fsyncs = fil_n_log_flushes;
  1399. export_vars.innodb_os_log_pending_fsyncs = fil_n_pending_log_flushes;
  1400. export_vars.innodb_os_log_pending_writes = srv_os_log_pending_writes;
  1401. export_vars.innodb_log_write_requests = srv_log_write_requests;
  1402. export_vars.innodb_log_writes = srv_log_writes;
  1403. export_vars.innodb_dblwr_pages_written = srv_dblwr_pages_written;
  1404. export_vars.innodb_dblwr_writes = srv_dblwr_writes;
  1405. export_vars.innodb_pages_created = buf_pool->n_pages_created;
  1406. export_vars.innodb_pages_read = buf_pool->n_pages_read;
  1407. export_vars.innodb_pages_written = buf_pool->n_pages_written;
  1408. export_vars.innodb_row_lock_waits = srv_n_lock_wait_count;
  1409. export_vars.innodb_row_lock_current_waits
  1410. = srv_n_lock_wait_current_count;
  1411. export_vars.innodb_row_lock_time = srv_n_lock_wait_time / 10000;
  1412. if (srv_n_lock_wait_count > 0) {
  1413. export_vars.innodb_row_lock_time_avg = (ulint)
  1414. (srv_n_lock_wait_time / 10000 / srv_n_lock_wait_count);
  1415. } else {
  1416. export_vars.innodb_row_lock_time_avg = 0;
  1417. }
  1418. export_vars.innodb_row_lock_time_max
  1419. = srv_n_lock_max_wait_time / 10000;
  1420. export_vars.innodb_rows_read = srv_n_rows_read;
  1421. export_vars.innodb_rows_inserted = srv_n_rows_inserted;
  1422. export_vars.innodb_rows_updated = srv_n_rows_updated;
  1423. export_vars.innodb_rows_deleted = srv_n_rows_deleted;
  1424. mutex_exit(&srv_innodb_monitor_mutex);
  1425. }
  1426. /*************************************************************************
  1427. A thread which wakes up threads whose lock wait may have lasted too long.
  1428. This also prints the info output by various InnoDB monitors. */
  1429. os_thread_ret_t
  1430. srv_lock_timeout_and_monitor_thread(
  1431. /*================================*/
  1432. /* out: a dummy parameter */
  1433. void* arg __attribute__((unused)))
  1434. /* in: a dummy parameter required by
  1435. os_thread_create */
  1436. {
  1437. srv_slot_t* slot;
  1438. double time_elapsed;
  1439. time_t current_time;
  1440. time_t last_table_monitor_time;
  1441. time_t last_monitor_time;
  1442. ibool some_waits;
  1443. double wait_time;
  1444. ulint i;
  1445. #ifdef UNIV_DEBUG_THREAD_CREATION
  1446. fprintf(stderr, "Lock timeout thread starts, id %lu\n",
  1447. os_thread_pf(os_thread_get_curr_id()));
  1448. #endif
  1449. UT_NOT_USED(arg);
  1450. srv_last_monitor_time = time(NULL);
  1451. last_table_monitor_time = time(NULL);
  1452. last_monitor_time = time(NULL);
  1453. loop:
  1454. srv_lock_timeout_and_monitor_active = TRUE;
  1455. /* When someone is waiting for a lock, we wake up every second
  1456. and check if a timeout has passed for a lock wait */
  1457. os_thread_sleep(1000000);
  1458. /* In case mutex_exit is not a memory barrier, it is
  1459. theoretically possible some threads are left waiting though
  1460. the semaphore is already released. Wake up those threads: */
  1461. sync_arr_wake_threads_if_sema_free();
  1462. current_time = time(NULL);
  1463. time_elapsed = difftime(current_time, last_monitor_time);
  1464. if (time_elapsed > 15) {
  1465. last_monitor_time = time(NULL);
  1466. if (srv_print_innodb_monitor) {
  1467. srv_printf_innodb_monitor(stderr, NULL, NULL);
  1468. }
  1469. if (srv_innodb_status) {
  1470. mutex_enter(&srv_monitor_file_mutex);
  1471. rewind(srv_monitor_file);
  1472. srv_printf_innodb_monitor(srv_monitor_file, NULL,
  1473. NULL);
  1474. os_file_set_eof(srv_monitor_file);
  1475. mutex_exit(&srv_monitor_file_mutex);
  1476. }
  1477. if (srv_print_innodb_tablespace_monitor
  1478. && difftime(current_time, last_table_monitor_time) > 60) {
  1479. last_table_monitor_time = time(NULL);
  1480. fputs("========================"
  1481. "========================\n",
  1482. stderr);
  1483. ut_print_timestamp(stderr);
  1484. fputs(" INNODB TABLESPACE MONITOR OUTPUT\n"
  1485. "========================"
  1486. "========================\n",
  1487. stderr);
  1488. fsp_print(0);
  1489. fputs("Validating tablespace\n", stderr);
  1490. fsp_validate(0);
  1491. fputs("Validation ok\n"
  1492. "---------------------------------------\n"
  1493. "END OF INNODB TABLESPACE MONITOR OUTPUT\n"
  1494. "=======================================\n",
  1495. stderr);
  1496. }
  1497. if (srv_print_innodb_table_monitor
  1498. && difftime(current_time, last_table_monitor_time) > 60) {
  1499. last_table_monitor_time = time(NULL);
  1500. fputs("===========================================\n",
  1501. stderr);
  1502. ut_print_timestamp(stderr);
  1503. fputs(" INNODB TABLE MONITOR OUTPUT\n"
  1504. "===========================================\n",
  1505. stderr);
  1506. dict_print();
  1507. fputs("-----------------------------------\n"
  1508. "END OF INNODB TABLE MONITOR OUTPUT\n"
  1509. "==================================\n",
  1510. stderr);
  1511. }
  1512. }
  1513. mutex_enter(&kernel_mutex);
  1514. some_waits = FALSE;
  1515. /* Check of all slots if a thread is waiting there, and if it
  1516. has exceeded the time limit */
  1517. for (i = 0; i < OS_THREAD_MAX_N; i++) {
  1518. slot = srv_mysql_table + i;
  1519. if (slot->in_use) {
  1520. some_waits = TRUE;
  1521. wait_time = ut_difftime(ut_time(), slot->suspend_time);
  1522. if (srv_lock_wait_timeout < 100000000
  1523. && (wait_time > (double) srv_lock_wait_timeout
  1524. || wait_time < 0)) {
  1525. /* Timeout exceeded or a wrap-around in system
  1526. time counter: cancel the lock request queued
  1527. by the transaction and release possible
  1528. other transactions waiting behind; it is
  1529. possible that the lock has already been
  1530. granted: in that case do nothing */
  1531. if (thr_get_trx(slot->thr)->wait_lock) {
  1532. lock_cancel_waiting_and_release(
  1533. thr_get_trx(slot->thr)
  1534. ->wait_lock);
  1535. }
  1536. }
  1537. }
  1538. }
  1539. os_event_reset(srv_lock_timeout_thread_event);
  1540. mutex_exit(&kernel_mutex);
  1541. if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
  1542. goto exit_func;
  1543. }
  1544. if (some_waits || srv_print_innodb_monitor
  1545. || srv_print_innodb_lock_monitor
  1546. || srv_print_innodb_tablespace_monitor
  1547. || srv_print_innodb_table_monitor) {
  1548. goto loop;
  1549. }
  1550. /* No one was waiting for a lock and no monitor was active:
  1551. suspend this thread */
  1552. srv_lock_timeout_and_monitor_active = FALSE;
  1553. #if 0
  1554. /* The following synchronisation is disabled, since
  1555. the InnoDB monitor output is to be updated every 15 seconds. */
  1556. os_event_wait(srv_lock_timeout_thread_event);
  1557. #endif
  1558. goto loop;
  1559. exit_func:
  1560. srv_lock_timeout_and_monitor_active = FALSE;
  1561. /* We count the number of threads in os_thread_exit(). A created
  1562. thread should always use that to exit and not use return() to exit. */
  1563. os_thread_exit(NULL);
  1564. OS_THREAD_DUMMY_RETURN;
  1565. }
  1566. /*************************************************************************
  1567. A thread which prints warnings about semaphore waits which have lasted
  1568. too long. These can be used to track bugs which cause hangs. */
  1569. os_thread_ret_t
  1570. srv_error_monitor_thread(
  1571. /*=====================*/
  1572. /* out: a dummy parameter */
  1573. void* arg __attribute__((unused)))
  1574. /* in: a dummy parameter required by
  1575. os_thread_create */
  1576. {
  1577. /* number of successive fatal timeouts observed */
  1578. ulint fatal_cnt = 0;
  1579. dulint old_lsn;
  1580. dulint new_lsn;
  1581. old_lsn = srv_start_lsn;
  1582. #ifdef UNIV_DEBUG_THREAD_CREATION
  1583. fprintf(stderr, "Error monitor thread starts, id %lu\n",
  1584. os_thread_pf(os_thread_get_curr_id()));
  1585. #endif
  1586. loop:
  1587. srv_error_monitor_active = TRUE;
  1588. /* Try to track a strange bug reported by Harald Fuchs and others,
  1589. where the lsn seems to decrease at times */
  1590. new_lsn = log_get_lsn();
  1591. if (ut_dulint_cmp(new_lsn, old_lsn) < 0) {
  1592. ut_print_timestamp(stderr);
  1593. fprintf(stderr,
  1594. " InnoDB: Error: old log sequence number %lu %lu"
  1595. " was greater\n"
  1596. "InnoDB: than the new log sequence number %lu %lu!\n"
  1597. "InnoDB: Please submit a bug report"
  1598. " to http://bugs.mysql.com\n",
  1599. (ulong) ut_dulint_get_high(old_lsn),
  1600. (ulong) ut_dulint_get_low(old_lsn),
  1601. (ulong) ut_dulint_get_high(new_lsn),
  1602. (ulong) ut_dulint_get_low(new_lsn));
  1603. }
  1604. old_lsn = new_lsn;
  1605. if (difftime(time(NULL), srv_last_monitor_time) > 60) {
  1606. /* We referesh InnoDB Monitor values so that averages are
  1607. printed from at most 60 last seconds */
  1608. srv_refresh_innodb_monitor_stats();
  1609. }
  1610. if (sync_array_print_long_waits()) {
  1611. fatal_cnt++;
  1612. if (fatal_cnt > 5) {
  1613. fprintf(stderr,
  1614. "InnoDB: Error: semaphore wait has lasted"
  1615. " > %lu seconds\n"
  1616. "InnoDB: We intentionally crash the server,"
  1617. " because it appears to be hung.\n",
  1618. (ulong) srv_fatal_semaphore_wait_threshold);
  1619. ut_error;
  1620. }
  1621. } else {
  1622. fatal_cnt = 0;
  1623. }
  1624. /* Flush stderr so that a database user gets the output
  1625. to possible MySQL error file */
  1626. fflush(stderr);
  1627. os_thread_sleep(2000000);
  1628. if (srv_shutdown_state < SRV_SHUTDOWN_LAST_PHASE) {
  1629. goto loop;
  1630. }
  1631. srv_error_monitor_active = FALSE;
  1632. /* We count the number of threads in os_thread_exit(). A created
  1633. thread should always use that to exit and not use return() to exit. */
  1634. os_thread_exit(NULL);
  1635. OS_THREAD_DUMMY_RETURN;
  1636. }
  1637. /***********************************************************************
  1638. Tells the InnoDB server that there has been activity in the database
  1639. and wakes up the master thread if it is suspended (not sleeping). Used
  1640. in the MySQL interface. Note that there is a small chance that the master
  1641. thread stays suspended (we do not protect our operation with the kernel
  1642. mutex, for performace reasons). */
  1643. void
  1644. srv_active_wake_master_thread(void)
  1645. /*===============================*/
  1646. {
  1647. srv_activity_count++;
  1648. if (srv_n_threads_active[SRV_MASTER] == 0) {
  1649. mutex_enter(&kernel_mutex);
  1650. srv_release_threads(SRV_MASTER, 1);
  1651. mutex_exit(&kernel_mutex);
  1652. }
  1653. }
  1654. /***********************************************************************
  1655. Wakes up the master thread if it is suspended or being suspended. */
  1656. void
  1657. srv_wake_master_thread(void)
  1658. /*========================*/
  1659. {
  1660. srv_activity_count++;
  1661. mutex_enter(&kernel_mutex);
  1662. srv_release_threads(SRV_MASTER, 1);
  1663. mutex_exit(&kernel_mutex);
  1664. }
  1665. /*************************************************************************
  1666. The master thread controlling the server. */
  1667. os_thread_ret_t
  1668. srv_master_thread(
  1669. /*==============*/
  1670. /* out: a dummy parameter */
  1671. void* arg __attribute__((unused)))
  1672. /* in: a dummy parameter required by
  1673. os_thread_create */
  1674. {
  1675. os_event_t event;
  1676. time_t last_flush_time;
  1677. time_t current_time;
  1678. ulint old_activity_count;
  1679. ulint n_pages_purged = 0;
  1680. ulint n_bytes_merged;
  1681. ulint n_pages_flushed;
  1682. ulint n_bytes_archived;
  1683. ulint n_tables_to_drop;
  1684. ulint n_ios;
  1685. ulint n_ios_old;
  1686. ulint n_ios_very_old;
  1687. ulint n_pend_ios;
  1688. ibool skip_sleep = FALSE;
  1689. ulint i;
  1690. #ifdef UNIV_DEBUG_THREAD_CREATION
  1691. fprintf(stderr, "Master thread starts, id %lu\n",
  1692. os_thread_pf(os_thread_get_curr_id()));
  1693. #endif
  1694. srv_main_thread_process_no = os_proc_get_number();
  1695. srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());
  1696. srv_table_reserve_slot(SRV_MASTER);
  1697. mutex_enter(&kernel_mutex);
  1698. srv_n_threads_active[SRV_MASTER]++;
  1699. mutex_exit(&kernel_mutex);
  1700. loop:
  1701. /*****************************************************************/
  1702. /* ---- When there is database activity by users, we cycle in this
  1703. loop */
  1704. srv_main_thread_op_info = "reserving kernel mutex";
  1705. n_ios_very_old = log_sys->n_log_ios + buf_pool->n_pages_read
  1706. + buf_pool->n_pages_written;
  1707. mutex_enter(&kernel_mutex);
  1708. /* Store the user activity counter at the start of this loop */
  1709. old_activity_count = srv_activity_count;
  1710. mutex_exit(&kernel_mutex);
  1711. if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {
  1712. goto suspend_thread;
  1713. }
  1714. /* ---- We run the following loop approximately once per second
  1715. when there is database activity */
  1716. skip_sleep = FALSE;
  1717. for (i = 0; i < 10; i++) {
  1718. n_ios_old = log_sys->n_log_ios + buf_pool->n_pages_read
  1719. + buf_pool->n_pages_written;
  1720. srv_main_thread_op_info = "sleeping";
  1721. if (!skip_sleep) {
  1722. os_thread_sleep(1000000);
  1723. }
  1724. skip_sleep = FALSE;
  1725. /* ALTER TABLE in MySQL requires on Unix that the table handler
  1726. can drop tables lazily after there no longer are SELECT
  1727. queries to them. */
  1728. srv_main_thread_op_info = "doing background drop tables";
  1729. row_drop_tables_for_mysql_in_background();
  1730. srv_main_thread_op_info = "";
  1731. if (srv_fast_shutdown && srv_shutdown_state > 0) {
  1732. goto background_loop;
  1733. }
  1734. /* We flush the log once in a second even if no commit
  1735. is issued or the we have specified in my.cnf no flush
  1736. at transaction commit */
  1737. srv_main_thread_op_info = "flushing log";
  1738. log_buffer_flush_to_disk();
  1739. srv_main_thread_op_info = "making checkpoint";
  1740. log_free_check();
  1741. /* If there were less than 5 i/os during the
  1742. one second sleep, we assume that there is free
  1743. disk i/o capacity available, and it makes sense to
  1744. do an insert buffer merge. */
  1745. n_pend_ios = buf_get_n_pending_ios()
  1746. + log_sys->n_pending_writes;
  1747. n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
  1748. + buf_pool->n_pages_written;
  1749. if (n_pend_ios < 3 && (n_ios - n_ios_old < 5)) {
  1750. srv_main_thread_op_info = "doing insert buffer merge";
  1751. ibuf_contract_for_n_pages(TRUE, 5);
  1752. srv_main_thread_op_info = "flushing log";
  1753. log_buffer_flush_to_disk();
  1754. }
  1755. if (UNIV_UNLIKELY(buf_get_modified_ratio_pct()
  1756. > srv_max_buf_pool_modified_pct)) {
  1757. /* Try to keep the number of modified pages in the
  1758. buffer pool under the limit wished by the user */
  1759. n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100,
  1760. ut_dulint_max);
  1761. /* If we had to do the flush, it may have taken
  1762. even more than 1 second, and also, there may be more
  1763. to flush. Do not sleep 1 second during the next
  1764. iteration of this loop. */
  1765. skip_sleep = TRUE;
  1766. }
  1767. if (srv_activity_count == old_activity_count) {
  1768. /* There is no user activity at the moment, go to
  1769. the background loop */
  1770. goto background_loop;
  1771. }
  1772. }
  1773. /* ---- We perform the following code approximately once per
  1774. 10 seconds when there is database activity */
  1775. #ifdef MEM_PERIODIC_CHECK
  1776. /* Check magic numbers of every allocated mem block once in 10
  1777. seconds */
  1778. mem_validate_all_blocks();
  1779. #endif
  1780. /* If there were less than 200 i/os during the 10 second period,
  1781. we assume that there is free disk i/o capacity available, and it
  1782. makes sense to flush 100 pages. */
  1783. n_pend_ios = buf_get_n_pending_ios() + log_sys->n_pending_writes;
  1784. n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
  1785. + buf_pool->n_pages_written;
  1786. if (n_pend_ios < 3 && (n_ios - n_ios_very_old < 200)) {
  1787. srv_main_thread_op_info = "flushing buffer pool pages";
  1788. buf_flush_batch(BUF_FLUSH_LIST, 100, ut_dulint_max);
  1789. srv_main_thread_op_info = "flushing log";
  1790. log_buffer_flush_to_disk();
  1791. }
  1792. /* We run a batch of insert buffer merge every 10 seconds,
  1793. even if the server were active */
  1794. srv_main_thread_op_info = "doing insert buffer merge";
  1795. ibuf_contract_for_n_pages(TRUE, 5);
  1796. srv_main_thread_op_info = "flushing log";
  1797. log_buffer_flush_to_disk();
  1798. /* We run a full purge every 10 seconds, even if the server
  1799. were active */
  1800. last_flush_time = time(NULL);
  1801. do {
  1802. if (srv_fast_shutdown && srv_shutdown_state > 0) {
  1803. goto background_loop;
  1804. }
  1805. srv_main_thread_op_info = "purging";
  1806. n_pages_purged = trx_purge();
  1807. current_time = time(NULL);
  1808. if (difftime(current_time, last_flush_time) > 1) {
  1809. srv_main_thread_op_info = "flushing log";
  1810. log_buffer_flush_to_disk();
  1811. last_flush_time = current_time;
  1812. }
  1813. } while (n_pages_purged);
  1814. srv_main_thread_op_info = "flushing buffer pool pages";
  1815. /* Flush a few oldest pages to make a new checkpoint younger */
  1816. if (buf_get_modified_ratio_pct() > 70) {
  1817. /* If there are lots of modified pages in the buffer pool
  1818. (> 70 %), we assume we can afford reserving the disk(s) for
  1819. the time it requires to flush 100 pages */
  1820. n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100,
  1821. ut_dulint_max);
  1822. } else {
  1823. /* Otherwise, we only flush a small number of pages so that
  1824. we do not unnecessarily use much disk i/o capacity from
  1825. other work */
  1826. n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 10,
  1827. ut_dulint_max);
  1828. }
  1829. srv_main_thread_op_info = "making checkpoint";
  1830. /* Make a new checkpoint about once in 10 seconds */
  1831. log_checkpoint(TRUE, FALSE);
  1832. srv_main_thread_op_info = "reserving kernel mutex";
  1833. mutex_enter(&kernel_mutex);
  1834. /* ---- When there is database activity, we jump from here back to
  1835. the start of loop */
  1836. if (srv_activity_count != old_activity_count) {
  1837. mutex_exit(&kernel_mutex);
  1838. goto loop;
  1839. }
  1840. mutex_exit(&kernel_mutex);
  1841. /* If the database is quiet, we enter the background loop */
  1842. /*****************************************************************/
  1843. background_loop:
  1844. /* ---- In this loop we run background operations when the server
  1845. is quiet from user activity. Also in the case of a shutdown, we
  1846. loop here, flushing the buffer pool to the data files. */
  1847. /* The server has been quiet for a while: start running background
  1848. operations */
  1849. srv_main_thread_op_info = "doing background drop tables";
  1850. n_tables_to_drop = row_drop_tables_for_mysql_in_background();
  1851. if (n_tables_to_drop > 0) {
  1852. /* Do not monopolize the CPU even if there are tables waiting
  1853. in the background drop queue. (It is essentially a bug if
  1854. MySQL tries to drop a table while there are still open handles
  1855. to it and we had to put it to the background drop queue.) */
  1856. os_thread_sleep(100000);
  1857. }
  1858. srv_main_thread_op_info = "purging";
  1859. /* Run a full purge */
  1860. last_flush_time = time(NULL);
  1861. do {
  1862. if (srv_fast_shutdown && srv_shutdown_state > 0) {
  1863. break;
  1864. }
  1865. srv_main_thread_op_info = "purging";
  1866. n_pages_purged = trx_purge();
  1867. current_time = time(NULL);
  1868. if (difftime(current_time, last_flush_time) > 1) {
  1869. srv_main_thread_op_info = "flushing log";
  1870. log_buffer_flush_to_disk();
  1871. last_flush_time = current_time;
  1872. }
  1873. } while (n_pages_purged);
  1874. srv_main_thread_op_info = "reserving kernel mutex";
  1875. mutex_enter(&kernel_mutex);
  1876. if (srv_activity_count != old_activity_count) {
  1877. mutex_exit(&kernel_mutex);
  1878. goto loop;
  1879. }
  1880. mutex_exit(&kernel_mutex);
  1881. srv_main_thread_op_info = "doing insert buffer merge";
  1882. if (srv_fast_shutdown && srv_shutdown_state > 0) {
  1883. n_bytes_merged = 0;
  1884. } else {
  1885. n_bytes_merged = ibuf_contract_for_n_pages(TRUE, 20);
  1886. }
  1887. srv_main_thread_op_info = "reserving kernel mutex";
  1888. mutex_enter(&kernel_mutex);
  1889. if (srv_activity_count != old_activity_count) {
  1890. mutex_exit(&kernel_mutex);
  1891. goto loop;
  1892. }
  1893. mutex_exit(&kernel_mutex);
  1894. flush_loop:
  1895. srv_main_thread_op_info = "flushing buffer pool pages";
  1896. if (srv_fast_shutdown < 2) {
  1897. n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100,
  1898. ut_dulint_max);
  1899. } else {
  1900. /* In the fastest shutdown we do not flush the buffer pool
  1901. to data files: we set n_pages_flushed to 0 artificially. */
  1902. n_pages_flushed = 0;
  1903. }
  1904. srv_main_thread_op_info = "reserving kernel mutex";
  1905. mutex_enter(&kernel_mutex);
  1906. if (srv_activity_count != old_activity_count) {
  1907. mutex_exit(&kernel_mutex);
  1908. goto loop;
  1909. }
  1910. mutex_exit(&kernel_mutex);
  1911. srv_main_thread_op_info = "waiting for buffer pool flush to end";
  1912. buf_flush_wait_batch_end(BUF_FLUSH_LIST);
  1913. srv_main_thread_op_info = "flushing log";
  1914. log_buffer_flush_to_disk();
  1915. srv_main_thread_op_info = "making checkpoint";
  1916. log_checkpoint(TRUE, FALSE);
  1917. if (buf_get_modified_ratio_pct() > srv_max_buf_pool_modified_pct) {
  1918. /* Try to keep the number of modified pages in the
  1919. buffer pool under the limit wished by the user */
  1920. goto flush_loop;
  1921. }
  1922. srv_main_thread_op_info = "reserving kernel mutex";
  1923. mutex_enter(&kernel_mutex);
  1924. if (srv_activity_count != old_activity_count) {
  1925. mutex_exit(&kernel_mutex);
  1926. goto loop;
  1927. }
  1928. mutex_exit(&kernel_mutex);
  1929. /*
  1930. srv_main_thread_op_info = "archiving log (if log archive is on)";
  1931. log_archive_do(FALSE, &n_bytes_archived);
  1932. */
  1933. n_bytes_archived = 0;
  1934. /* Keep looping in the background loop if still work to do */
  1935. if (srv_fast_shutdown && srv_shutdown_state > 0) {
  1936. if (n_tables_to_drop + n_pages_flushed
  1937. + n_bytes_archived != 0) {
  1938. /* If we are doing a fast shutdown (= the default)
  1939. we do not do purge or insert buffer merge. But we
  1940. flush the buffer pool completely to disk.
  1941. In a 'very fast' shutdown we do not flush the buffer
  1942. pool to data files: we have set n_pages_flushed to
  1943. 0 artificially. */
  1944. goto background_loop;
  1945. }
  1946. } else if (n_tables_to_drop
  1947. + n_pages_purged + n_bytes_merged + n_pages_flushed
  1948. + n_bytes_archived != 0) {
  1949. /* In a 'slow' shutdown we run purge and the insert buffer
  1950. merge to completion */
  1951. goto background_loop;
  1952. }
  1953. /* There is no work for background operations either: suspend
  1954. master thread to wait for more server activity */
  1955. suspend_thread:
  1956. srv_main_thread_op_info = "suspending";
  1957. mutex_enter(&kernel_mutex);
  1958. if (row_get_background_drop_list_len_low() > 0) {
  1959. mutex_exit(&kernel_mutex);
  1960. goto loop;
  1961. }
  1962. event = srv_suspend_thread();
  1963. mutex_exit(&kernel_mutex);
  1964. /* DO NOT CHANGE THIS STRING. innobase_start_or_create_for_mysql()
  1965. waits for database activity to die down when converting < 4.1.x
  1966. databases, and relies on this string being exactly as it is. InnoDB
  1967. manual also mentions this string in several places. */
  1968. srv_main_thread_op_info = "waiting for server activity";
  1969. os_event_wait(event);
  1970. if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
  1971. /* This is only extra safety, the thread should exit
  1972. already when the event wait ends */
  1973. os_thread_exit(NULL);
  1974. }
  1975. /* When there is user activity, InnoDB will set the event and the
  1976. main thread goes back to loop. */
  1977. goto loop;
  1978. OS_THREAD_DUMMY_RETURN; /* Not reached, avoid compiler warning */
  1979. }
  1980. #endif /* !UNIV_HOTBACKUP */