srv0srv.c 83.1 KB
Newer Older
1 2 3 4 5 6 7 8 9
/******************************************************
The database server main program

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

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

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

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

unknown's avatar
unknown committed
23
(c) 1995 Innobase Oy
24 25 26

Created 10/8/1995 Heikki Tuuri
*******************************************************/
unknown's avatar
unknown committed
27
/* Dummy comment */
28 29 30 31 32
#include "srv0srv.h"

#include "ut0mem.h"
#include "os0proc.h"
#include "mem0mem.h"
33
#include "mem0pool.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include "sync0sync.h"
#include "sync0ipm.h"
#include "thr0loc.h"
#include "com0com.h"
#include "com0shm.h"
#include "que0que.h"
#include "srv0que.h"
#include "log0recv.h"
#include "odbc0odbc.h"
#include "pars0pars.h"
#include "usr0sess.h"
#include "lock0lock.h"
#include "trx0purge.h"
#include "ibuf0ibuf.h"
#include "buf0flu.h"
#include "btr0sea.h"
50
#include "dict0load.h"
unknown's avatar
Merge  
unknown committed
51
#include "srv0start.h"
unknown's avatar
unknown committed
52
#include "row0mysql.h"
53

unknown's avatar
unknown committed
54 55 56 57
/* This is set to TRUE if the MySQL user has set it in MySQL; currently
affects only FOREIGN KEY definition parsing */
ibool	srv_lower_case_table_names	= FALSE;

unknown's avatar
unknown committed
58 59 60
/* Buffer which can be used in printing fatal error messages */
char	srv_fatal_errbuf[5000];

61 62 63 64
/* The following counter is incremented whenever there is some user activity
in the server */
ulint	srv_activity_count	= 0;

unknown's avatar
Merge  
unknown committed
65 66 67
ibool	srv_lock_timeout_and_monitor_active = FALSE;
ibool	srv_error_monitor_active = FALSE;

unknown's avatar
unknown committed
68
char*	srv_main_thread_op_info = (char*) "";
69

70 71 72 73 74 75 76 77 78 79 80 81
/* Server parameters which are read from the initfile */

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

char*	srv_data_home 	= NULL;
char*	srv_arch_dir 	= NULL;

ulint	srv_n_data_files = 0;
char**	srv_data_file_names = NULL;
ulint*	srv_data_file_sizes = NULL;	/* size in database pages */ 

unknown's avatar
unknown committed
82 83 84 85 86 87 88
ibool	srv_auto_extend_last_data_file	= FALSE; /* if TRUE, then we
						 auto-extend the last data
						 file */
ulint	srv_last_file_size_max	= 0;		 /* if != 0, this tells
						 the max size auto-extending
						 may increase the last data
						 file size */
89 90
ulint*  srv_data_file_is_raw_partition = NULL;

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

ibool	srv_created_new_raw	= FALSE;

96 97 98 99 100
char**	srv_log_group_home_dirs = NULL; 

ulint	srv_n_log_groups	= ULINT_MAX;
ulint	srv_n_log_files		= ULINT_MAX;
ulint	srv_log_file_size	= ULINT_MAX;	/* size in database pages */ 
unknown's avatar
unknown committed
101
ibool	srv_log_archive_on	= TRUE;
102
ulint	srv_log_buffer_size	= ULINT_MAX;	/* size in database pages */ 
unknown's avatar
unknown committed
103
ulint	srv_flush_log_at_trx_commit = 1;
104

unknown's avatar
unknown committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
byte	srv_latin1_ordering[256]	/* The sort order table of the latin1
					character set. The following table is
					the MySQL order as of Feb 10th, 2002 */
= {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17
, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27
, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F
, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37
, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F
, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F
, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57
, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F
, 0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47
, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F
, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57
, 0x58, 0x59, 0x5A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F
, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87
, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F
, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97
, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F
, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7
, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF
, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7
, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF
, 0x41, 0x41, 0x41, 0x41, 0x5C, 0x5B, 0x5C, 0x43
, 0x45, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x49
, 0x44, 0x4E, 0x4F, 0x4F, 0x4F, 0x4F, 0x5D, 0xD7
, 0xD8, 0x55, 0x55, 0x55, 0x59, 0x59, 0xDE, 0xDF
, 0x41, 0x41, 0x41, 0x41, 0x5C, 0x5B, 0x5C, 0x43
, 0x45, 0x45, 0x45, 0x45, 0x49, 0x49, 0x49, 0x49
, 0x44, 0x4E, 0x4F, 0x4F, 0x4F, 0x4F, 0x5D, 0xF7
, 0xD8, 0x55, 0x55, 0x55, 0x59, 0x59, 0xDE, 0xFF
};
142 143 144 145 146 147 148 149 150 151 152 153 154
		
ulint	srv_pool_size		= ULINT_MAX;	/* size in database pages;
						MySQL originally sets this
						value in megabytes */ 
ulint	srv_mem_pool_size	= ULINT_MAX;	/* size in bytes */ 
ulint	srv_lock_table_size	= ULINT_MAX;

ulint	srv_n_file_io_threads	= ULINT_MAX;

ibool	srv_archive_recovery	= 0;
dulint	srv_archive_recovery_limit_lsn;

ulint	srv_lock_wait_timeout	= 1024 * 1024 * 1024;
unknown's avatar
unknown committed
155

unknown's avatar
unknown committed
156 157 158
char*   srv_file_flush_method_str = NULL;
ulint   srv_unix_file_flush_method = SRV_UNIX_FDATASYNC;
ulint   srv_win_file_flush_method = SRV_WIN_IO_UNBUFFERED;
159

160 161 162 163 164
/* The InnoDB main thread tries to keep the ratio of modified pages
in the buffer pool to all database pages in the buffer pool smaller than
the following number. But it is not guaranteed that the value stays below
that during a time of heavy update/insert activity. */

165
ulint	srv_max_buf_pool_modified_pct	= 90;
166

167
/* If the following is != 0 we do not allow inserts etc. This protects
unknown's avatar
Merge  
unknown committed
168
the user from forgetting the innodb_force_recovery keyword to my.cnf */
169 170

ulint	srv_force_recovery	= 0;
unknown's avatar
Merge  
unknown committed
171 172 173 174 175 176 177 178
/*-----------------------*/
/* The following controls how many threads we let inside InnoDB concurrently:
threads waiting for locks are not counted into the number because otherwise
we could get a deadlock. MySQL creates a thread for each user session, and
semaphore contention and convoy problems can occur withput this restriction.
Value 10 should be good if there are less than 4 processors + 4 disks in the
computer. Bigger computers need bigger values. */

unknown's avatar
unknown committed
179
ulint	srv_thread_concurrency	= 8;
unknown's avatar
Merge  
unknown committed
180 181 182

os_fast_mutex_t	srv_conc_mutex;		/* this mutex protects srv_conc data
					structures */
unknown's avatar
unknown committed
183 184 185 186 187 188 189
lint	srv_conc_n_threads	= 0;	/* number of OS threads currently
					inside InnoDB; it is not an error
					if this drops temporarily below zero
					because we do not demand that every
					thread increments this, but a thread
					waiting for a lock decrements this
					temporarily */
unknown's avatar
unknown committed
190 191 192
ulint	srv_conc_n_waiting_threads = 0;	/* number of OS threads waiting in the
					FIFO for a permission to enter InnoDB
					*/
unknown's avatar
Merge  
unknown committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

typedef struct srv_conc_slot_struct	srv_conc_slot_t;
struct srv_conc_slot_struct{
	os_event_t			event;		/* event to wait */
	ibool				reserved;	/* TRUE if slot
							reserved */
	ibool				wait_ended;	/* TRUE when another
							thread has already set
							the event and the
							thread in this slot is
							free to proceed; but
							reserved may still be
							TRUE at that point */
	UT_LIST_NODE_T(srv_conc_slot_t)	srv_conc_queue;	/* queue node */
};

UT_LIST_BASE_NODE_T(srv_conc_slot_t)	srv_conc_queue;	/* queue of threads
							waiting to get in */
srv_conc_slot_t	srv_conc_slots[OS_THREAD_MAX_N];	/* array of wait
							slots */
unknown's avatar
unknown committed
213 214 215 216 217

/* Number of times a thread is allowed to enter InnoDB within the same
SQL query after it has once got the ticket at srv_conc_enter_innodb */
#define SRV_FREE_TICKETS_TO_ENTER	500

unknown's avatar
Merge  
unknown committed
218 219 220 221 222
/*-----------------------*/
/* If the following is set TRUE then we do not run purge and insert buffer
merge to completion before shutdown */

ibool	srv_fast_shutdown	= FALSE;
223

224 225
ibool	srv_use_doublewrite_buf	= TRUE;

unknown's avatar
unknown committed
226 227
ibool   srv_set_thread_priorities = TRUE;
int     srv_query_thread_priority = 0;
228 229 230 231 232 233 234 235 236 237 238 239 240 241
/*-------------------------------------------*/
ulint	srv_n_spin_wait_rounds	= 20;
ulint	srv_spin_wait_delay	= 5;
ibool	srv_priority_boost	= TRUE;
char	srv_endpoint_name[COM_MAX_ADDR_LEN];
ulint	srv_n_com_threads	= ULINT_MAX;
ulint	srv_n_worker_threads	= ULINT_MAX;

ibool	srv_print_thread_releases	= FALSE;
ibool	srv_print_lock_waits		= FALSE;
ibool	srv_print_buf_io		= FALSE;
ibool	srv_print_log_io		= FALSE;
ibool	srv_print_latch_waits		= FALSE;

242 243 244 245
ulint	srv_n_rows_inserted		= 0;
ulint	srv_n_rows_updated		= 0;
ulint	srv_n_rows_deleted		= 0;
ulint	srv_n_rows_read			= 0;
246 247 248 249
ulint	srv_n_rows_inserted_old		= 0;
ulint	srv_n_rows_updated_old		= 0;
ulint	srv_n_rows_deleted_old		= 0;
ulint	srv_n_rows_read_old		= 0;
250

251 252 253 254 255
/*
  Set the following to 0 if you want InnoDB to write messages on
  stderr on startup/shutdown
*/
ibool	srv_print_verbose_log		= TRUE;
256
ibool	srv_print_innodb_monitor	= FALSE;
257 258
ibool   srv_print_innodb_lock_monitor   = FALSE;
ibool   srv_print_innodb_tablespace_monitor = FALSE;
259
ibool   srv_print_innodb_table_monitor = FALSE;
260

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
/* The parameters below are obsolete: */

ibool	srv_print_parsed_sql		= FALSE;

ulint	srv_sim_disk_wait_pct		= ULINT_MAX;
ulint	srv_sim_disk_wait_len		= ULINT_MAX;
ibool	srv_sim_disk_wait_by_yield	= FALSE;
ibool	srv_sim_disk_wait_by_wait	= FALSE;

ibool	srv_measure_contention	= FALSE;
ibool	srv_measure_by_spin	= FALSE;
	
ibool	srv_test_extra_mutexes	= FALSE;
ibool	srv_test_nocache	= FALSE;
ibool	srv_test_cache_evict	= FALSE;

ibool	srv_test_sync		= FALSE;
ulint	srv_test_n_threads	= ULINT_MAX;
ulint	srv_test_n_loops	= ULINT_MAX;
ulint	srv_test_n_free_rnds	= ULINT_MAX;
ulint	srv_test_n_reserved_rnds = ULINT_MAX;
ulint	srv_test_array_size	= ULINT_MAX;
ulint	srv_test_n_mutexes	= ULINT_MAX;

285 286 287 288
/* Array of English strings describing the current state of an
i/o handler thread */

char* srv_io_thread_op_info[SRV_MAX_N_IO_THREADS];
unknown's avatar
unknown committed
289
char* srv_io_thread_function[SRV_MAX_N_IO_THREADS];
290

unknown's avatar
unknown committed
291 292
time_t	srv_last_monitor_time;

unknown's avatar
unknown committed
293 294
mutex_t srv_innodb_monitor_mutex;

unknown's avatar
unknown committed
295 296 297
ulint	srv_main_thread_process_no	= 0;
ulint	srv_main_thread_id		= 0;

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
/*
	IMPLEMENTATION OF THE SERVER MAIN PROGRAM
	=========================================

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

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

query thread		--	thread;

lock			--	semaphore;

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

kernel			--	kernel;

query thread execution:
(a) without kernel mutex
reserved	 	-- 	process executing in user mode;
(b) with kernel mutex reserved
			--	process executing in kernel mode;

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

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

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

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

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

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

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

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

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

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

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

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

The above solution with priority inheritance may become actual in the
future, but at the moment we plan to implement a more coarse solution,
which could be called a global priority inheritance. If a thread
has to wait for a long time, say 300 milliseconds, for a resource,
we just guess that it may be waiting for a resource owned by a background
thread, and boost the the priority of all runnable background threads
to the normal level. The background threads then themselves adjust
their fixed priority back to background after releasing all resources
they had (or, at some fixed points in their program code).

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

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

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

/* Thread slot in the thread table */
struct srv_slot_struct{
	os_thread_id_t	id;		/* thread id */
	os_thread_t	handle;		/* thread handle */
	ulint		type;		/* thread type: user, utility etc. */
	ibool		in_use;		/* TRUE if this slot is in use */
	ibool		suspended;	/* TRUE if the thread is waiting
					for the event of this slot */
	ib_time_t	suspend_time;	/* time when the thread was
					suspended */
	os_event_t	event;		/* event used in suspending the
					thread when it has nothing to do */
	que_thr_t*	thr;		/* suspended query thread (only
					used for MySQL threads) */
};

/* Table for MySQL threads where they will be suspended to wait for locks */
srv_slot_t*	srv_mysql_table = NULL;

os_event_t	srv_lock_timeout_thread_event;

srv_sys_t*	srv_sys	= NULL;

byte		srv_pad1[64];	/* padding to prevent other memory update
				hotspots from residing on the same memory
				cache line */
mutex_t*	kernel_mutex_temp;/* mutex protecting the server, trx structs,
				query threads, and lock table */
byte		srv_pad2[64];	/* padding to prevent other memory update
				hotspots from residing on the same memory
				cache line */

/* The following three values measure the urgency of the jobs of
buffer, version, and insert threads. They may vary from 0 - 1000.
The server mutex protects all these variables. The low-water values
tell that the server can acquiesce the utility when the value
drops below this low-water mark. */

ulint	srv_meter[SRV_MASTER + 1];
ulint	srv_meter_low_water[SRV_MASTER + 1];
ulint	srv_meter_high_water[SRV_MASTER + 1];
ulint	srv_meter_high_water2[SRV_MASTER + 1];
ulint	srv_meter_foreground[SRV_MASTER + 1];

/* The following values give info about the activity going on in
the database. They are protected by the server mutex. The arrays
are indexed by the type of the thread. */

ulint	srv_n_threads_active[SRV_MASTER + 1];
ulint	srv_n_threads[SRV_MASTER + 1];


/*************************************************************************
Accessor function to get pointer to n'th slot in the server thread
table. */
static
srv_slot_t*
srv_table_get_nth_slot(
/*===================*/
				/* out: pointer to the slot */
	ulint	index)		/* in: index of the slot */
{
	ut_a(index < OS_THREAD_MAX_N);

	return(srv_sys->threads + index);
}

/*************************************************************************
Gets the number of threads in the system. */

ulint
srv_get_n_threads(void)
/*===================*/
{
	ulint	i;
	ulint	n_threads	= 0;

	mutex_enter(&kernel_mutex);

	for (i = SRV_COM; i < SRV_MASTER + 1; i++) {
	
		n_threads += srv_n_threads[i];
	}

	mutex_exit(&kernel_mutex);

	return(n_threads);
}

/*************************************************************************
Reserves a slot in the thread table for the current thread. Also creates the
thread local storage struct for the current thread. NOTE! The server mutex
has to be reserved by the caller! */
static
ulint
srv_table_reserve_slot(
/*===================*/
			/* out: reserved slot index */
	ulint	type)	/* in: type of the thread: one of SRV_COM, ... */
{
	srv_slot_t*	slot;
	ulint		i;
	
	ut_a(type > 0);
	ut_a(type <= SRV_MASTER);

	i = 0;
	slot = srv_table_get_nth_slot(i);

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

	ut_a(slot->in_use == FALSE);
	
	slot->in_use = TRUE;
	slot->suspended = FALSE;
	slot->id = os_thread_get_curr_id();
	slot->handle = os_thread_get_curr();
	slot->type = type;

	thr_local_create();

	thr_local_set_slot_no(os_thread_get_curr_id(), i);

	return(i);
}

/*************************************************************************
Suspends the calling thread to wait for the event in its thread slot.
NOTE! The server mutex has to be reserved by the caller! */
static
os_event_t
srv_suspend_thread(void)
/*====================*/
			/* out: event for the calling thread to wait */
{
	srv_slot_t*	slot;
	os_event_t	event;
	ulint		slot_no;
	ulint		type;

	ut_ad(mutex_own(&kernel_mutex));
	
	slot_no = thr_local_get_slot_no(os_thread_get_curr_id());

	if (srv_print_thread_releases) {
	
		printf("Suspending thread %lu to slot %lu meter %lu\n",
		os_thread_get_curr_id(), slot_no, srv_meter[SRV_RECOVERY]);
	}

	slot = srv_table_get_nth_slot(slot_no);

	type = slot->type;

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

	event = slot->event;
	
	slot->suspended = TRUE;

	ut_ad(srv_n_threads_active[type] > 0);

	srv_n_threads_active[type]--;

	os_event_reset(event);

	return(event);
}

/*************************************************************************
Releases threads of the type given from suspension in the thread table.
NOTE! The server mutex has to be reserved by the caller! */

ulint
srv_release_threads(
/*================*/
			/* out: number of threads released: this may be
			< n if not enough threads were suspended at the
			moment */
	ulint	type,	/* in: thread type */
	ulint	n)	/* in: number of threads to release */
{
	srv_slot_t*	slot;
	ulint		i;
	ulint		count	= 0;

	ut_ad(type >= SRV_WORKER);
	ut_ad(type <= SRV_MASTER);
	ut_ad(n > 0);
	ut_ad(mutex_own(&kernel_mutex));
	
	for (i = 0; i < OS_THREAD_MAX_N; i++) {
	
		slot = srv_table_get_nth_slot(i);

unknown's avatar
unknown committed
665
		if (slot->in_use && slot->type == type && slot->suspended) {
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
			
			slot->suspended = FALSE;

			srv_n_threads_active[type]++;

			os_event_set(slot->event);

			if (srv_print_thread_releases) {
				printf(
		"Releasing thread %lu type %lu from slot %lu meter %lu\n",
				slot->id, type, i, srv_meter[SRV_RECOVERY]);
			}

			count++;

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

	return(count);
}

/*************************************************************************
Returns the calling thread type. */

ulint
srv_get_thread_type(void)
/*=====================*/
			/* out: SRV_COM, ... */
{
	ulint		slot_no;
	srv_slot_t*	slot;
	ulint		type;

	mutex_enter(&kernel_mutex);
	
	slot_no = thr_local_get_slot_no(os_thread_get_curr_id());

	slot = srv_table_get_nth_slot(slot_no);

	type = slot->type;

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

	mutex_exit(&kernel_mutex);

	return(type);
}

/***********************************************************************
Increments by 1 the count of active threads of the type given
and releases master thread if necessary. */
static
void
srv_inc_thread_count(
/*=================*/
	ulint	type)	/* in: type of the thread */
{
	mutex_enter(&kernel_mutex);

	srv_activity_count++;
	
	srv_n_threads_active[type]++;
		
	if (srv_n_threads_active[SRV_MASTER] == 0) {

		srv_release_threads(SRV_MASTER, 1);
	}

	mutex_exit(&kernel_mutex);
}

/***********************************************************************
Decrements by 1 the count of active threads of the type given. */
static
void
srv_dec_thread_count(
/*=================*/
	ulint	type)	/* in: type of the thread */

{
	mutex_enter(&kernel_mutex);

	/* FIXME: the following assertion sometimes fails: */

	if (srv_n_threads_active[type] == 0) {
		printf("Error: thread type %lu\n", type);

		ut_ad(0);
	}	

	srv_n_threads_active[type]--;

	mutex_exit(&kernel_mutex);
}

/***********************************************************************
Calculates the number of allowed utility threads for a thread to decide if
it has to suspend itself in the thread table. */
static
ulint
srv_max_n_utilities(
/*================*/
			/* out: maximum number of allowed utilities
			of the type given */
	ulint	type)	/* in: utility type */
{
	ulint	ret;

	if (srv_n_threads_active[SRV_COM] == 0) {
		if (srv_meter[type] > srv_meter_low_water[type]) {
			return(srv_n_threads[type] / 2);
		} else {
			return(0);
		}
	} else {

		if (srv_meter[type] < srv_meter_foreground[type]) {
			return(0);
		}
		ret = 1 + ((srv_n_threads[type]
		     * (ulint)(srv_meter[type] - srv_meter_foreground[type]))
		     / (ulint)(1000 - srv_meter_foreground[type]));
		if (ret > srv_n_threads[type]) {
			return(srv_n_threads[type]);
		} else {
			return(ret);
		}
	}
}

/***********************************************************************
Increments the utility meter by the value given and releases utility
threads if necessary. */

void
srv_increment_meter(
/*================*/
	ulint	type,	/* in: utility type */
	ulint	n)	/* in: value to add to meter */
{
	ulint	m;

	mutex_enter(&kernel_mutex);

	srv_meter[type] += n;

	m = srv_max_n_utilities(type);

	if (m > srv_n_threads_active[type]) {
		
		srv_release_threads(type, m - srv_n_threads_active[type]);
	}

	mutex_exit(&kernel_mutex);
}

/***********************************************************************
Releases max number of utility threads if no queries are active and
the high-water mark for the utility is exceeded. */

void
srv_release_max_if_no_queries(void)
/*===============================*/
{
	ulint	m;
	ulint	type;

	mutex_enter(&kernel_mutex);

	if (srv_n_threads_active[SRV_COM] > 0) {
		mutex_exit(&kernel_mutex);

		return;
	}

	type = SRV_RECOVERY;
	
	m = srv_n_threads[type] / 2;

	if ((srv_meter[type] > srv_meter_high_water[type])
				&& (srv_n_threads_active[type] < m)) {

		srv_release_threads(type, m - srv_n_threads_active[type]);

		printf("Releasing max background\n");
	}

	mutex_exit(&kernel_mutex);
}

860
#ifdef notdefined
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
/***********************************************************************
Releases one utility thread if no queries are active and
the high-water mark 2 for the utility is exceeded. */
static
void
srv_release_one_if_no_queries(void)
/*===============================*/
{
	ulint	m;
	ulint	type;

	mutex_enter(&kernel_mutex);

	if (srv_n_threads_active[SRV_COM] > 0) {
		mutex_exit(&kernel_mutex);

		return;
	}

	type = SRV_RECOVERY;
	
	m = 1;

	if ((srv_meter[type] > srv_meter_high_water2[type])
	   				&& (srv_n_threads_active[type] < m)) {

		srv_release_threads(type, m - srv_n_threads_active[type]);

		printf("Releasing one background\n");
	}

	mutex_exit(&kernel_mutex);
}

/***********************************************************************
Decrements the utility meter by the value given and suspends the calling
thread, which must be an utility thread of the type given, if necessary. */
static
void
srv_decrement_meter(
/*================*/
	ulint	type,	/* in: utility type */
	ulint	n)	/* in: value to subtract from meter */
{
	ulint		opt;
	os_event_t	event;
	
	mutex_enter(&kernel_mutex);

	if (srv_meter[type] < n) {
		srv_meter[type] = 0;
	} else {
		srv_meter[type] -= n;
	}

	opt = srv_max_n_utilities(type);

	if (opt < srv_n_threads_active[type]) {
		
 		event = srv_suspend_thread();
		mutex_exit(&kernel_mutex);

		os_event_wait(event);
	} else {
		mutex_exit(&kernel_mutex);
	}
}
#endif

/*************************************************************************
Implements the server console. */

ulint
srv_console(
/*========*/
			/* out: return code, not used */
	void*	arg)	/* in: argument, not used */
{
	char	command[256];

	UT_NOT_USED(arg);

	mutex_enter(&kernel_mutex);
	srv_table_reserve_slot(SRV_CONSOLE);
	mutex_exit(&kernel_mutex);

	os_event_wait(srv_sys->operational);

	for (;;) {
		scanf("%s", command);
		
		srv_inc_thread_count(SRV_CONSOLE);

		if (command[0] == 'c') {
			printf("Making checkpoint\n");

			log_make_checkpoint_at(ut_dulint_max, TRUE);

			printf("Checkpoint completed\n");

		} else if (command[0] == 'd') {
			srv_sim_disk_wait_pct = atoi(command + 1);

			printf(
			"Starting disk access simulation with pct %lu\n",
							srv_sim_disk_wait_pct);
		} else {
			printf("\nNot supported!\n");
		}

		srv_dec_thread_count(SRV_CONSOLE);
	}
	
	return(0);
}

/*************************************************************************
Creates the first communication endpoint for the server. This
first call also initializes the com0com.* module. */
980

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
void
srv_communication_init(
/*===================*/
	char*	endpoint)	/* in: server address */
{
	ulint	ret;
	ulint	len;

	srv_sys->endpoint = com_endpoint_create(COM_SHM);

	ut_a(srv_sys->endpoint);

	len = ODBC_DATAGRAM_SIZE;
	
	ret = com_endpoint_set_option(srv_sys->endpoint,
					COM_OPT_MAX_DGRAM_SIZE,
					(byte*)&len, sizeof(ulint));
	ut_a(ret == 0);

	ret = com_bind(srv_sys->endpoint, endpoint, ut_strlen(endpoint));
	
	ut_a(ret == 0);
}
1004 1005

#ifdef notdefined
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
	
/*************************************************************************
Implements the recovery utility. */
static
ulint
srv_recovery_thread(
/*================*/
			/* out: return code, not used */
	void*	arg)	/* in: not used */
{
	ulint	slot_no;
	os_event_t event;

	UT_NOT_USED(arg);
	
	slot_no = srv_table_reserve_slot(SRV_RECOVERY);

	os_event_wait(srv_sys->operational);

	for (;;) {
		/* Finish a possible recovery */

		srv_inc_thread_count(SRV_RECOVERY);

/*		recv_recovery_from_checkpoint_finish(); */

		srv_dec_thread_count(SRV_RECOVERY);

		mutex_enter(&kernel_mutex);
 		event = srv_suspend_thread();
		mutex_exit(&kernel_mutex);

		/* Wait for somebody to release this thread; (currently, this
		should never be released) */

		os_event_wait(event);
	}

	return(0);
}

/*************************************************************************
Implements the purge utility. */

ulint
srv_purge_thread(
/*=============*/
			/* out: return code, not used */
	void*	arg)	/* in: not used */
{
	UT_NOT_USED(arg);

	os_event_wait(srv_sys->operational);

	for (;;) {
		trx_purge();
	}

	return(0);
}
1066
#endif /* notdefined */
1067 1068 1069 1070 1071 1072 1073 1074

/*************************************************************************
Creates the utility threads. */

void
srv_create_utility_threads(void)
/*============================*/
{
1075 1076
/*      os_thread_t	thread;
 	os_thread_id_t	thr_id; */
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
	ulint		i;

	mutex_enter(&kernel_mutex);

	srv_n_threads[SRV_RECOVERY] = 1;
	srv_n_threads_active[SRV_RECOVERY] = 1;

	mutex_exit(&kernel_mutex);

	for (i = 0; i < 1; i++) {
1087
	  /* thread = os_thread_create(srv_recovery_thread, NULL, &thr_id); */
1088

1089
	  /* ut_a(thread); */
1090 1091 1092 1093 1094 1095 1096
	}

/*	thread = os_thread_create(srv_purge_thread, NULL, &thr_id);

	ut_a(thread); */
}

1097
#ifdef notdefined
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
/*************************************************************************
Implements the communication threads. */
static
ulint
srv_com_thread(
/*===========*/
			/* out: return code; not used */
	void*	arg)	/* in: not used */
{
	byte*	msg_buf;
	byte*	addr_buf;
	ulint	msg_len;
	ulint	addr_len;
	ulint	ret;

	UT_NOT_USED(arg);

	srv_table_reserve_slot(SRV_COM);

	os_event_wait(srv_sys->operational);

	msg_buf = mem_alloc(com_endpoint_get_max_size(srv_sys->endpoint));
	addr_buf = mem_alloc(COM_MAX_ADDR_LEN);
	
	for (;;) {
		ret = com_recvfrom(srv_sys->endpoint, msg_buf,
				com_endpoint_get_max_size(srv_sys->endpoint),
				&msg_len, (char*)addr_buf, COM_MAX_ADDR_LEN,
				&addr_len);
		ut_a(ret == 0);

		srv_inc_thread_count(SRV_COM);
		
		sess_process_cli_msg(msg_buf, msg_len, addr_buf, addr_len);

/*		srv_increment_meter(SRV_RECOVERY, 1); */

		srv_dec_thread_count(SRV_COM);

		/* Release one utility thread for each utility if
		high water mark 2 is exceeded and there are no
		active queries. This is done to utilize possible
		quiet time in the server. */

		srv_release_one_if_no_queries();
	}		

	return(0);
}
1147
#endif
1148 1149 1150 1151 1152 1153 1154 1155

/*************************************************************************
Creates the communication threads. */

void
srv_create_com_threads(void)
/*========================*/
{
1156 1157
  /*	os_thread_t	thread;
	os_thread_id_t	thr_id; */
1158 1159 1160 1161 1162
	ulint		i;

	srv_n_threads[SRV_COM] = srv_n_com_threads;

	for (i = 0; i < srv_n_com_threads; i++) {
1163
	  /* thread = os_thread_create(srv_com_thread, NULL, &thr_id); */
1164
	  /* ut_a(thread); */
1165 1166 1167
	}
}

1168
#ifdef notdefined
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
/*************************************************************************
Implements the worker threads. */
static
ulint
srv_worker_thread(
/*==============*/
			/* out: return code, not used */
	void*	arg)	/* in: not used */
{
	os_event_t	event;
	
	UT_NOT_USED(arg);

	srv_table_reserve_slot(SRV_WORKER);

	os_event_wait(srv_sys->operational);

	for (;;) {
		mutex_enter(&kernel_mutex);
 		event = srv_suspend_thread();
		mutex_exit(&kernel_mutex);

		/* Wait for somebody to release this thread */
		os_event_wait(event);

		srv_inc_thread_count(SRV_WORKER);

		/* Check in the server task queue if there is work for this
		thread, and do the work */

		srv_que_task_queue_check();				

		srv_dec_thread_count(SRV_WORKER);

		/* Release one utility thread for each utility if
		high water mark 2 is exceeded and there are no
		active queries. This is done to utilize possible
		quiet time in the server. */

		srv_release_one_if_no_queries();
	}		

	return(0);
}
1213
#endif
1214 1215 1216

/*************************************************************************
Creates the worker threads. */
1217

1218 1219 1220 1221
void
srv_create_worker_threads(void)
/*===========================*/
{
1222 1223
/*	os_thread_t	thread;
	os_thread_id_t	thr_id; */
1224 1225 1226 1227 1228 1229
	ulint		i;

	srv_n_threads[SRV_WORKER] = srv_n_worker_threads;
	srv_n_threads_active[SRV_WORKER] = srv_n_worker_threads;

	for (i = 0; i < srv_n_worker_threads; i++) {
1230
	  /* thread = os_thread_create(srv_worker_thread, NULL, &thr_id); */
1231
	  /* ut_a(thread); */
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
	}
}

#ifdef notdefined
/*************************************************************************
Reads a keyword and a value from a file. */

ulint
srv_read_init_val(
/*==============*/
				/* out: DB_SUCCESS or error code */
	FILE*	initfile,	/* in: file pointer */
	char*	keyword,	/* in: keyword before value(s), or NULL if
				no keyword read */
	char*	str_buf,	/* in/out: buffer for a string value to read,
				buffer size must be 10000 bytes, if NULL
				then not read */
	ulint*	num_val,	/* out:	numerical value to read, if NULL
				then not read */
	ibool	print_not_err)	/* in: if TRUE, then we will not print
				error messages to console */
{		
	ulint	ret;
	char	scan_buf[10000];

	if (keyword == NULL) {

		goto skip_keyword;
	}
	
	ret = fscanf(initfile, "%9999s", scan_buf);
	
	if (ret == 0 || ret == EOF || 0 != ut_strcmp(scan_buf, keyword)) {
		if (print_not_err) {

			return(DB_ERROR);
		}
		
1270
		printf("Error in InnoDB booting: keyword %s not found\n",
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
							keyword);
		printf("from the initfile!\n");

		return(DB_ERROR);
	}
skip_keyword:
	if (num_val == NULL && str_buf == NULL) {

		return(DB_SUCCESS);
	}		

	ret = fscanf(initfile, "%9999s", scan_buf);
	
	if (ret == EOF || ret == 0) {
		if (print_not_err) {

			return(DB_ERROR);
		}

		printf(
1291
	"Error in InnoDB booting: could not read first value after %s\n",
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
								keyword);
		printf("from the initfile!\n");

		return(DB_ERROR);
	}

	if (str_buf) {
		ut_memcpy(str_buf, scan_buf, 10000);

		printf("init keyword %s value %s read\n", keyword, str_buf);

		if (!num_val) {
			return(DB_SUCCESS);
		}

		ret = fscanf(initfile, "%9999s", scan_buf);
	
		if (ret == EOF || ret == 0) {

			if (print_not_err) {

				return(DB_ERROR);
			}
			
			printf(
1317
	"Error in InnoDB booting: could not read second value after %s\n",
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
							keyword);
			printf("from the initfile!\n");

			return(DB_ERROR);
		}
	}

	if (ut_strlen(scan_buf) > 9) {

		if (print_not_err) {

			return(DB_ERROR);
		}

		printf(
1333
	"Error in InnoDB booting: numerical value too big after %s\n",
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
								keyword);
		printf("in the initfile!\n");

		return(DB_ERROR);
	}

	*num_val = (ulint)atoi(scan_buf);

	if (*num_val >= 1000000000) {

		if (print_not_err) {

			return(DB_ERROR);
		}

		printf(
1350
	"Error in InnoDB booting: numerical value too big after %s\n",
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
							keyword);
		printf("in the initfile!\n");

		return(DB_ERROR);
	}

	printf("init keyword %s value %lu read\n", keyword, *num_val);

	return(DB_SUCCESS);
}

/*************************************************************************
Reads keywords and values from an initfile. */

ulint
srv_read_initfile(
/*==============*/
				/* out: DB_SUCCESS or error code */
	FILE*	initfile)	/* in: file pointer */
{
	char	str_buf[10000];
	ulint	n;
	ulint	i;
	ulint	ulint_val;
	ulint	val1;
	ulint	val2;
	ulint	err;

	err = srv_read_init_val(initfile, "INNOBASE_DATA_HOME_DIR",
						str_buf, NULL, FALSE);
	if (err != DB_SUCCESS) return(err);

	srv_data_home = ut_malloc(ut_strlen(str_buf) + 1);
	ut_memcpy(srv_data_home, str_buf, ut_strlen(str_buf) + 1);
		
	err = srv_read_init_val(initfile,"TABLESPACE_NUMBER_OF_DATA_FILES",
							NULL, &n, FALSE);
	if (err != DB_SUCCESS) return(err);

	srv_n_data_files = n;

	srv_data_file_names = ut_malloc(n * sizeof(char*));
	srv_data_file_sizes = ut_malloc(n * sizeof(ulint));
	
	for (i = 0; i < n; i++) {
		err = srv_read_init_val(initfile,
				"DATA_FILE_PATH_AND_SIZE_MB",
						str_buf, &ulint_val, FALSE);
		if (err != DB_SUCCESS) return(err);

		srv_data_file_names[i] = ut_malloc(ut_strlen(str_buf) + 1);
		ut_memcpy(srv_data_file_names[i], str_buf,
						ut_strlen(str_buf) + 1);
		srv_data_file_sizes[i] = ulint_val
					* ((1024 * 1024) / UNIV_PAGE_SIZE);
	}		

	err = srv_read_init_val(initfile,
				"NUMBER_OF_MIRRORED_LOG_GROUPS", NULL,
						&srv_n_log_groups, FALSE);	
	if (err != DB_SUCCESS) return(err);

	err = srv_read_init_val(initfile,
				"NUMBER_OF_LOG_FILES_IN_GROUP", NULL,
						&srv_n_log_files, FALSE);
	if (err != DB_SUCCESS) return(err);

	err = srv_read_init_val(initfile, "LOG_FILE_SIZE_KB", NULL,
						&srv_log_file_size, FALSE);
	if (err != DB_SUCCESS) return(err);

	srv_log_file_size = srv_log_file_size / (UNIV_PAGE_SIZE / 1024);

	srv_log_group_home_dirs = ut_malloc(srv_n_log_files * sizeof(char*));

	for (i = 0; i < srv_n_log_groups; i++) {
	
		err = srv_read_init_val(initfile,
					"INNOBASE_LOG_GROUP_HOME_DIR",
							str_buf, NULL, FALSE);
		if (err != DB_SUCCESS) return(err);

		srv_log_group_home_dirs[i] = ut_malloc(ut_strlen(str_buf) + 1);
		ut_memcpy(srv_log_group_home_dirs[i], str_buf,
							ut_strlen(str_buf) + 1);
	}

	err = srv_read_init_val(initfile, "INNOBASE_LOG_ARCH_DIR",
						str_buf, NULL, FALSE);
	if (err != DB_SUCCESS) return(err);

	srv_arch_dir = ut_malloc(ut_strlen(str_buf) + 1);
	ut_memcpy(srv_arch_dir, str_buf, ut_strlen(str_buf) + 1);
	
	err = srv_read_init_val(initfile, "LOG_ARCHIVE_ON(1/0)", NULL,
						&srv_log_archive_on, FALSE);
	if (err != DB_SUCCESS) return(err);
							
	err = srv_read_init_val(initfile, "LOG_BUFFER_SIZE_KB", NULL,
						&srv_log_buffer_size, FALSE);
	if (err != DB_SUCCESS) return(err);

	srv_log_buffer_size = srv_log_buffer_size / (UNIV_PAGE_SIZE / 1024);

	err = srv_read_init_val(initfile, "FLUSH_LOG_AT_TRX_COMMIT(1/0)", NULL,
				&srv_flush_log_at_trx_commit, FALSE);
	if (err != DB_SUCCESS) return(err);
	
	err = srv_read_init_val(initfile, "BUFFER_POOL_SIZE_MB", NULL,
						&srv_pool_size, FALSE);
	if (err != DB_SUCCESS) return(err);

	srv_pool_size = srv_pool_size * ((1024 * 1024) / UNIV_PAGE_SIZE);
	
	err = srv_read_init_val(initfile, "ADDITIONAL_MEM_POOL_SIZE_MB", NULL,
						&srv_mem_pool_size, FALSE);
	if (err != DB_SUCCESS) return(err);
	
	srv_mem_pool_size = srv_mem_pool_size * 1024 * 1024;

	srv_lock_table_size = 20 * srv_pool_size;

	err = srv_read_init_val(initfile, "NUMBER_OF_FILE_IO_THREADS", NULL,
						&srv_n_file_io_threads, FALSE);
	if (err != DB_SUCCESS) return(err);
	
	err = srv_read_init_val(initfile, "SRV_RECOVER_FROM_BACKUP",
							NULL, NULL, TRUE);
	if (err == DB_SUCCESS) {
		srv_archive_recovery = TRUE;
		srv_archive_recovery_limit_lsn = ut_dulint_max;
		
		err = srv_read_init_val(initfile, NULL, NULL, &val1, TRUE);
		err = srv_read_init_val(initfile, NULL, NULL, &val2, TRUE);

		if (err == DB_SUCCESS) {
			srv_archive_recovery_limit_lsn =
					ut_dulint_create(val1, val2);
		}
	}	

	/* err = srv_read_init_val(initfile,
				"SYNC_NUMBER_OF_SPIN_WAIT_ROUNDS", NULL,
						&srv_n_spin_wait_rounds);

	err = srv_read_init_val(initfile, "SYNC_SPIN_WAIT_DELAY", NULL,
						&srv_spin_wait_delay); */
	return(DB_SUCCESS);
}

/*************************************************************************
Reads keywords and a values from an initfile. In case of an error, exits
from the process. */

void
srv_read_initfile(
/*==============*/
	FILE*	initfile)	/* in: file pointer */
{
	char	str_buf[10000];
	ulint	ulint_val;

	srv_read_init_val(initfile, FALSE, "SRV_ENDPOINT_NAME", str_buf,
								&ulint_val);
	ut_a(ut_strlen(str_buf) < COM_MAX_ADDR_LEN);
	
	ut_memcpy(srv_endpoint_name, str_buf, COM_MAX_ADDR_LEN);

	srv_read_init_val(initfile, TRUE, "SRV_N_COM_THREADS", str_buf,
						&srv_n_com_threads);

	srv_read_init_val(initfile, TRUE, "SRV_N_WORKER_THREADS", str_buf,
						&srv_n_worker_threads);

	srv_read_init_val(initfile, TRUE, "SYNC_N_SPIN_WAIT_ROUNDS", str_buf,
						&srv_n_spin_wait_rounds);

	srv_read_init_val(initfile, TRUE, "SYNC_SPIN_WAIT_DELAY", str_buf,
						&srv_spin_wait_delay);

	srv_read_init_val(initfile, TRUE, "THREAD_PRIORITY_BOOST", str_buf,
						&srv_priority_boost);

	srv_read_init_val(initfile, TRUE, "N_SPACES", str_buf, &srv_n_spaces);
	srv_read_init_val(initfile, TRUE, "N_FILES", str_buf, &srv_n_files);
	srv_read_init_val(initfile, TRUE, "FILE_SIZE", str_buf,
							&srv_file_size);

	srv_read_init_val(initfile, TRUE, "N_LOG_GROUPS", str_buf,
							&srv_n_log_groups);
	srv_read_init_val(initfile, TRUE, "N_LOG_FILES", str_buf,
							&srv_n_log_files);
	srv_read_init_val(initfile, TRUE, "LOG_FILE_SIZE", str_buf,
							&srv_log_file_size);
	srv_read_init_val(initfile, TRUE, "LOG_ARCHIVE_ON", str_buf,
							&srv_log_archive_on);
	srv_read_init_val(initfile, TRUE, "LOG_BUFFER_SIZE", str_buf,
						&srv_log_buffer_size);
	srv_read_init_val(initfile, TRUE, "FLUSH_LOG_AT_TRX_COMMIT", str_buf,
						&srv_flush_log_at_trx_commit);
	
	
	srv_read_init_val(initfile, TRUE, "POOL_SIZE", str_buf,
						&srv_pool_size);
	srv_read_init_val(initfile, TRUE, "MEM_POOL_SIZE", str_buf,
						&srv_mem_pool_size);
	srv_read_init_val(initfile, TRUE, "LOCK_TABLE_SIZE", str_buf,
						&srv_lock_table_size);

	srv_read_init_val(initfile, TRUE, "SIM_DISK_WAIT_PCT", str_buf,
						&srv_sim_disk_wait_pct);

	srv_read_init_val(initfile, TRUE, "SIM_DISK_WAIT_LEN", str_buf,
						&srv_sim_disk_wait_len);

	srv_read_init_val(initfile, TRUE, "SIM_DISK_WAIT_BY_YIELD", str_buf,
						&srv_sim_disk_wait_by_yield);

	srv_read_init_val(initfile, TRUE, "SIM_DISK_WAIT_BY_WAIT", str_buf,
						&srv_sim_disk_wait_by_wait);

	srv_read_init_val(initfile, TRUE, "MEASURE_CONTENTION", str_buf,
						&srv_measure_contention);

	srv_read_init_val(initfile, TRUE, "MEASURE_BY_SPIN", str_buf,
						&srv_measure_by_spin);
	

	srv_read_init_val(initfile, TRUE, "PRINT_THREAD_RELEASES", str_buf,
						&srv_print_thread_releases);
	
	srv_read_init_val(initfile, TRUE, "PRINT_LOCK_WAITS", str_buf,
						&srv_print_lock_waits);
	if (srv_print_lock_waits) {
		lock_print_waits = TRUE;
	}
	
	srv_read_init_val(initfile, TRUE, "PRINT_BUF_IO", str_buf,
						&srv_print_buf_io);
	if (srv_print_buf_io) {
		buf_debug_prints = TRUE;
	}	
	
	srv_read_init_val(initfile, TRUE, "PRINT_LOG_IO", str_buf,
						&srv_print_log_io);
	if (srv_print_log_io) {
		log_debug_writes = TRUE;
	}	
	
	srv_read_init_val(initfile, TRUE, "PRINT_PARSED_SQL", str_buf,
						&srv_print_parsed_sql);
	if (srv_print_parsed_sql) {
		pars_print_lexed = TRUE;
	}

	srv_read_init_val(initfile, TRUE, "PRINT_LATCH_WAITS", str_buf,
						&srv_print_latch_waits);

	srv_read_init_val(initfile, TRUE, "TEST_EXTRA_MUTEXES", str_buf,
						&srv_test_extra_mutexes);
	srv_read_init_val(initfile, TRUE, "TEST_NOCACHE", str_buf,
						&srv_test_nocache);
	srv_read_init_val(initfile, TRUE, "TEST_CACHE_EVICT", str_buf,
						&srv_test_cache_evict);

	srv_read_init_val(initfile, TRUE, "TEST_SYNC", str_buf,
						&srv_test_sync);
	srv_read_init_val(initfile, TRUE, "TEST_N_THREADS", str_buf,
						&srv_test_n_threads);
	srv_read_init_val(initfile, TRUE, "TEST_N_LOOPS", str_buf,
						&srv_test_n_loops);
	srv_read_init_val(initfile, TRUE, "TEST_N_FREE_RNDS", str_buf,
						&srv_test_n_free_rnds);
	srv_read_init_val(initfile, TRUE, "TEST_N_RESERVED_RNDS", str_buf,
						&srv_test_n_reserved_rnds);
	srv_read_init_val(initfile, TRUE, "TEST_N_MUTEXES", str_buf,
						&srv_test_n_mutexes);
	srv_read_init_val(initfile, TRUE, "TEST_ARRAY_SIZE", str_buf,
						&srv_test_array_size);
}
#endif

/*************************************************************************
Initializes the server. */
unknown's avatar
unknown committed
1635

1636 1637 1638 1639
void
srv_init(void)
/*==========*/
{
unknown's avatar
Merge  
unknown committed
1640 1641 1642
	srv_conc_slot_t* 	conc_slot;
	srv_slot_t*		slot;
	ulint			i;
1643 1644 1645 1646 1647 1648

	srv_sys = mem_alloc(sizeof(srv_sys_t));

	kernel_mutex_temp = mem_alloc(sizeof(mutex_t));
	mutex_create(&kernel_mutex);
	mutex_set_level(&kernel_mutex, SYNC_KERNEL);
unknown's avatar
unknown committed
1649 1650 1651

	mutex_create(&srv_innodb_monitor_mutex);
	mutex_set_level(&srv_innodb_monitor_mutex, SYNC_NO_ORDER_CHECK);
1652 1653 1654 1655 1656 1657
	
	srv_sys->threads = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));

	for (i = 0; i < OS_THREAD_MAX_N; i++) {
		slot = srv_table_get_nth_slot(i);
		slot->in_use = FALSE;
unknown's avatar
unknown committed
1658
                slot->type=0;	/* Avoid purify errors */
1659 1660 1661 1662 1663 1664 1665 1666 1667
		slot->event = os_event_create(NULL);
		ut_a(slot->event);
	}

	srv_mysql_table = mem_alloc(OS_THREAD_MAX_N * sizeof(srv_slot_t));

	for (i = 0; i < OS_THREAD_MAX_N; i++) {
		slot = srv_mysql_table + i;
		slot->in_use = FALSE;
unknown's avatar
unknown committed
1668
		slot->type = 0;
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
		slot->event = os_event_create(NULL);
		ut_a(slot->event);
	}

	srv_lock_timeout_thread_event = os_event_create(NULL);
	
	for (i = 0; i < SRV_MASTER + 1; i++) {
		srv_n_threads_active[i] = 0;
		srv_n_threads[i] = 0;
		srv_meter[i] = 30;
		srv_meter_low_water[i] = 50;
		srv_meter_high_water[i] = 100;
		srv_meter_high_water2[i] = 200;
		srv_meter_foreground[i] = 250;
	}
	
	srv_sys->operational = os_event_create(NULL);

	ut_a(srv_sys->operational);

	UT_LIST_INIT(srv_sys->tasks);
unknown's avatar
Merge  
unknown committed
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702

	/* Init the server concurrency restriction data structures */

	os_fast_mutex_init(&srv_conc_mutex);
	
	UT_LIST_INIT(srv_conc_queue);
	
	for (i = 0; i < OS_THREAD_MAX_N; i++) {
		conc_slot = srv_conc_slots + i;
		conc_slot->reserved = FALSE;
		conc_slot->event = os_event_create(NULL);
		ut_a(conc_slot->event);
	}
1703
}	
unknown's avatar
unknown committed
1704

1705
/*************************************************************************
unknown's avatar
unknown committed
1706
Frees the OS fast mutex created in srv_init(). */
unknown's avatar
unknown committed
1707

1708
void
unknown's avatar
unknown committed
1709 1710
srv_free(void)
/*==========*/
1711
{
unknown's avatar
unknown committed
1712
	os_fast_mutex_free(&srv_conc_mutex);
1713 1714
}

unknown's avatar
unknown committed
1715
/*************************************************************************
unknown's avatar
unknown committed
1716
Initializes the synchronization primitives, memory system, and the thread
unknown's avatar
unknown committed
1717 1718 1719
local storage. */

void
unknown's avatar
unknown committed
1720
srv_general_init(void)
unknown's avatar
unknown committed
1721 1722
/*==================*/
{
unknown's avatar
unknown committed
1723 1724 1725 1726
	os_sync_init();
	sync_init();
	mem_init(srv_mem_pool_size);
	thr_local_init();
unknown's avatar
unknown committed
1727 1728
}

unknown's avatar
unknown committed
1729 1730
/*======================= InnoDB Server FIFO queue =======================*/

unknown's avatar
unknown committed
1731

unknown's avatar
Merge  
unknown committed
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
/*************************************************************************
Puts an OS thread to wait if there are too many concurrent threads
(>= srv_thread_concurrency) inside InnoDB. The threads wait in a FIFO queue. */

void
srv_conc_enter_innodb(
/*==================*/
	trx_t*	trx)	/* in: transaction object associated with the
			thread */
{
unknown's avatar
unknown committed
1742
	ibool			has_slept = FALSE;
unknown's avatar
Merge  
unknown committed
1743 1744
	srv_conc_slot_t*	slot;
	ulint			i;
unknown's avatar
unknown committed
1745
	char                    err_buf[1000];
unknown's avatar
Merge  
unknown committed
1746

unknown's avatar
unknown committed
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
	if (srv_thread_concurrency >= 500) {
		/* Disable the concurrency check */
	
		return;
	}

	/* If trx has 'free tickets' to enter the engine left, then use one
	such ticket */

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

		return;
	}
unknown's avatar
unknown committed
1761

unknown's avatar
Merge  
unknown committed
1762
	os_fast_mutex_lock(&srv_conc_mutex);
unknown's avatar
unknown committed
1763
retry:
unknown's avatar
unknown committed
1764 1765 1766 1767 1768 1769 1770 1771
	if (trx->declared_to_be_inside_innodb) {
	        ut_print_timestamp(stderr);

	        trx_print(err_buf, trx);

	        fprintf(stderr,
"  InnoDB: Error: trying to declare trx to enter InnoDB, but\n"
"InnoDB: it already is declared.\n%s\n", err_buf);
unknown's avatar
unknown committed
1772 1773 1774
		os_fast_mutex_unlock(&srv_conc_mutex);

		return;
unknown's avatar
unknown committed
1775 1776
	}

unknown's avatar
unknown committed
1777
	if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
unknown's avatar
Merge  
unknown committed
1778

unknown's avatar
unknown committed
1779 1780 1781 1782
		srv_conc_n_threads++;
		trx->declared_to_be_inside_innodb = TRUE;
		trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;
		
unknown's avatar
Merge  
unknown committed
1783 1784 1785 1786
		os_fast_mutex_unlock(&srv_conc_mutex);

		return;
	}
unknown's avatar
unknown committed
1787

unknown's avatar
unknown committed
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
	/* If the transaction is not holding resources, let it sleep for 50
	milliseconds, and try again then */
 
	if (!has_slept && !trx->has_search_latch
	    && NULL == UT_LIST_GET_FIRST(trx->trx_locks)) {

	        has_slept = TRUE; /* We let is sleep only once to avoid
				  starvation */

		srv_conc_n_waiting_threads++;

		os_fast_mutex_unlock(&srv_conc_mutex);

1801 1802
		trx->op_info = (char*)"sleeping before joining InnoDB queue";

unknown's avatar
unknown committed
1803 1804
		os_thread_sleep(50000);

1805 1806
		trx->op_info = (char*)"";

unknown's avatar
unknown committed
1807 1808 1809 1810 1811 1812 1813
		os_fast_mutex_lock(&srv_conc_mutex);

		srv_conc_n_waiting_threads--;

		goto retry;
	}   

unknown's avatar
unknown committed
1814
	/* Too many threads inside: put the current thread to a queue */
unknown's avatar
Merge  
unknown committed
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828

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

		if (!slot->reserved) {
			break;
		}
	}

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

		srv_conc_n_threads++;
unknown's avatar
unknown committed
1829 1830
		trx->declared_to_be_inside_innodb = TRUE;
		trx->n_tickets_to_enter_innodb = 0;
unknown's avatar
Merge  
unknown committed
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849

		os_fast_mutex_unlock(&srv_conc_mutex);

		return;
	}

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

	/* Add to the queue */
	slot->reserved = TRUE;
	slot->wait_ended = FALSE;
	
	UT_LIST_ADD_LAST(srv_conc_queue, srv_conc_queue, slot);

	os_event_reset(slot->event);

unknown's avatar
unknown committed
1850 1851
	srv_conc_n_waiting_threads++;

unknown's avatar
Merge  
unknown committed
1852 1853 1854 1855 1856
	os_fast_mutex_unlock(&srv_conc_mutex);

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

unknown's avatar
unknown committed
1857
	trx->op_info = (char*)"waiting in InnoDB queue";
unknown's avatar
unknown committed
1858

unknown's avatar
Merge  
unknown committed
1859 1860
	os_event_wait(slot->event);

unknown's avatar
unknown committed
1861
	trx->op_info = (char*)"";
unknown's avatar
unknown committed
1862

unknown's avatar
Merge  
unknown committed
1863 1864
	os_fast_mutex_lock(&srv_conc_mutex);

unknown's avatar
unknown committed
1865 1866
	srv_conc_n_waiting_threads--;

unknown's avatar
Merge  
unknown committed
1867 1868 1869 1870 1871 1872 1873
	/* NOTE that the thread which released this thread already
	incremented the thread counter on behalf of this thread */

	slot->reserved = FALSE;

	UT_LIST_REMOVE(srv_conc_queue, srv_conc_queue, slot);

unknown's avatar
unknown committed
1874 1875 1876
	trx->declared_to_be_inside_innodb = TRUE;
	trx->n_tickets_to_enter_innodb = SRV_FREE_TICKETS_TO_ENTER;

unknown's avatar
Merge  
unknown committed
1877 1878 1879 1880 1881 1882 1883 1884
	os_fast_mutex_unlock(&srv_conc_mutex);
}

/*************************************************************************
This lets a thread enter InnoDB regardless of the number of threads inside
InnoDB. This must be called when a thread ends a lock wait. */

void
unknown's avatar
unknown committed
1885 1886 1887 1888
srv_conc_force_enter_innodb(
/*========================*/
	trx_t*	trx)	/* in: transaction object associated with the
			thread */
unknown's avatar
Merge  
unknown committed
1889
{
unknown's avatar
unknown committed
1890 1891 1892 1893 1894
	if (srv_thread_concurrency >= 500) {
	
		return;
	}

unknown's avatar
Merge  
unknown committed
1895 1896 1897
	os_fast_mutex_lock(&srv_conc_mutex);

	srv_conc_n_threads++;
unknown's avatar
unknown committed
1898 1899
	trx->declared_to_be_inside_innodb = TRUE;
	trx->n_tickets_to_enter_innodb = 0;
unknown's avatar
Merge  
unknown committed
1900 1901 1902 1903 1904

	os_fast_mutex_unlock(&srv_conc_mutex);
}

/*************************************************************************
unknown's avatar
unknown committed
1905 1906
This must be called when a thread exits InnoDB in a lock wait or at the
end of an SQL statement. */
unknown's avatar
Merge  
unknown committed
1907 1908

void
unknown's avatar
unknown committed
1909 1910 1911 1912
srv_conc_force_exit_innodb(
/*=======================*/
	trx_t*	trx)	/* in: transaction object associated with the
			thread */
unknown's avatar
Merge  
unknown committed
1913 1914 1915
{
	srv_conc_slot_t*	slot	= NULL;

unknown's avatar
unknown committed
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
	if (srv_thread_concurrency >= 500) {
	
		return;
	}

	if (trx->declared_to_be_inside_innodb == FALSE) {
		
		return;
	}

unknown's avatar
Merge  
unknown committed
1926 1927 1928
	os_fast_mutex_lock(&srv_conc_mutex);

	srv_conc_n_threads--;
unknown's avatar
unknown committed
1929 1930
	trx->declared_to_be_inside_innodb = FALSE;
	trx->n_tickets_to_enter_innodb = 0;
unknown's avatar
Merge  
unknown committed
1931

unknown's avatar
unknown committed
1932
	if (srv_conc_n_threads < (lint)srv_thread_concurrency) {
unknown's avatar
Merge  
unknown committed
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
		/* Look for a slot where a thread is waiting and no other
		thread has yet released the thread */
	
		slot = UT_LIST_GET_FIRST(srv_conc_queue);

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

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

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

			srv_conc_n_threads++;
		}
	}

	os_fast_mutex_unlock(&srv_conc_mutex);

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

unknown's avatar
unknown committed
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
/*************************************************************************
This must be called when a thread exits InnoDB. */

void
srv_conc_exit_innodb(
/*=================*/
	trx_t*	trx)	/* in: transaction object associated with the
			thread */
{
	if (srv_thread_concurrency >= 500) {
	
		return;
	}

	if (trx->n_tickets_to_enter_innodb > 0) {
		/* We will pretend the thread is still inside InnoDB though it
		now leaves the InnoDB engine. In this way we save
		a lot of semaphore operations. srv_conc_force_exit_innodb is
		used to declare the thread definitely outside InnoDB. It
		should be called when there is a lock wait or an SQL statement
		ends. */

		return;
	}

	srv_conc_force_exit_innodb(trx);
}

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

1989
/*************************************************************************
1990
Normalizes init parameter values to use units we use inside InnoDB. */
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
static
ulint
srv_normalize_init_values(void)
/*===========================*/
				/* out: DB_SUCCESS or error code */
{
	ulint	n;
	ulint	i;

	n = srv_n_data_files;
	
	for (i = 0; i < n; i++) {
		srv_data_file_sizes[i] = srv_data_file_sizes[i]
					* ((1024 * 1024) / UNIV_PAGE_SIZE);
	}		

unknown's avatar
unknown committed
2007 2008 2009
	srv_last_file_size_max = srv_last_file_size_max
					* ((1024 * 1024) / UNIV_PAGE_SIZE);
		
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
	srv_log_file_size = srv_log_file_size / UNIV_PAGE_SIZE;

	srv_log_buffer_size = srv_log_buffer_size / UNIV_PAGE_SIZE;

	srv_pool_size = srv_pool_size / UNIV_PAGE_SIZE;
	
	srv_lock_table_size = 20 * srv_pool_size;

	return(DB_SUCCESS);
}

/*************************************************************************
2022
Boots the InnoDB server. */
2023 2024 2025 2026 2027 2028 2029 2030 2031

ulint
srv_boot(void)
/*==========*/
			/* out: DB_SUCCESS or error code */
{
	ulint	err;

	/* Transform the init parameter values given by MySQL to
2032
	use units we use inside InnoDB: */
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
	
	err = srv_normalize_init_values();

	if (err != DB_SUCCESS) {
		return(err);
	}
	
	/* Initialize synchronization primitives, memory management, and thread
	local storage */
	
	srv_general_init();

	/* Initialize this module */

	srv_init();

	return(DB_SUCCESS);
}

/*************************************************************************
Reserves a slot in the thread table for the current MySQL OS thread.
unknown's avatar
unknown committed
2054
NOTE! The kernel mutex has to be reserved by the caller! */
2055 2056 2057 2058 2059 2060 2061 2062 2063
static
srv_slot_t*
srv_table_reserve_slot_for_mysql(void)
/*==================================*/
			/* out: reserved slot */
{
	srv_slot_t*	slot;
	ulint		i;

unknown's avatar
unknown committed
2064 2065
	ut_ad(mutex_own(&kernel_mutex));

2066 2067 2068 2069 2070
	i = 0;
	slot = srv_mysql_table + i;

	while (slot->in_use) {
		i++;
unknown's avatar
unknown committed
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087

		if (i >= OS_THREAD_MAX_N) {

		        ut_print_timestamp(stderr);

		        fprintf(stderr,
"  InnoDB: There appear to be %lu MySQL threads currently waiting\n"
"InnoDB: inside InnoDB, which is the upper limit. Cannot continue operation.\n"
"InnoDB: We intentionally generate a seg fault to print a stack trace\n"
"InnoDB: on Linux. But first we print a list of waiting threads.\n", i);

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

			        slot = srv_mysql_table + i;

			        fprintf(stderr,
"Slot %lu: thread id %lu, type %lu, in use %lu, susp %lu, time %lu\n",
unknown's avatar
unknown committed
2088
				  i, os_thread_pf(slot->id),
unknown's avatar
unknown committed
2089 2090 2091 2092 2093 2094 2095
				  slot->type, slot->in_use,
				  slot->suspended,
			  (ulint)difftime(ut_time(), slot->suspend_time));
			}

		        ut_a(0);
		}
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
		
		slot = srv_mysql_table + i;
	}

	ut_a(slot->in_use == FALSE);
	
	slot->in_use = TRUE;
	slot->id = os_thread_get_curr_id();
	slot->handle = os_thread_get_curr();

	return(slot);
}

/*******************************************************************
unknown's avatar
unknown committed
2110 2111 2112 2113 2114
Puts a MySQL OS thread to wait for a lock to be released. If an error
occurs during the wait trx->error_state associated with thr is
!= DB_SUCCESS when we return. DB_LOCK_WAIT_TIMEOUT and DB_DEADLOCK
are possible errors. DB_DEADLOCK is returned if selective deadlock
resolution chose this transaction as a victim. */
2115

unknown's avatar
unknown committed
2116
void
2117 2118
srv_suspend_mysql_thread(
/*=====================*/
unknown's avatar
unknown committed
2119 2120
	que_thr_t*	thr)	/* in: query thread associated with the MySQL
				OS thread */
2121 2122 2123 2124
{
	srv_slot_t*	slot;
	os_event_t	event;
	double		wait_time;
unknown's avatar
unknown committed
2125
	trx_t*		trx;
unknown's avatar
unknown committed
2126 2127
	ibool		had_dict_lock			= FALSE;
	ibool		was_declared_inside_innodb	= FALSE;
unknown's avatar
unknown committed
2128
	
2129 2130
	ut_ad(!mutex_own(&kernel_mutex));

unknown's avatar
unknown committed
2131 2132
	trx = thr_get_trx(thr);
	
2133 2134 2135 2136
	os_event_set(srv_lock_timeout_thread_event);

	mutex_enter(&kernel_mutex);

unknown's avatar
unknown committed
2137 2138
	trx->error_state = DB_SUCCESS;

2139 2140
	if (thr->state == QUE_THR_RUNNING) {

unknown's avatar
unknown committed
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
		ut_ad(thr->is_active == TRUE);
	
		/* The lock has already been released or this transaction
		was chosen as a deadlock victim: no need to suspend */

		if (trx->was_chosen_as_deadlock_victim) {

			trx->error_state = DB_DEADLOCK;
			trx->was_chosen_as_deadlock_victim = FALSE;
		}
2151 2152 2153

		mutex_exit(&kernel_mutex);

unknown's avatar
unknown committed
2154
		return;
2155 2156
	}
	
unknown's avatar
unknown committed
2157 2158
	ut_ad(thr->is_active == FALSE);

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
	slot = srv_table_reserve_slot_for_mysql();

	event = slot->event;
	
	slot->thr = thr;

	os_event_reset(event);	

	slot->suspend_time = ut_time();

	/* Wake the lock timeout monitor thread, if it is suspended */

	os_event_set(srv_lock_timeout_thread_event);
	
	mutex_exit(&kernel_mutex);

unknown's avatar
unknown committed
2175 2176 2177
	if (trx->declared_to_be_inside_innodb) {

		was_declared_inside_innodb = TRUE;
unknown's avatar
Merge  
unknown committed
2178
	
unknown's avatar
unknown committed
2179 2180 2181 2182 2183 2184
		/* We must declare this OS thread to exit InnoDB, since a
		possible other thread holding a lock which this thread waits
		for must be allowed to enter, sooner or later */
	
		srv_conc_force_exit_innodb(trx);
	}
unknown's avatar
Merge  
unknown committed
2185

unknown's avatar
unknown committed
2186
	/* Release possible foreign key check latch */
unknown's avatar
unknown committed
2187 2188 2189
	if (trx->dict_operation_lock_mode == RW_S_LATCH) {

		had_dict_lock = TRUE;
unknown's avatar
unknown committed
2190

unknown's avatar
unknown committed
2191
		row_mysql_unfreeze_data_dictionary(trx);
unknown's avatar
unknown committed
2192 2193
	}

unknown's avatar
unknown committed
2194 2195
	ut_a(trx->dict_operation_lock_mode == 0);

2196 2197 2198 2199
	/* Wait for the release */
	
	os_event_wait(event);

unknown's avatar
unknown committed
2200
	if (had_dict_lock) {
unknown's avatar
unknown committed
2201

unknown's avatar
unknown committed
2202
		row_mysql_freeze_data_dictionary(trx);
unknown's avatar
unknown committed
2203 2204
	}

unknown's avatar
unknown committed
2205 2206 2207
	if (was_declared_inside_innodb) {

		/* Return back inside InnoDB */
unknown's avatar
Merge  
unknown committed
2208
	
unknown's avatar
unknown committed
2209 2210
		srv_conc_force_enter_innodb(trx);
	}
unknown's avatar
Merge  
unknown committed
2211

2212 2213 2214 2215 2216 2217 2218 2219
	mutex_enter(&kernel_mutex);

	/* Release the slot for others to use */
	
	slot->in_use = FALSE;

	wait_time = ut_difftime(ut_time(), slot->suspend_time);
	
unknown's avatar
unknown committed
2220 2221 2222 2223 2224 2225
	if (trx->was_chosen_as_deadlock_victim) {

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

2226 2227 2228 2229 2230
	mutex_exit(&kernel_mutex);

	if (srv_lock_wait_timeout < 100000000 && 
	    			wait_time > (double)srv_lock_wait_timeout) {

unknown's avatar
unknown committed
2231 2232
	    	trx->error_state = DB_LOCK_WAIT_TIMEOUT;
	}
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
}

/************************************************************************
Releases a MySQL OS thread waiting for a lock to be released, if the
thread is already suspended. */

void
srv_release_mysql_thread_if_suspended(
/*==================================*/
	que_thr_t*	thr)	/* in: query thread associated with the
				MySQL OS thread  */
{
	srv_slot_t*	slot;
	ulint		i;
	
	ut_ad(mutex_own(&kernel_mutex));

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

		slot = srv_mysql_table + i;

		if (slot->in_use && slot->thr == thr) {
			/* Found */

			os_event_set(slot->event);

			return;
		}
	}

	/* not found */
}

unknown's avatar
unknown committed
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
/**********************************************************************
Refreshes the values used to calculate per-second averages. */
static
void
srv_refresh_innodb_monitor_stats(void)
/*==================================*/
{
	mutex_enter(&srv_innodb_monitor_mutex);

	srv_last_monitor_time = time(NULL);

	os_aio_refresh_stats();

	btr_cur_n_sea_old = btr_cur_n_sea;
	btr_cur_n_non_sea_old = btr_cur_n_non_sea;

	log_refresh_stats();
	
	buf_refresh_io_stats();

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

	mutex_exit(&srv_innodb_monitor_mutex);
}

unknown's avatar
unknown committed
2294 2295
/**********************************************************************
Sprintfs to a buffer the output of the InnoDB Monitor. */
2296

unknown's avatar
unknown committed
2297 2298 2299 2300 2301
void
srv_sprintf_innodb_monitor(
/*=======================*/
	char*	buf,	/* in/out: buffer which must be at least 4 kB */
	ulint	len)	/* in: length of the buffer */
2302
{
unknown's avatar
unknown committed
2303 2304 2305
	char*	buf_end	= buf + len - 2000;
	double	time_elapsed;
	time_t	current_time;
2306
	ulint	n_reserved;
unknown's avatar
Merge  
unknown committed
2307

unknown's avatar
unknown committed
2308
	mutex_enter(&srv_innodb_monitor_mutex);
2309

unknown's avatar
unknown committed
2310
	current_time = time(NULL);
2311

unknown's avatar
unknown committed
2312 2313 2314
	/* We add 0.001 seconds to time_elapsed to prevent division
	by zero if two users happen to call SHOW INNODB STATUS at the same
	time */
2315
	
unknown's avatar
unknown committed
2316 2317
	time_elapsed = difftime(current_time, srv_last_monitor_time)
			+ 0.001;
2318

unknown's avatar
unknown committed
2319
	srv_last_monitor_time = time(NULL);
2320

unknown's avatar
unknown committed
2321
	ut_a(len >= 4096);	
2322

unknown's avatar
unknown committed
2323
	buf += sprintf(buf, "\n=====================================\n");
unknown's avatar
Merge  
unknown committed
2324

unknown's avatar
unknown committed
2325 2326
	ut_sprintf_timestamp(buf);
	buf = buf + strlen(buf);
2327
	ut_a(buf < buf_end + 1500);
2328
	
unknown's avatar
unknown committed
2329
	buf += sprintf(buf, " INNODB MONITOR OUTPUT\n"
2330
	       	       "=====================================\n");
unknown's avatar
unknown committed
2331 2332

	buf += sprintf(buf,
unknown's avatar
unknown committed
2333
"Per second averages calculated from the last %lu seconds\n",
unknown's avatar
unknown committed
2334 2335 2336
					(ulint)time_elapsed);
	       	       
	buf += sprintf(buf, "----------\n"
2337 2338
		       "SEMAPHORES\n"
		       "----------\n");
unknown's avatar
unknown committed
2339 2340 2341
	sync_print(buf, buf_end);

	buf = buf + strlen(buf);
2342
	ut_a(buf < buf_end + 1500);
unknown's avatar
unknown committed
2343

unknown's avatar
unknown committed
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
	if (*dict_foreign_err_buf != '\0') {
		buf += sprintf(buf,
			"------------------------\n"
		       	"LATEST FOREIGN KEY ERROR\n"
		       	"------------------------\n");

		if (buf_end - buf > 6000) {
			buf+= sprintf(buf, "%.4000s", dict_foreign_err_buf);
		}
	}	

	ut_a(buf < buf_end + 1500);

2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
	if (*dict_unique_err_buf != '\0') {
		buf += sprintf(buf,
"---------------------------------------------------------------\n"
"LATEST UNIQUE KEY ERROR (is masked in REPLACE or INSERT IGNORE)\n"
"---------------------------------------------------------------\n");

		if (buf_end - buf > 6000) {
			buf+= sprintf(buf, "%.4000s", dict_unique_err_buf);
		}
	}	

	ut_a(buf < buf_end + 1500);

unknown's avatar
unknown committed
2370 2371
	lock_print_info(buf, buf_end);
	buf = buf + strlen(buf);
unknown's avatar
unknown committed
2372
	
unknown's avatar
unknown committed
2373
	buf += sprintf(buf, "--------\n"
2374 2375
		       "FILE I/O\n"
		       "--------\n");
unknown's avatar
unknown committed
2376 2377
	os_aio_print(buf, buf_end);
	buf = buf + strlen(buf);
2378
	ut_a(buf < buf_end + 1500);
unknown's avatar
unknown committed
2379 2380

	buf += sprintf(buf, "-------------------------------------\n"
unknown's avatar
unknown committed
2381 2382
		       "INSERT BUFFER AND ADAPTIVE HASH INDEX\n"
		       "-------------------------------------\n");
unknown's avatar
unknown committed
2383 2384
	ibuf_print(buf, buf_end);
	buf = buf + strlen(buf);
2385
	ut_a(buf < buf_end + 1500);
unknown's avatar
unknown committed
2386 2387 2388

	ha_print_info(buf, buf_end, btr_search_sys->hash_index);
	buf = buf + strlen(buf);
2389
	ut_a(buf < buf_end + 1500);
unknown's avatar
unknown committed
2390 2391 2392 2393 2394 2395 2396

	buf += sprintf(buf,
		"%.2f hash searches/s, %.2f non-hash searches/s\n",
			(btr_cur_n_sea - btr_cur_n_sea_old)
						/ time_elapsed,
			(btr_cur_n_non_sea - btr_cur_n_non_sea_old)
						/ time_elapsed);
unknown's avatar
unknown committed
2397 2398
	btr_cur_n_sea_old = btr_cur_n_sea;
	btr_cur_n_non_sea_old = btr_cur_n_non_sea;
unknown's avatar
unknown committed
2399 2400

	buf += sprintf(buf,"---\n"
2401 2402
		       "LOG\n"
		       "---\n");
unknown's avatar
unknown committed
2403 2404
	log_print(buf, buf_end);
	buf = buf + strlen(buf);
2405
	ut_a(buf < buf_end + 1500);
unknown's avatar
unknown committed
2406 2407
	
	buf += sprintf(buf, "----------------------\n"
2408 2409
		       "BUFFER POOL AND MEMORY\n"
		       "----------------------\n");
unknown's avatar
unknown committed
2410
	buf += sprintf(buf,
2411 2412 2413
	"Total memory allocated %lu; in additional pool allocated %lu\n",
				ut_total_allocated_memory,
				mem_pool_get_reserved(mem_comm_pool));
unknown's avatar
unknown committed
2414 2415
	buf_print_io(buf, buf_end);
	buf = buf + strlen(buf);
2416
	ut_a(buf < buf_end + 1500);
unknown's avatar
unknown committed
2417 2418

	buf += sprintf(buf, "--------------\n"
2419 2420
		       "ROW OPERATIONS\n"
		       "--------------\n");
unknown's avatar
unknown committed
2421
	buf += sprintf(buf,
2422
	"%ld queries inside InnoDB, %lu queries in queue\n",
unknown's avatar
unknown committed
2423
			srv_conc_n_threads, srv_conc_n_waiting_threads);
2424 2425 2426 2427 2428 2429 2430 2431

	n_reserved = fil_space_get_n_reserved_extents(0);
	if (n_reserved > 0) {
	        buf += sprintf(buf,
	"%lu tablespace extents now reserved for B-tree split operations\n",
						    n_reserved);
	}

unknown's avatar
unknown committed
2432 2433
#ifdef UNIV_LINUX
	buf += sprintf(buf,
unknown's avatar
unknown committed
2434
	"Main thread process no. %lu, id %lu, state: %s\n",
unknown's avatar
unknown committed
2435
			srv_main_thread_process_no,
unknown's avatar
unknown committed
2436
			srv_main_thread_id,
unknown's avatar
unknown committed
2437 2438 2439 2440 2441
			srv_main_thread_op_info);
#else
	buf += sprintf(buf,
	"Main thread id %lu, state: %s\n",
			srv_main_thread_id,
unknown's avatar
unknown committed
2442
			srv_main_thread_op_info);
unknown's avatar
unknown committed
2443
#endif
unknown's avatar
unknown committed
2444
	buf += sprintf(buf,
2445 2446 2447 2448 2449
	"Number of rows inserted %lu, updated %lu, deleted %lu, read %lu\n",
			srv_n_rows_inserted, 
			srv_n_rows_updated, 
			srv_n_rows_deleted, 
			srv_n_rows_read);
unknown's avatar
unknown committed
2450
	buf += sprintf(buf,
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
	"%.2f inserts/s, %.2f updates/s, %.2f deletes/s, %.2f reads/s\n",
			(srv_n_rows_inserted - srv_n_rows_inserted_old)
						/ time_elapsed,
			(srv_n_rows_updated - srv_n_rows_updated_old)
						/ time_elapsed,
			(srv_n_rows_deleted - srv_n_rows_deleted_old)
						/ time_elapsed,
			(srv_n_rows_read - srv_n_rows_read_old)
						/ time_elapsed);

unknown's avatar
unknown committed
2461 2462 2463 2464
	srv_n_rows_inserted_old = srv_n_rows_inserted;
	srv_n_rows_updated_old = srv_n_rows_updated;
	srv_n_rows_deleted_old = srv_n_rows_deleted;
	srv_n_rows_read_old = srv_n_rows_read;
2465

unknown's avatar
unknown committed
2466
	buf += sprintf(buf, "----------------------------\n"
2467 2468
		       "END OF INNODB MONITOR OUTPUT\n"
		       "============================\n");
2469 2470
	ut_a(buf < buf_end + 1900);

unknown's avatar
unknown committed
2471
	mutex_exit(&srv_innodb_monitor_mutex);
unknown's avatar
unknown committed
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
}

/*************************************************************************
A thread which wakes up threads whose lock wait may have lasted too long.
This also prints the info output by various InnoDB monitors. */

#ifndef __WIN__
void*
#else
ulint
#endif
srv_lock_timeout_and_monitor_thread(
/*================================*/
			/* out: a dummy parameter */
	void*	arg)	/* in: a dummy parameter required by
			os_thread_create */
{
	srv_slot_t*	slot;
	double		time_elapsed;
	time_t          current_time;
	time_t		last_table_monitor_time;
	time_t		last_monitor_time;
	ibool		some_waits;
	double		wait_time;
	char*		buf;
	ulint		i;

2499
#ifdef UNIV_DEBUG_THREAD_CREATION
unknown's avatar
unknown committed
2500 2501
	printf("Lock timeout thread starts, id %lu\n",
			     os_thread_pf(os_thread_get_curr_id()));
2502
#endif
unknown's avatar
unknown committed
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512
	UT_NOT_USED(arg);
	srv_last_monitor_time = time(NULL);
	last_table_monitor_time = time(NULL);
	last_monitor_time = time(NULL);
loop:
	srv_lock_timeout_and_monitor_active = TRUE;

	/* When someone is waiting for a lock, we wake up every second
	and check if a timeout has passed for a lock wait */

unknown's avatar
unknown committed
2513
	os_thread_sleep(1000000);
unknown's avatar
unknown committed
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529

	/* In case mutex_exit is not a memory barrier, it is
	theoretically possible some threads are left waiting though
	the semaphore is already released. Wake up those threads: */
	
	sync_arr_wake_threads_if_sema_free();

	current_time = time(NULL);

	time_elapsed = difftime(current_time, last_monitor_time);
	
	if (time_elapsed > 15) {
	    last_monitor_time = time(NULL);

	    if (srv_print_innodb_monitor) {

unknown's avatar
unknown committed
2530
	        buf = mem_alloc(100000);
unknown's avatar
unknown committed
2531

2532 2533 2534
	        srv_sprintf_innodb_monitor(buf, 90000);

		ut_a(strlen(buf) < 99000);
unknown's avatar
unknown committed
2535 2536 2537 2538

	    	printf("%s", buf);

	    	mem_free(buf);
2539 2540
            }

unknown's avatar
unknown committed
2541 2542 2543 2544 2545
            if (srv_print_innodb_tablespace_monitor
                && difftime(current_time, last_table_monitor_time) > 60) {

		last_table_monitor_time = time(NULL);	

2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561
		printf("================================================\n");

		ut_print_timestamp(stdout);

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

unknown's avatar
unknown committed
2562 2563 2564 2565
	    if (srv_print_innodb_table_monitor
                && difftime(current_time, last_table_monitor_time) > 60) {

		last_table_monitor_time = time(NULL);	
2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580

		printf("===========================================\n");

		ut_print_timestamp(stdout);

		printf(" INNODB TABLE MONITOR OUTPUT\n"
		       "===========================================\n");
	    	dict_print();

		printf("-----------------------------------\n"
	       		"END OF INNODB TABLE MONITOR OUTPUT\n"
	       		"==================================\n");
	    }
	}

2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600
	mutex_enter(&kernel_mutex);

	some_waits = FALSE;

	/* Check of all slots if a thread is waiting there, and if it
	has exceeded the time limit */
	
	for (i = 0; i < OS_THREAD_MAX_N; i++) {

		slot = srv_mysql_table + i;

		if (slot->in_use) {
			some_waits = TRUE;

			wait_time = ut_difftime(ut_time(), slot->suspend_time);
			
			if (srv_lock_wait_timeout < 100000000 && 
	    			(wait_time > (double) srv_lock_wait_timeout
						|| wait_time < 0)) {

unknown's avatar
Merge  
unknown committed
2601
				/* Timeout exceeded or a wrap-around in system
2602
				time counter: cancel the lock request queued
2603
				by the transaction and release possible
unknown's avatar
unknown committed
2604 2605 2606 2607 2608 2609 2610 2611
				other transactions waiting behind; it is
				possible that the lock has already been
				granted: in that case do nothing */

			        if (thr_get_trx(slot->thr)->wait_lock) {
				        lock_cancel_waiting_and_release(
				          thr_get_trx(slot->thr)->wait_lock);
			        }
2612 2613 2614 2615 2616 2617 2618 2619
			}
		}
	}

	os_event_reset(srv_lock_timeout_thread_event);

	mutex_exit(&kernel_mutex);

unknown's avatar
Merge  
unknown committed
2620 2621 2622 2623
	if (srv_shutdown_state >= SRV_SHUTDOWN_CLEANUP) {
		goto exit_func;
	}

2624 2625 2626 2627
	if (some_waits || srv_print_innodb_monitor
			|| srv_print_innodb_lock_monitor
			|| srv_print_innodb_tablespace_monitor
			|| srv_print_innodb_table_monitor) {
2628 2629 2630
		goto loop;
	}

2631 2632
	/* No one was waiting for a lock and no monitor was active:
	suspend this thread */
unknown's avatar
Merge  
unknown committed
2633 2634 2635

	srv_lock_timeout_and_monitor_active = FALSE;

2636 2637 2638 2639
	os_event_wait(srv_lock_timeout_thread_event);

	goto loop;

unknown's avatar
Merge  
unknown committed
2640 2641 2642
exit_func:
	srv_lock_timeout_and_monitor_active = FALSE;

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

	os_thread_exit(NULL);
2647 2648 2649
#ifndef __WIN__
        return(NULL);
#else
2650
	return(0);
2651
#endif
2652 2653
}

2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
/*************************************************************************
A thread which prints warnings about semaphore waits which have lasted
too long. These can be used to track bugs which cause hangs. */

#ifndef __WIN__
void*
#else
ulint
#endif
srv_error_monitor_thread(
/*=====================*/
			/* out: a dummy parameter */
	void*	arg)	/* in: a dummy parameter required by
			os_thread_create */
{
unknown's avatar
unknown committed
2669 2670
	ulint	cnt	= 0;

2671
	UT_NOT_USED(arg);
2672
#ifdef UNIV_DEBUG_THREAD_CREATION
unknown's avatar
unknown committed
2673 2674
	printf("Error monitor thread starts, id %lu\n",
			      os_thread_pf(os_thread_get_curr_id()));
2675
#endif
2676
loop:
unknown's avatar
Merge  
unknown committed
2677 2678
	srv_error_monitor_active = TRUE;

unknown's avatar
unknown committed
2679 2680 2681 2682
	cnt++;

	os_thread_sleep(2000000);

unknown's avatar
unknown committed
2683 2684 2685
	if (difftime(time(NULL), srv_last_monitor_time) > 60) {
		/* We referesh InnoDB Monitor values so that averages are
		printed from at most 60 last seconds */
2686

unknown's avatar
unknown committed
2687 2688 2689
		srv_refresh_innodb_monitor_stats();
	}

unknown's avatar
unknown committed
2690
/*	mem_print_new_info();
unknown's avatar
unknown committed
2691

unknown's avatar
unknown committed
2692 2693 2694 2695 2696
	if (cnt % 10 == 0) {

		mem_print_info();
	}
*/
2697
	sync_array_print_long_waits();
unknown's avatar
unknown committed
2698 2699 2700 2701 2702 2703 2704

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

	fflush(stderr);
	fflush(stdout);

unknown's avatar
Merge  
unknown committed
2705 2706 2707 2708 2709 2710
	if (srv_shutdown_state < SRV_SHUTDOWN_LAST_PHASE) {

		goto loop;
	}

	srv_error_monitor_active = FALSE;
2711

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

unknown's avatar
unknown committed
2715 2716
	os_thread_exit(NULL);

2717 2718 2719 2720 2721 2722 2723
#ifndef __WIN__
        return(NULL);
#else
	return(0);
#endif
}

2724
/***********************************************************************
2725
Tells the InnoDB server that there has been activity in the database
2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
and wakes up the master thread if it is suspended (not sleeping). Used
in the MySQL interface. Note that there is a small chance that the master
thread stays suspended (we do not protect our operation with the kernel
mutex, for performace reasons). */

void
srv_active_wake_master_thread(void)
/*===============================*/
{
	srv_activity_count++;
			
	if (srv_n_threads_active[SRV_MASTER] == 0) {

		mutex_enter(&kernel_mutex);

		srv_release_threads(SRV_MASTER, 1);

		mutex_exit(&kernel_mutex);
	}
}

unknown's avatar
unknown committed
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
/***********************************************************************
Wakes up the master thread if it is suspended or being suspended. */

void
srv_wake_master_thread(void)
/*========================*/
{
	srv_activity_count++;
			
	mutex_enter(&kernel_mutex);

	srv_release_threads(SRV_MASTER, 1);

	mutex_exit(&kernel_mutex);
}

2763 2764 2765
/*************************************************************************
The master thread controlling the server. */

2766 2767 2768
#ifndef __WIN__
void*
#else
2769
ulint
2770
#endif
2771 2772 2773 2774 2775 2776 2777
srv_master_thread(
/*==============*/
			/* out: a dummy parameter */
	void*	arg)	/* in: a dummy parameter required by
			os_thread_create */
{
	os_event_t	event;
2778 2779
	time_t          last_flush_time;
	time_t          current_time;
2780 2781 2782 2783 2784
	ulint		old_activity_count;
	ulint		n_pages_purged;
	ulint		n_bytes_merged;
	ulint		n_pages_flushed;
	ulint		n_bytes_archived;
unknown's avatar
unknown committed
2785
	ulint		n_tables_to_drop;
2786 2787 2788 2789
	ulint		n_ios;
	ulint		n_ios_old;
	ulint		n_ios_very_old;
	ulint		n_pend_ios;
unknown's avatar
unknown committed
2790
	ibool		skip_sleep	= FALSE;
2791 2792 2793 2794
	ulint		i;
	
	UT_NOT_USED(arg);

2795
#ifdef UNIV_DEBUG_THREAD_CREATION
unknown's avatar
unknown committed
2796 2797
	printf("Master thread starts, id %lu\n",
			      os_thread_pf(os_thread_get_curr_id()));
2798
#endif
unknown's avatar
unknown committed
2799 2800 2801
	srv_main_thread_process_no = os_proc_get_number();
	srv_main_thread_id = os_thread_pf(os_thread_get_curr_id());
	
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
	srv_table_reserve_slot(SRV_MASTER);	

	mutex_enter(&kernel_mutex);

	srv_n_threads_active[SRV_MASTER]++;

	mutex_exit(&kernel_mutex);

	os_event_set(srv_sys->operational);
loop:
2812 2813 2814 2815
	/*****************************************************************/
	/* ---- When there is database activity by users, we cycle in this
	loop */

unknown's avatar
unknown committed
2816
	srv_main_thread_op_info = (char*) "reserving kernel mutex";
2817 2818 2819

	n_ios_very_old = log_sys->n_log_ios + buf_pool->n_pages_read
						+ buf_pool->n_pages_written;
2820 2821
	mutex_enter(&kernel_mutex);

2822
	/* Store the user activity counter at the start of this loop */
2823 2824 2825 2826
	old_activity_count = srv_activity_count;

	mutex_exit(&kernel_mutex);

2827 2828 2829 2830 2831 2832 2833 2834
	if (srv_force_recovery >= SRV_FORCE_NO_BACKGROUND) {

		goto suspend_thread;
	}

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

unknown's avatar
unknown committed
2835 2836
	skip_sleep = FALSE;

2837
	for (i = 0; i < 10; i++) {
2838 2839
		n_ios_old = log_sys->n_log_ios + buf_pool->n_pages_read
						+ buf_pool->n_pages_written;
unknown's avatar
unknown committed
2840
		srv_main_thread_op_info = (char*)"sleeping";
unknown's avatar
unknown committed
2841 2842 2843 2844 2845 2846 2847
		
		if (!skip_sleep) {

		        os_thread_sleep(1000000);
		}

		skip_sleep = FALSE;
2848

unknown's avatar
unknown committed
2849 2850 2851 2852
		/* ALTER TABLE in MySQL requires on Unix that the table handler
		can drop tables lazily after there no longer are SELECT
		queries to them. */

unknown's avatar
unknown committed
2853 2854
		srv_main_thread_op_info =
					(char*)"doing background drop tables";
unknown's avatar
unknown committed
2855 2856 2857

		row_drop_tables_for_mysql_in_background();

unknown's avatar
unknown committed
2858
		srv_main_thread_op_info = (char*)"";
unknown's avatar
unknown committed
2859

unknown's avatar
unknown committed
2860 2861 2862 2863 2864
		if (srv_fast_shutdown && srv_shutdown_state > 0) {

			goto background_loop;
		}

unknown's avatar
unknown committed
2865 2866 2867 2868
		/* We flush the log once in a second even if no commit
		is issued or the we have specified in my.cnf no flush
		at transaction commit */

unknown's avatar
unknown committed
2869
		srv_main_thread_op_info = (char*)"flushing log";
unknown's avatar
unknown committed
2870
		log_buffer_flush_to_disk();
unknown's avatar
unknown committed
2871

2872
		/* If there were less than 5 i/os during the
2873 2874 2875 2876 2877 2878 2879 2880
		one second sleep, we assume that there is free
		disk i/o capacity available, and it makes sense to
		do an insert buffer merge. */

		n_pend_ios = buf_get_n_pending_ios()
						+ log_sys->n_pending_writes;
		n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
						+ buf_pool->n_pages_written;
2881
		if (n_pend_ios < 3 && (n_ios - n_ios_old < 5)) {
unknown's avatar
unknown committed
2882
			srv_main_thread_op_info =
unknown's avatar
unknown committed
2883
					(char*)"doing insert buffer merge";
2884 2885
			ibuf_contract_for_n_pages(TRUE, 5);

unknown's avatar
unknown committed
2886 2887 2888
			srv_main_thread_op_info = (char*)"flushing log";

			log_buffer_flush_to_disk();
2889
		}
unknown's avatar
Merge  
unknown committed
2890

2891 2892 2893 2894 2895 2896 2897 2898
		if (buf_get_modified_ratio_pct() >
				             srv_max_buf_pool_modified_pct) {

			/* Try to keep the number of modified pages in the
			buffer pool under the limit wished by the user */
			
			n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100,
							  ut_dulint_max);
unknown's avatar
unknown committed
2899 2900 2901 2902 2903 2904 2905

		        /* If we had to do the flush, it may have taken
			even more than 1 second, and also, there may be more
			to flush. Do not sleep 1 second during the next
			iteration of this loop. */
			     
			skip_sleep = TRUE;
2906 2907
		}

2908 2909
		if (srv_activity_count == old_activity_count) {

2910 2911
			/* There is no user activity at the moment, go to
			the background loop */
2912 2913 2914 2915 2916

			goto background_loop;
		}
	}

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

unknown's avatar
unknown committed
2920 2921 2922 2923 2924
#ifdef MEM_PERIODIC_CHECK
	/* Check magic numbers of every allocated mem block once in 10
	seconds */
	mem_validate_all_blocks();
#endif	
2925 2926
	/* If there were less than 200 i/os during the 10 second period,
	we assume that there is free disk i/o capacity available, and it
2927
	makes sense to flush 100 pages. */
2928 2929 2930 2931 2932 2933

	n_pend_ios = buf_get_n_pending_ios() + log_sys->n_pending_writes;
	n_ios = log_sys->n_log_ios + buf_pool->n_pages_read
						+ buf_pool->n_pages_written;
	if (n_pend_ios < 3 && (n_ios - n_ios_very_old < 200)) {

unknown's avatar
unknown committed
2934
		srv_main_thread_op_info = (char*) "flushing buffer pool pages";
unknown's avatar
unknown committed
2935
		buf_flush_batch(BUF_FLUSH_LIST, 100, ut_dulint_max);
2936

unknown's avatar
unknown committed
2937
		srv_main_thread_op_info = (char*) "flushing log";
unknown's avatar
unknown committed
2938
		log_buffer_flush_to_disk();
2939 2940 2941 2942 2943
	}

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

unknown's avatar
unknown committed
2944
	srv_main_thread_op_info = (char*)"doing insert buffer merge";
2945 2946
	ibuf_contract_for_n_pages(TRUE, 5);

unknown's avatar
unknown committed
2947
	srv_main_thread_op_info = (char*)"flushing log";
unknown's avatar
unknown committed
2948
	log_buffer_flush_to_disk();
2949 2950 2951 2952

	/* We run a full purge every 10 seconds, even if the server
	were active */
	
2953 2954
	n_pages_purged = 1;

unknown's avatar
unknown committed
2955 2956
	last_flush_time = time(NULL);

2957
	while (n_pages_purged) {
unknown's avatar
unknown committed
2958

unknown's avatar
Merge  
unknown committed
2959 2960 2961 2962 2963
		if (srv_fast_shutdown && srv_shutdown_state > 0) {

			goto background_loop;
		}

unknown's avatar
unknown committed
2964
		srv_main_thread_op_info = (char*)"purging";
2965
		n_pages_purged = trx_purge();
2966

unknown's avatar
unknown committed
2967 2968 2969
		current_time = time(NULL);

		if (difftime(current_time, last_flush_time) > 1) {
unknown's avatar
unknown committed
2970
			srv_main_thread_op_info = (char*) "flushing log";
2971

unknown's avatar
unknown committed
2972
		        log_buffer_flush_to_disk();
unknown's avatar
unknown committed
2973 2974
			last_flush_time = current_time;
		}
2975
	}
unknown's avatar
unknown committed
2976
	
unknown's avatar
unknown committed
2977
	srv_main_thread_op_info = (char*)"flushing buffer pool pages";
unknown's avatar
unknown committed
2978

2979 2980 2981 2982 2983 2984 2985
	/* Flush a few oldest pages to make a new checkpoint younger */

	if (buf_get_modified_ratio_pct() > 70) {

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

unknown's avatar
unknown committed
2987 2988 2989
	        n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100,
							ut_dulint_max);
	} else {
2990 2991 2992 2993
	        /* Otherwise, we only flush a small number of pages so that
		we do not unnecessarily use much disk i/o capacity from
		other work */

unknown's avatar
unknown committed
2994 2995 2996
	        n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 10,
							ut_dulint_max);
	}
unknown's avatar
unknown committed
2997

unknown's avatar
unknown committed
2998
	srv_main_thread_op_info = (char*)"making checkpoint";
unknown's avatar
unknown committed
2999 3000 3001 3002

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

	log_checkpoint(TRUE, FALSE);
3003

unknown's avatar
unknown committed
3004
	srv_main_thread_op_info = (char*)"reserving kernel mutex";
3005

3006
	mutex_enter(&kernel_mutex);
3007 3008 3009 3010
	
	/* ---- When there is database activity, we jump from here back to
	the start of loop */

3011 3012 3013 3014
	if (srv_activity_count != old_activity_count) {
		mutex_exit(&kernel_mutex);
		goto loop;
	}
3015
	
3016 3017
	mutex_exit(&kernel_mutex);

3018 3019 3020 3021 3022 3023 3024
	/* If the database is quiet, we enter the background loop */

	/*****************************************************************/
background_loop:
	/* ---- In this loop we run background operations when the server
	is quiet from user activity */

3025 3026 3027
	/* The server has been quiet for a while: start running background
	operations */
		
3028 3029 3030 3031
	srv_main_thread_op_info = (char*)"doing background drop tables";

	n_tables_to_drop = row_drop_tables_for_mysql_in_background();

3032 3033 3034 3035 3036 3037 3038 3039 3040
	if (n_tables_to_drop > 0) {
	        /* Do not monopolize the CPU even if there are tables waiting
		in the background drop queue. (It is essentially a bug if
		MySQL tries to drop a table while there are still open handles
		to it and we had to put it to the background drop queue.) */

		os_thread_sleep(100000);
	}
 
unknown's avatar
unknown committed
3041
	srv_main_thread_op_info = (char*)"purging";
3042

unknown's avatar
unknown committed
3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
	/* Run a full purge */
	
	n_pages_purged = 1;

	last_flush_time = time(NULL);

	while (n_pages_purged) {
		if (srv_fast_shutdown && srv_shutdown_state > 0) {

			break;
		}

		srv_main_thread_op_info = (char*)"purging";
		n_pages_purged = trx_purge();

		current_time = time(NULL);

		if (difftime(current_time, last_flush_time) > 1) {
			srv_main_thread_op_info = (char*) "flushing log";

		        log_buffer_flush_to_disk();
			last_flush_time = current_time;
		}
unknown's avatar
unknown committed
3066
	}
3067

unknown's avatar
unknown committed
3068
	srv_main_thread_op_info = (char*)"reserving kernel mutex";
3069

3070 3071 3072 3073 3074 3075 3076
	mutex_enter(&kernel_mutex);
	if (srv_activity_count != old_activity_count) {
		mutex_exit(&kernel_mutex);
		goto loop;
	}
	mutex_exit(&kernel_mutex);

unknown's avatar
unknown committed
3077
	srv_main_thread_op_info = (char*)"doing insert buffer merge";
unknown's avatar
unknown committed
3078 3079 3080 3081 3082 3083

	if (srv_fast_shutdown && srv_shutdown_state > 0) {
	        n_bytes_merged = 0;
	} else {
	        n_bytes_merged = ibuf_contract_for_n_pages(TRUE, 20);
	}
3084

unknown's avatar
unknown committed
3085
	srv_main_thread_op_info = (char*)"reserving kernel mutex";
3086

3087 3088 3089 3090 3091 3092 3093
	mutex_enter(&kernel_mutex);
	if (srv_activity_count != old_activity_count) {
		mutex_exit(&kernel_mutex);
		goto loop;
	}
	mutex_exit(&kernel_mutex);
	
3094
flush_loop:
unknown's avatar
unknown committed
3095
	srv_main_thread_op_info = (char*)"flushing buffer pool pages";
3096
	n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100, ut_dulint_max);
3097

unknown's avatar
unknown committed
3098
	srv_main_thread_op_info = (char*)"reserving kernel mutex";
3099

3100 3101 3102 3103 3104 3105 3106
	mutex_enter(&kernel_mutex);
	if (srv_activity_count != old_activity_count) {
		mutex_exit(&kernel_mutex);
		goto loop;
	}
	mutex_exit(&kernel_mutex);
	
unknown's avatar
unknown committed
3107 3108
	srv_main_thread_op_info =
			(char*) "waiting for buffer pool flush to end";
3109 3110
	buf_flush_wait_batch_end(BUF_FLUSH_LIST);

unknown's avatar
unknown committed
3111 3112 3113 3114
	srv_main_thread_op_info = (char*) "flushing log";

	log_buffer_flush_to_disk();

unknown's avatar
unknown committed
3115
	srv_main_thread_op_info = (char*)"making checkpoint";
3116

3117 3118
	log_checkpoint(TRUE, FALSE);

3119 3120 3121 3122 3123 3124 3125 3126
	if (buf_get_modified_ratio_pct() > srv_max_buf_pool_modified_pct) {

		/* Try to keep the number of modified pages in the
		buffer pool under the limit wished by the user */
			
		goto flush_loop;
	}

unknown's avatar
unknown committed
3127
	srv_main_thread_op_info = (char*)"reserving kernel mutex";
3128

3129 3130 3131 3132 3133 3134
	mutex_enter(&kernel_mutex);
	if (srv_activity_count != old_activity_count) {
		mutex_exit(&kernel_mutex);
		goto loop;
	}
	mutex_exit(&kernel_mutex);
3135

unknown's avatar
unknown committed
3136
	srv_main_thread_op_info =
unknown's avatar
unknown committed
3137
				(char*)"archiving log (if log archive is on)";
3138 3139 3140
	
	log_archive_do(FALSE, &n_bytes_archived);

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

unknown's avatar
Merge  
unknown committed
3143
	if (srv_fast_shutdown && srv_shutdown_state > 0) {
unknown's avatar
unknown committed
3144 3145
		if (n_tables_to_drop + n_pages_flushed
				+ n_bytes_archived != 0) {
unknown's avatar
Merge  
unknown committed
3146

3147 3148 3149 3150
			/* If we are doing a fast shutdown (= the default)
			we do not do purge or insert buffer merge. But we
			flush the buffer pool completely to disk. */

unknown's avatar
Merge  
unknown committed
3151 3152
			goto background_loop;
		}
unknown's avatar
unknown committed
3153
	} else if (n_tables_to_drop +
3154
		   n_pages_purged + n_bytes_merged + n_pages_flushed
3155
						+ n_bytes_archived != 0) {
3156 3157 3158
		/* In a 'slow' shutdown we run purge and the insert buffer
		merge to completion */

3159 3160 3161 3162
		goto background_loop;
	}
		
/*	mem_print_new_info();
3163
 */
3164

3165 3166 3167 3168 3169 3170
#ifdef UNIV_SEARCH_PERF_STAT
/*	btr_search_print_info(); */
#endif
	/* There is no work for background operations either: suspend
	master thread to wait for more server activity */
	
unknown's avatar
Merge  
unknown committed
3171
suspend_thread:
unknown's avatar
unknown committed
3172
	srv_main_thread_op_info = (char*)"suspending";
3173

3174 3175
	mutex_enter(&kernel_mutex);

unknown's avatar
unknown committed
3176 3177 3178 3179 3180 3181
	if (row_get_background_drop_list_len_low() > 0) {
		mutex_exit(&kernel_mutex);

		goto loop;
	}

3182 3183 3184 3185
	event = srv_suspend_thread();

	mutex_exit(&kernel_mutex);

unknown's avatar
unknown committed
3186
	srv_main_thread_op_info = (char*)"waiting for server activity";
3187

3188 3189
	os_event_wait(event);

unknown's avatar
unknown committed
3190 3191 3192 3193 3194 3195 3196
	if (srv_shutdown_state == SRV_SHUTDOWN_EXIT_THREADS) {
	        /* This is only extra safety, the thread should exit
		already when the event wait ends */

	        os_thread_exit(NULL);
	}

3197 3198 3199
	/* When there is user activity, InnoDB will set the event and the main
	thread goes back to loop: */

3200 3201
	goto loop;

3202 3203 3204 3205 3206 3207 3208
	/* We count the number of threads in os_thread_exit(). A created
	thread should always use that to exit and not use return() to exit.
	The thread actually never comes here because it is exited in an
	os_event_wait(). */
	
	os_thread_exit(NULL);

3209 3210 3211
#ifndef __WIN__
        return(NULL);
#else
3212
	return(0);
3213
#endif
3214
}