sync0sync.c 37.7 KB
Newer Older
osku's avatar
osku committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/******************************************************
Mutex, the basic synchronization primitive

(c) 1995 Innobase Oy

Created 9/5/1995 Heikki Tuuri
*******************************************************/

#include "sync0sync.h"
#ifdef UNIV_NONINL
#include "sync0sync.ic"
#endif

#include "sync0rw.h"
#include "buf0buf.h"
#include "srv0srv.h"
#include "buf0types.h"

/*
	REASONS FOR IMPLEMENTING THE SPIN LOCK MUTEX
	============================================

Semaphore operations in operating systems are slow: Solaris on a 1993 Sparc
takes 3 microseconds (us) for a lock-unlock pair and Windows NT on a 1995
Pentium takes 20 microseconds for a lock-unlock pair. Therefore, we have to
implement our own efficient spin lock mutex. Future operating systems may
provide efficient spin locks, but we cannot count on that.

Another reason for implementing a spin lock is that on multiprocessor systems
30
it can be more efficient for a processor to run a loop waiting for the
osku's avatar
osku committed
31 32 33 34 35 36 37
semaphore to be released than to switch to a different thread. A thread switch
takes 25 us on both platforms mentioned above. See Gray and Reuter's book
Transaction processing for background.

How long should the spin loop last before suspending the thread? On a
uniprocessor, spinning does not help at all, because if the thread owning the
mutex is not executing, it cannot be released. Spinning actually wastes
38
resources.
osku's avatar
osku committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

On a multiprocessor, we do not know if the thread owning the mutex is
executing or not. Thus it would make sense to spin as long as the operation
guarded by the mutex would typically last assuming that the thread is
executing. If the mutex is not released by that time, we may assume that the
thread owning the mutex is not executing and suspend the waiting thread.

A typical operation (where no i/o involved) guarded by a mutex or a read-write
lock may last 1 - 20 us on the current Pentium platform. The longest
operations are the binary searches on an index node.

We conclude that the best choice is to set the spin time at 20 us. Then the
system should work well on a multiprocessor. On a uniprocessor we have to
make sure that thread swithches due to mutex collisions are not frequent,
i.e., they do not happen every 100 us or so, because that wastes too much
resources. If the thread switches are not frequent, the 20 us wasted in spin
55
loop is not too much.
osku's avatar
osku committed
56 57 58 59

Empirical studies on the effect of spin time should be done for different
platforms.

60

osku's avatar
osku committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	IMPLEMENTATION OF THE MUTEX
	===========================

For background, see Curt Schimmel's book on Unix implementation on modern
architectures. The key points in the implementation are atomicity and
serialization of memory accesses. The test-and-set instruction (XCHG in
Pentium) must be atomic. As new processors may have weak memory models, also
serialization of memory references may be necessary. The successor of Pentium,
P6, has at least one mode where the memory model is weak. As far as we know,
in Pentium all memory accesses are serialized in the program order and we do
not have to worry about the memory model. On other processors there are
special machine instructions called a fence, memory barrier, or storage
barrier (STBAR in Sparc), which can be used to serialize the memory accesses
to happen in program order relative to the fence instruction.

Leslie Lamport has devised a "bakery algorithm" to implement a mutex without
the atomic test-and-set, but his algorithm should be modified for weak memory
models. We do not use Lamport's algorithm, because we guess it is slower than
the atomic test-and-set.

Our mutex implementation works as follows: After that we perform the atomic
test-and-set instruction on the memory word. If the test returns zero, we
know we got the lock first. If the test returns not zero, some other thread
was quicker and got the lock: then we spin in a loop reading the memory word,
waiting it to become zero. It is wise to just read the word in the loop, not
perform numerous test-and-set instructions, because they generate memory
traffic between the cache and the main memory. The read loop can just access
the cache, saving bus bandwidth.

If we cannot acquire the mutex lock in the specified time, we reserve a cell
in the wait array, set the waiters byte in the mutex to 1. To avoid a race
condition, after setting the waiters byte and before suspending the waiting
thread, we still have to check that the mutex is reserved, because it may
have happened that the thread which was holding the mutex has just released
it and did not see the waiters byte set to 1, a case which would lead the
other thread to an infinite wait.

98 99 100 101
LEMMA 1: After a thread resets the event of a mutex (or rw_lock), some
=======
thread will eventually call os_event_set() on that particular event.
Thus no infinite wait is possible in this case.
osku's avatar
osku committed
102 103 104 105 106 107

Proof:	After making the reservation the thread sets the waiters field in the
mutex to 1. Then it checks that the mutex is still reserved by some thread,
or it reserves the mutex for itself. In any case, some thread (which may be
also some earlier thread, not necessarily the one currently holding the mutex)
will set the waiters field to 0 in mutex_exit, and then call
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
os_event_set() with the mutex as an argument.
Q.E.D.

LEMMA 2: If an os_event_set() call is made after some thread has called
=======
the os_event_reset() and before it starts wait on that event, the call
will not be lost to the second thread. This is true even if there is an
intervening call to os_event_reset() by another thread.
Thus no infinite wait is possible in this case.

Proof (non-windows platforms): os_event_reset() returns a monotonically
increasing value of signal_count. This value is increased at every
call of os_event_set() If thread A has called os_event_reset() followed
by thread B calling os_event_set() and then some other thread C calling
os_event_reset(), the is_set flag of the event will be set to FALSE;
but now if thread A calls os_event_wait_low() with the signal_count
value returned from the earlier call of os_event_reset(), it will
return immediately without waiting.
Q.E.D.

Proof (windows): If there is a writer thread which is forced to wait for
the lock, it may be able to set the state of rw_lock to RW_LOCK_WAIT_EX
The design of rw_lock ensures that there is one and only one thread
that is able to change the state to RW_LOCK_WAIT_EX and this thread is
guaranteed to acquire the lock after it is released by the current
holders and before any other waiter gets the lock.
On windows this thread waits on a separate event i.e.: wait_ex_event.
Since only one thread can wait on this event there is no chance
of this event getting reset before the writer starts wait on it.
Therefore, this thread is guaranteed to catch the os_set_event()
signalled unconditionally at the release of the lock.
osku's avatar
osku committed
139 140 141 142 143
Q.E.D. */

/* The number of system calls made in this module. Intended for performance
monitoring. */

144
UNIV_INTERN ulint	mutex_system_call_count		= 0;
osku's avatar
osku committed
145 146 147

/* Number of spin waits on mutexes: for performance monitoring */

148
/* round=one iteration of a spin loop */
149 150 151 152
UNIV_INTERN ulint	mutex_spin_round_count		= 0;
UNIV_INTERN ulint	mutex_spin_wait_count		= 0;
UNIV_INTERN ulint	mutex_os_wait_count		= 0;
UNIV_INTERN ulint	mutex_exit_count		= 0;
osku's avatar
osku committed
153 154 155

/* The global array of wait cells for implementation of the database's own
mutexes and read-write locks */
156
UNIV_INTERN sync_array_t*	sync_primary_wait_array;
osku's avatar
osku committed
157 158

/* This variable is set to TRUE when sync_init is called */
159
UNIV_INTERN ibool	sync_initialized	= FALSE;
osku's avatar
osku committed
160 161 162 163 164


typedef struct sync_level_struct	sync_level_t;
typedef struct sync_thread_struct	sync_thread_t;

165
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
166 167 168
/* The latch levels currently owned by threads are stored in this data
structure; the size of this array is OS_THREAD_MAX_N */

169
UNIV_INTERN sync_thread_t*	sync_thread_level_arrays;
osku's avatar
osku committed
170 171

/* Mutex protecting sync_thread_level_arrays */
172
UNIV_INTERN mutex_t		sync_thread_mutex;
173
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
174 175

/* Global list of database mutexes (not OS mutexes) created. */
176
UNIV_INTERN ut_list_base_node_t  mutex_list;
osku's avatar
osku committed
177 178

/* Mutex protecting the mutex_list variable */
179
UNIV_INTERN mutex_t mutex_list_mutex;
osku's avatar
osku committed
180

181
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
182
/* Latching order checks start when this is set TRUE */
183
UNIV_INTERN ibool	sync_order_checks_on	= FALSE;
184
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

struct sync_thread_struct{
	os_thread_id_t	id;	/* OS thread id */
	sync_level_t*	levels;	/* level array for this thread; if this is NULL
				this slot is unused */
};

/* Number of slots reserved for each OS thread in the sync level array */
#define SYNC_THREAD_N_LEVELS	10000

struct sync_level_struct{
	void*	latch;	/* pointer to a mutex or an rw-lock; NULL means that
			the slot is empty */
	ulint	level;	/* level of the latch in the latching order */
};

/**********************************************************************
Creates, or rather, initializes a mutex object in a specified memory
location (which must be appropriately aligned). The mutex is initialized
in the reset state. Explicit freeing of the mutex with mutex_free is
necessary only if the memory block containing it is freed. */
206
UNIV_INTERN
osku's avatar
osku committed
207 208 209 210
void
mutex_create_func(
/*==============*/
	mutex_t*	mutex,		/* in: pointer to memory */
211 212 213
#ifdef UNIV_DEBUG
	const char*	cmutex_name,	/* in: mutex name */
# ifdef UNIV_SYNC_DEBUG
214
	ulint		level,		/* in: level */
215 216
# endif /* UNIV_SYNC_DEBUG */
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
217
	const char*	cfile_name,	/* in: file name where created */
218
	ulint		cline)		/* in: file line where created */
osku's avatar
osku committed
219 220 221
{
#if defined(_WIN32) && defined(UNIV_CAN_USE_X86_ASSEMBLER)
	mutex_reset_lock_word(mutex);
222
#else
osku's avatar
osku committed
223 224 225
	os_fast_mutex_init(&(mutex->os_fast_mutex));
	mutex->lock_word = 0;
#endif
226
	mutex->event = os_event_create(NULL);
osku's avatar
osku committed
227
	mutex_set_waiters(mutex, 0);
228
#ifdef UNIV_DEBUG
osku's avatar
osku committed
229
	mutex->magic_n = MUTEX_MAGIC_N;
230
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
231 232 233
#ifdef UNIV_SYNC_DEBUG
	mutex->line = 0;
	mutex->file_name = "not yet reserved";
234
	mutex->level = level;
235
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
236 237 238
	mutex->cfile_name = cfile_name;
	mutex->cline = cline;
#ifndef UNIV_HOTBACKUP
239 240
	mutex->count_os_wait = 0;
# ifdef UNIV_DEBUG
241 242 243 244 245 246 247 248
	mutex->cmutex_name=	  cmutex_name;
	mutex->count_using=	  0;
	mutex->mutex_type=	  0;
	mutex->lspent_time=	  0;
	mutex->lmax_spent_time=     0;
	mutex->count_spin_loop= 0;
	mutex->count_spin_rounds=   0;
	mutex->count_os_yield=  0;
249
# endif /* UNIV_DEBUG */
osku's avatar
osku committed
250
#endif /* !UNIV_HOTBACKUP */
251

osku's avatar
osku committed
252 253 254 255 256
	/* Check that lock_word is aligned; this is important on Intel */
	ut_ad(((ulint)(&(mutex->lock_word))) % 4 == 0);

	/* NOTE! The very first mutexes are not put to the mutex list */

257 258 259 260 261
	if ((mutex == &mutex_list_mutex)
#ifdef UNIV_SYNC_DEBUG
	    || (mutex == &sync_thread_mutex)
#endif /* UNIV_SYNC_DEBUG */
	    ) {
osku's avatar
osku committed
262

263
		return;
osku's avatar
osku committed
264
	}
265

osku's avatar
osku committed
266 267
	mutex_enter(&mutex_list_mutex);

268 269
	ut_ad(UT_LIST_GET_LEN(mutex_list) == 0
	      || UT_LIST_GET_FIRST(mutex_list)->magic_n == MUTEX_MAGIC_N);
osku's avatar
osku committed
270 271 272 273 274 275 276 277 278 279

	UT_LIST_ADD_FIRST(list, mutex_list, mutex);

	mutex_exit(&mutex_list_mutex);
}

/**********************************************************************
Calling this function is obligatory only if the memory buffer containing
the mutex is freed. Removes a mutex object from the mutex list. The mutex
is checked to be in the reset state. */
280
UNIV_INTERN
osku's avatar
osku committed
281 282 283 284 285
void
mutex_free(
/*=======*/
	mutex_t*	mutex)	/* in: mutex */
{
286
	ut_ad(mutex_validate(mutex));
osku's avatar
osku committed
287 288
	ut_a(mutex_get_lock_word(mutex) == 0);
	ut_a(mutex_get_waiters(mutex) == 0);
289

290 291 292 293 294
	if (mutex != &mutex_list_mutex
#ifdef UNIV_SYNC_DEBUG
	    && mutex != &sync_thread_mutex
#endif /* UNIV_SYNC_DEBUG */
	    ) {
osku's avatar
osku committed
295

296
		mutex_enter(&mutex_list_mutex);
osku's avatar
osku committed
297

298 299 300 301 302 303
		ut_ad(!UT_LIST_GET_PREV(list, mutex)
		      || UT_LIST_GET_PREV(list, mutex)->magic_n
		      == MUTEX_MAGIC_N);
		ut_ad(!UT_LIST_GET_NEXT(list, mutex)
		      || UT_LIST_GET_NEXT(list, mutex)->magic_n
		      == MUTEX_MAGIC_N);
304 305

		UT_LIST_REMOVE(list, mutex_list, mutex);
osku's avatar
osku committed
306 307 308 309

		mutex_exit(&mutex_list_mutex);
	}

310 311
	os_event_free(mutex->event);

312
#if !defined(_WIN32) || !defined(UNIV_CAN_USE_X86_ASSEMBLER)
osku's avatar
osku committed
313 314 315 316 317
	os_fast_mutex_free(&(mutex->os_fast_mutex));
#endif
	/* If we free the mutex protecting the mutex list (freeing is
	not necessary), we have to reset the magic number AFTER removing
	it from the list. */
318
#ifdef UNIV_DEBUG
osku's avatar
osku committed
319
	mutex->magic_n = 0;
320
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
321 322 323
}

/************************************************************************
324 325 326
NOTE! Use the corresponding macro in the header file, not this function
directly. Tries to lock the mutex for the current thread. If the lock is not
acquired immediately, returns with return value 1. */
327
UNIV_INTERN
osku's avatar
osku committed
328
ulint
329 330
mutex_enter_nowait_func(
/*====================*/
osku's avatar
osku committed
331 332 333 334 335 336 337 338 339 340 341 342
					/* out: 0 if succeed, 1 if not */
	mutex_t*	mutex,		/* in: pointer to mutex */
	const char*	file_name __attribute__((unused)),
					/* in: file name where mutex
					requested */
	ulint		line __attribute__((unused)))
					/* in: line where requested */
{
	ut_ad(mutex_validate(mutex));

	if (!mutex_test_and_set(mutex)) {

343
		ut_d(mutex->thread_id = os_thread_get_curr_id());
osku's avatar
osku committed
344 345 346 347 348 349 350 351 352 353
#ifdef UNIV_SYNC_DEBUG
		mutex_set_debug_info(mutex, file_name, line);
#endif

		return(0);	/* Succeeded! */
	}

	return(1);
}

354
#ifdef UNIV_DEBUG
osku's avatar
osku committed
355 356
/**********************************************************************
Checks that the mutex has been initialized. */
357
UNIV_INTERN
osku's avatar
osku committed
358 359 360
ibool
mutex_validate(
/*===========*/
361
	const mutex_t*	mutex)
osku's avatar
osku committed
362 363 364 365 366 367
{
	ut_a(mutex);
	ut_a(mutex->magic_n == MUTEX_MAGIC_N);

	return(TRUE);
}
368 369 370 371

/**********************************************************************
Checks that the current thread owns the mutex. Works only in the debug
version. */
372
UNIV_INTERN
373 374 375 376 377 378 379 380 381 382 383
ibool
mutex_own(
/*======*/
				/* out: TRUE if owns */
	const mutex_t*	mutex)	/* in: mutex */
{
	ut_ad(mutex_validate(mutex));

	return(mutex_get_lock_word(mutex) == 1
	       && os_thread_eq(mutex->thread_id, os_thread_get_curr_id()));
}
384
#endif /* UNIV_DEBUG */
osku's avatar
osku committed
385 386 387

/**********************************************************************
Sets the waiters field in a mutex. */
388
UNIV_INTERN
osku's avatar
osku committed
389 390 391 392
void
mutex_set_waiters(
/*==============*/
	mutex_t*	mutex,	/* in: mutex */
393
	ulint		n)	/* in: value to set */
osku's avatar
osku committed
394
{
395 396
	volatile ulint*	ptr;		/* declared volatile to ensure that
					the value is stored to memory */
osku's avatar
osku committed
397 398 399 400 401 402 403 404 405 406 407 408
	ut_ad(mutex);

	ptr = &(mutex->waiters);

	*ptr = n;		/* Here we assume that the write of a single
				word in memory is atomic */
}

/**********************************************************************
Reserves a mutex for the current thread. If the mutex is reserved, the
function spins a preset time (controlled by SYNC_SPIN_ROUNDS), waiting
for the mutex before suspending the thread. */
409
UNIV_INTERN
osku's avatar
osku committed
410 411 412
void
mutex_spin_wait(
/*============*/
413 414 415 416
	mutex_t*	mutex,		/* in: pointer to mutex */
	const char*	file_name,	/* in: file name where mutex
					requested */
	ulint		line)		/* in: line where requested */
osku's avatar
osku committed
417
{
418 419
	ulint	   index; /* index of the reserved wait cell */
	ulint	   i;	  /* spin round count */
420
#if defined UNIV_DEBUG && !defined UNIV_HOTBACKUP
421
	ib_int64_t lstart_time = 0, lfinish_time; /* for timing os_wait */
422 423 424 425
	ulint ltime_diff;
	ulint sec;
	ulint ms;
	uint timer_started = 0;
426
#endif /* UNIV_DEBUG && !UNIV_HOTBACKUP */
427
	ut_ad(mutex);
osku's avatar
osku committed
428 429 430

mutex_loop:

431
	i = 0;
osku's avatar
osku committed
432

433 434 435 436 437
	/* Spin waiting for the lock word to become zero. Note that we do
	not have to assume that the read access to the lock word is atomic,
	as the actual locking is always committed with atomic test-and-set.
	In reality, however, all processors probably have an atomic read of
	a memory word. */
osku's avatar
osku committed
438 439

spin_loop:
440
#if defined UNIV_DEBUG && !defined UNIV_HOTBACKUP
441 442
	mutex_spin_wait_count++;
	mutex->count_spin_loop++;
443
#endif /* UNIV_DEBUG && !UNIV_HOTBACKUP */
osku's avatar
osku committed
444

445 446 447 448
	while (mutex_get_lock_word(mutex) != 0 && i < SYNC_SPIN_ROUNDS) {
		if (srv_spin_wait_delay) {
			ut_delay(ut_rnd_interval(0, srv_spin_wait_delay));
		}
osku's avatar
osku committed
449

450 451
		i++;
	}
osku's avatar
osku committed
452

453
	if (i == SYNC_SPIN_ROUNDS) {
454
#if defined UNIV_DEBUG && !defined UNIV_HOTBACKUP
455 456 457
		mutex->count_os_yield++;
		if (timed_mutexes == 1 && timer_started==0) {
			ut_usectime(&sec, &ms);
458
			lstart_time= (ib_int64_t)sec * 1000000 + ms;
459 460
			timer_started = 1;
		}
461
#endif /* UNIV_DEBUG && !UNIV_HOTBACKUP */
462 463
		os_thread_yield();
	}
osku's avatar
osku committed
464 465

#ifdef UNIV_SRV_PRINT_LATCH_WAITS
466
	fprintf(stderr,
467 468
		"Thread %lu spin wait mutex at %p"
		" cfile %s cline %lu rnds %lu\n",
469
		(ulong) os_thread_pf(os_thread_get_curr_id()), (void*) mutex,
470
		mutex->cfile_name, (ulong) mutex->cline, (ulong) i);
osku's avatar
osku committed
471 472
#endif

473
	mutex_spin_round_count += i;
osku's avatar
osku committed
474

475
#if defined UNIV_DEBUG && !defined UNIV_HOTBACKUP
476
	mutex->count_spin_rounds += i;
477
#endif /* UNIV_DEBUG && !UNIV_HOTBACKUP */
osku's avatar
osku committed
478

479 480
	if (mutex_test_and_set(mutex) == 0) {
		/* Succeeded! */
osku's avatar
osku committed
481

482
		ut_d(mutex->thread_id = os_thread_get_curr_id());
osku's avatar
osku committed
483
#ifdef UNIV_SYNC_DEBUG
484
		mutex_set_debug_info(mutex, file_name, line);
osku's avatar
osku committed
485 486
#endif

487 488
		goto finish_timing;
	}
osku's avatar
osku committed
489

490 491 492 493 494 495
	/* We may end up with a situation where lock_word is 0 but the OS
	fast mutex is still reserved. On FreeBSD the OS does not seem to
	schedule a thread which is constantly calling pthread_mutex_trylock
	(in mutex_test_and_set implementation). Then we could end up
	spinning here indefinitely. The following 'i++' stops this infinite
	spin. */
osku's avatar
osku committed
496

497
	i++;
osku's avatar
osku committed
498

499 500 501
	if (i < SYNC_SPIN_ROUNDS) {
		goto spin_loop;
	}
osku's avatar
osku committed
502

503
	sync_array_reserve_cell(sync_primary_wait_array, mutex,
504
				SYNC_MUTEX, file_name, line, &index);
osku's avatar
osku committed
505

506
	mutex_system_call_count++;
osku's avatar
osku committed
507

508 509 510 511 512
	/* The memory order of the array reservation and the change in the
	waiters field is important: when we suspend a thread, we first
	reserve the cell and then set waiters field to 1. When threads are
	released in mutex_exit, the waiters field is first set to zero and
	then the event is set to the signaled state. */
osku's avatar
osku committed
513

514
	mutex_set_waiters(mutex, 1);
osku's avatar
osku committed
515

516 517 518 519
	/* Try to reserve still a few times */
	for (i = 0; i < 4; i++) {
		if (mutex_test_and_set(mutex) == 0) {
			/* Succeeded! Free the reserved wait cell */
osku's avatar
osku committed
520

521
			sync_array_free_cell(sync_primary_wait_array, index);
osku's avatar
osku committed
522

523
			ut_d(mutex->thread_id = os_thread_get_curr_id());
osku's avatar
osku committed
524
#ifdef UNIV_SYNC_DEBUG
525
			mutex_set_debug_info(mutex, file_name, line);
osku's avatar
osku committed
526 527 528
#endif

#ifdef UNIV_SRV_PRINT_LATCH_WAITS
529 530 531
			fprintf(stderr, "Thread %lu spin wait succeeds at 2:"
				" mutex at %p\n",
				(ulong) os_thread_pf(os_thread_get_curr_id()),
532
				(void*) mutex);
osku's avatar
osku committed
533 534
#endif

535
			goto finish_timing;
osku's avatar
osku committed
536

537 538 539 540 541
			/* Note that in this case we leave the waiters field
			set to 1. We cannot reset it to zero, as we do not
			know if there are other waiters. */
		}
	}
osku's avatar
osku committed
542

543 544 545
	/* Now we know that there has been some thread holding the mutex
	after the change in the wait array and the waiters field was made.
	Now there is no risk of infinite wait on the event. */
osku's avatar
osku committed
546 547

#ifdef UNIV_SRV_PRINT_LATCH_WAITS
548 549
	fprintf(stderr,
		"Thread %lu OS wait mutex at %p cfile %s cline %lu rnds %lu\n",
550
		(ulong) os_thread_pf(os_thread_get_curr_id()), (void*) mutex,
551
		mutex->cfile_name, (ulong) mutex->cline, (ulong) i);
osku's avatar
osku committed
552 553
#endif

554 555
	mutex_system_call_count++;
	mutex_os_wait_count++;
osku's avatar
osku committed
556 557

#ifndef UNIV_HOTBACKUP
558
	mutex->count_os_wait++;
559
# ifdef UNIV_DEBUG
560 561 562 563
	/* !!!!! Sometimes os_wait can be called without os_thread_yield */

	if (timed_mutexes == 1 && timer_started==0) {
		ut_usectime(&sec, &ms);
564
		lstart_time= (ib_int64_t)sec * 1000000 + ms;
565 566
		timer_started = 1;
	}
567
# endif /* UNIV_DEBUG */
osku's avatar
osku committed
568 569
#endif /* !UNIV_HOTBACKUP */

570 571
	sync_array_wait_event(sync_primary_wait_array, index);
	goto mutex_loop;
osku's avatar
osku committed
572 573

finish_timing:
574
#if defined UNIV_DEBUG && !defined UNIV_HOTBACKUP
575 576
	if (timed_mutexes == 1 && timer_started==1) {
		ut_usectime(&sec, &ms);
577
		lfinish_time= (ib_int64_t)sec * 1000000 + ms;
578 579 580 581 582 583 584 585

		ltime_diff= (ulint) (lfinish_time - lstart_time);
		mutex->lspent_time += ltime_diff;

		if (mutex->lmax_spent_time < ltime_diff) {
			mutex->lmax_spent_time= ltime_diff;
		}
	}
586
#endif /* UNIV_DEBUG && !UNIV_HOTBACKUP */
587
	return;
osku's avatar
osku committed
588 589 590 591
}

/**********************************************************************
Releases the threads waiting in the primary wait array for this mutex. */
592
UNIV_INTERN
osku's avatar
osku committed
593 594 595 596 597 598 599 600 601
void
mutex_signal_object(
/*================*/
	mutex_t*	mutex)	/* in: mutex */
{
	mutex_set_waiters(mutex, 0);

	/* The memory order of resetting the waiters field and
	signaling the object is important. See LEMMA 1 above. */
602 603
	os_event_set(mutex->event);
	sync_array_object_signalled(sync_primary_wait_array);
osku's avatar
osku committed
604 605 606 607 608
}

#ifdef UNIV_SYNC_DEBUG
/**********************************************************************
Sets the debug information for a reserved mutex. */
609
UNIV_INTERN
osku's avatar
osku committed
610 611 612 613 614 615 616 617 618 619 620 621 622
void
mutex_set_debug_info(
/*=================*/
	mutex_t*	mutex,		/* in: mutex */
	const char*	file_name,	/* in: file where requested */
	ulint		line)		/* in: line where requested */
{
	ut_ad(mutex);
	ut_ad(file_name);

	sync_thread_add_level(mutex, mutex->level);

	mutex->file_name = file_name;
623 624
	mutex->line	 = line;
}
osku's avatar
osku committed
625 626 627

/**********************************************************************
Gets the debug information for a reserved mutex. */
628
UNIV_INTERN
osku's avatar
osku committed
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
void
mutex_get_debug_info(
/*=================*/
	mutex_t*	mutex,		/* in: mutex */
	const char**	file_name,	/* out: file where requested */
	ulint*		line,		/* out: line where requested */
	os_thread_id_t* thread_id)	/* out: id of the thread which owns
					the mutex */
{
	ut_ad(mutex);

	*file_name = mutex->file_name;
	*line	   = mutex->line;
	*thread_id = mutex->thread_id;
}

/**********************************************************************
Prints debug info of currently reserved mutexes. */
647
static
osku's avatar
osku committed
648
void
649 650 651
mutex_list_print_info(
/*==================*/
	FILE*	file)		/* in: file where to print */
osku's avatar
osku committed
652 653 654 655 656 657 658 659
{
	mutex_t*	mutex;
	const char*	file_name;
	ulint		line;
	os_thread_id_t	thread_id;
	ulint		count		= 0;

	fputs("----------\n"
660
	      "MUTEX INFO\n"
661
	      "----------\n", file);
osku's avatar
osku committed
662 663 664 665 666 667 668 669 670

	mutex_enter(&mutex_list_mutex);

	mutex = UT_LIST_GET_FIRST(mutex_list);

	while (mutex != NULL) {
		count++;

		if (mutex_get_lock_word(mutex) != 0) {
671
			mutex_get_debug_info(mutex, &file_name, &line,
672
					     &thread_id);
673
			fprintf(file,
674 675
				"Locked mutex: addr %p thread %ld"
				" file %s line %ld\n",
676
				(void*) mutex, os_thread_pf(thread_id),
osku's avatar
osku committed
677 678 679 680 681 682
				file_name, line);
		}

		mutex = UT_LIST_GET_NEXT(list, mutex);
	}

683
	fprintf(file, "Total number of mutexes %ld\n", count);
684

osku's avatar
osku committed
685 686 687 688 689
	mutex_exit(&mutex_list_mutex);
}

/**********************************************************************
Counts currently reserved mutexes. Works only in the debug version. */
690
UNIV_INTERN
osku's avatar
osku committed
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
ulint
mutex_n_reserved(void)
/*==================*/
{
	mutex_t*	mutex;
	ulint		count		= 0;

	mutex_enter(&mutex_list_mutex);

	mutex = UT_LIST_GET_FIRST(mutex_list);

	while (mutex != NULL) {
		if (mutex_get_lock_word(mutex) != 0) {

			count++;
		}

		mutex = UT_LIST_GET_NEXT(list, mutex);
	}

	mutex_exit(&mutex_list_mutex);

	ut_a(count >= 1);

	return(count - 1); /* Subtract one, because this function itself
			   was holding one mutex (mutex_list_mutex) */
}

/**********************************************************************
Returns TRUE if no mutex or rw-lock is currently locked. Works only in
the debug version. */
722
UNIV_INTERN
osku's avatar
osku committed
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
ibool
sync_all_freed(void)
/*================*/
{
	return(mutex_n_reserved() + rw_lock_n_locked() == 0);
}

/**********************************************************************
Gets the value in the nth slot in the thread level arrays. */
static
sync_thread_t*
sync_thread_level_arrays_get_nth(
/*=============================*/
			/* out: pointer to thread slot */
	ulint	n)	/* in: slot number */
{
	ut_ad(n < OS_THREAD_MAX_N);

	return(sync_thread_level_arrays + n);
}

/**********************************************************************
Looks for the thread slot for the calling thread. */
static
sync_thread_t*
sync_thread_level_arrays_find_slot(void)
/*====================================*/
			/* out: pointer to thread slot, NULL if not found */
751

osku's avatar
osku committed
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
{
	sync_thread_t*	slot;
	os_thread_id_t	id;
	ulint		i;

	id = os_thread_get_curr_id();

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

		slot = sync_thread_level_arrays_get_nth(i);

		if (slot->levels && os_thread_eq(slot->id, id)) {

			return(slot);
		}
	}

	return(NULL);
}

/**********************************************************************
Looks for an unused thread slot. */
static
sync_thread_t*
sync_thread_level_arrays_find_free(void)
/*====================================*/
			/* out: pointer to thread slot */
779

osku's avatar
osku committed
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
{
	sync_thread_t*	slot;
	ulint		i;

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

		slot = sync_thread_level_arrays_get_nth(i);

		if (slot->levels == NULL) {

			return(slot);
		}
	}

	return(NULL);
}

/**********************************************************************
Gets the value in the nth slot in the thread level array. */
static
sync_level_t*
sync_thread_levels_get_nth(
/*=======================*/
				/* out: pointer to level slot */
	sync_level_t*	arr,	/* in: pointer to level array for an OS
				thread */
	ulint		n)	/* in: slot number */
{
	ut_ad(n < SYNC_THREAD_N_LEVELS);

	return(arr + n);
}

/**********************************************************************
Checks if all the level values stored in the level array are greater than
the given limit. */
static
ibool
sync_thread_levels_g(
/*=================*/
				/* out: TRUE if all greater */
	sync_level_t*	arr,	/* in: pointer to level array for an OS
				thread */
	ulint		limit)	/* in: level limit */
{
	sync_level_t*	slot;
	rw_lock_t*	lock;
	mutex_t*	mutex;
	ulint		i;

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

		slot = sync_thread_levels_get_nth(arr, i);

		if (slot->latch != NULL) {
			if (slot->level <= limit) {

				lock = slot->latch;
				mutex = slot->latch;

				fprintf(stderr,
841
					"InnoDB: sync levels should be"
842 843
					" > %lu but a level is %lu\n",
					(ulong) limit, (ulong) slot->level);
osku's avatar
osku committed
844 845 846 847 848 849 850 851 852 853 854 855

				if (mutex->magic_n == MUTEX_MAGIC_N) {
					fprintf(stderr,
						"Mutex created at %s %lu\n",
						mutex->cfile_name,
						(ulong) mutex->cline);

					if (mutex_get_lock_word(mutex) != 0) {
						const char*	file_name;
						ulint		line;
						os_thread_id_t	thread_id;

856 857 858
						mutex_get_debug_info(
							mutex, &file_name,
							&line, &thread_id);
osku's avatar
osku committed
859 860

						fprintf(stderr,
861 862 863 864
							"InnoDB: Locked mutex:"
							" addr %p thread %ld"
							" file %s line %ld\n",
							(void*) mutex,
865 866
							os_thread_pf(
								thread_id),
867 868
							file_name,
							(ulong) line);
osku's avatar
osku committed
869 870
					} else {
						fputs("Not locked\n", stderr);
871
					}
osku's avatar
osku committed
872 873 874
				} else {
					rw_lock_print(lock);
				}
875

osku's avatar
osku committed
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
				return(FALSE);
			}
		}
	}

	return(TRUE);
}

/**********************************************************************
Checks if the level value is stored in the level array. */
static
ibool
sync_thread_levels_contain(
/*=======================*/
				/* out: TRUE if stored */
	sync_level_t*	arr,	/* in: pointer to level array for an OS
				thread */
	ulint		level)	/* in: level */
{
	sync_level_t*	slot;
	ulint		i;

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

		slot = sync_thread_levels_get_nth(arr, i);

		if (slot->latch != NULL) {
			if (slot->level == level) {

				return(TRUE);
			}
		}
	}

	return(FALSE);
}

/**********************************************************************
Checks that the level array for the current thread is empty. */
915
UNIV_INTERN
osku's avatar
osku committed
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
ibool
sync_thread_levels_empty_gen(
/*=========================*/
					/* out: TRUE if empty except the
					exceptions specified below */
	ibool	dict_mutex_allowed)	/* in: TRUE if dictionary mutex is
					allowed to be owned by the thread,
					also purge_is_running mutex is
					allowed */
{
	sync_level_t*	arr;
	sync_thread_t*	thread_slot;
	sync_level_t*	slot;
	ulint		i;

	if (!sync_order_checks_on) {

		return(TRUE);
	}

	mutex_enter(&sync_thread_mutex);

	thread_slot = sync_thread_level_arrays_find_slot();

	if (thread_slot == NULL) {

		mutex_exit(&sync_thread_mutex);

		return(TRUE);
	}

	arr = thread_slot->levels;

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

		slot = sync_thread_levels_get_nth(arr, i);

953 954 955 956
		if (slot->latch != NULL
		    && (!dict_mutex_allowed
			|| (slot->level != SYNC_DICT
			    && slot->level != SYNC_DICT_OPERATION))) {
osku's avatar
osku committed
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971

			mutex_exit(&sync_thread_mutex);
			ut_error;

			return(FALSE);
		}
	}

	mutex_exit(&sync_thread_mutex);

	return(TRUE);
}

/**********************************************************************
Checks that the level array for the current thread is empty. */
972
UNIV_INTERN
osku's avatar
osku committed
973 974 975 976 977 978 979 980 981 982 983 984
ibool
sync_thread_levels_empty(void)
/*==========================*/
			/* out: TRUE if empty */
{
	return(sync_thread_levels_empty_gen(FALSE));
}

/**********************************************************************
Adds a latch and its level in the thread level array. Allocates the memory
for the array if called first time for this OS thread. Makes the checks
against other latch levels stored in the array for this thread. */
985
UNIV_INTERN
osku's avatar
osku committed
986 987 988 989
void
sync_thread_add_level(
/*==================*/
	void*	latch,	/* in: pointer to a mutex or an rw-lock */
990 991
	ulint	level)	/* in: level in the latching order; if
			SYNC_LEVEL_VARYING, nothing is done */
osku's avatar
osku committed
992 993 994 995 996
{
	sync_level_t*	array;
	sync_level_t*	slot;
	sync_thread_t*	thread_slot;
	ulint		i;
997

osku's avatar
osku committed
998 999 1000 1001 1002 1003
	if (!sync_order_checks_on) {

		return;
	}

	if ((latch == (void*)&sync_thread_mutex)
1004 1005 1006
	    || (latch == (void*)&mutex_list_mutex)
	    || (latch == (void*)&rw_lock_debug_mutex)
	    || (latch == (void*)&rw_lock_list_mutex)) {
osku's avatar
osku committed
1007 1008 1009 1010

		return;
	}

1011
	if (level == SYNC_LEVEL_VARYING) {
osku's avatar
osku committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022

		return;
	}

	mutex_enter(&sync_thread_mutex);

	thread_slot = sync_thread_level_arrays_find_slot();

	if (thread_slot == NULL) {
		/* We have to allocate the level array for a new thread */
		array = ut_malloc(sizeof(sync_level_t) * SYNC_THREAD_N_LEVELS);
1023

osku's avatar
osku committed
1024
		thread_slot = sync_thread_level_arrays_find_free();
1025 1026

		thread_slot->id = os_thread_get_curr_id();
osku's avatar
osku committed
1027
		thread_slot->levels = array;
1028

osku's avatar
osku committed
1029 1030 1031 1032 1033 1034 1035 1036 1037
		for (i = 0; i < SYNC_THREAD_N_LEVELS; i++) {

			slot = sync_thread_levels_get_nth(array, i);

			slot->latch = NULL;
		}
	}

	array = thread_slot->levels;
1038

osku's avatar
osku committed
1039 1040 1041 1042 1043
	/* NOTE that there is a problem with _NODE and _LEAF levels: if the
	B-tree height changes, then a leaf can change to an internal node
	or the other way around. We do not know at present if this can cause
	unnecessary assertion failures below. */

1044 1045 1046 1047
	switch (level) {
	case SYNC_NO_ORDER_CHECK:
	case SYNC_EXTERN_STORAGE:
	case SYNC_TREE_NODE_FROM_HASH:
osku's avatar
osku committed
1048
		/* Do no order checking */
1049 1050 1051 1052
		break;
	case SYNC_MEM_POOL:
	case SYNC_MEM_HASH:
	case SYNC_RECV:
1053
	case SYNC_WORK_QUEUE:
1054 1055 1056 1057
	case SYNC_LOG:
	case SYNC_THR_LOCAL:
	case SYNC_ANY_LATCH:
	case SYNC_TRX_SYS_HEADER:
calvin's avatar
calvin committed
1058
	case SYNC_FILE_FORMAT_TAG:
1059
	case SYNC_DOUBLEWRITE:
1060 1061
	case SYNC_BUF_POOL:
	case SYNC_SEARCH_SYS:
1062
	case SYNC_SEARCH_SYS_CONF:
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	case SYNC_TRX_LOCK_HEAP:
	case SYNC_KERNEL:
	case SYNC_IBUF_BITMAP_MUTEX:
	case SYNC_RSEG:
	case SYNC_TRX_UNDO:
	case SYNC_PURGE_LATCH:
	case SYNC_PURGE_SYS:
	case SYNC_DICT_AUTOINC_MUTEX:
	case SYNC_DICT_OPERATION:
	case SYNC_DICT_HEADER:
vasil's avatar
vasil committed
1073 1074
	case SYNC_TRX_I_S_RWLOCK:
	case SYNC_TRX_I_S_LAST_READ:
1075 1076 1077
		if (!sync_thread_levels_g(array, level)) {
			fprintf(stderr,
				"InnoDB: sync_thread_levels_g(array, %lu)"
vasil's avatar
vasil committed
1078
				" does not hold!\n", level);
1079 1080
			ut_error;
		}
1081 1082
		break;
	case SYNC_BUF_BLOCK:
1083 1084 1085
		/* Either the thread must own the buffer pool mutex
		(buf_pool_mutex), or it is allowed to latch only ONE
		buffer block (block->mutex or buf_pool_zip_mutex). */
osku's avatar
osku committed
1086
		ut_a((sync_thread_levels_contain(array, SYNC_BUF_POOL)
1087 1088
		      && sync_thread_levels_g(array, SYNC_BUF_BLOCK - 1))
		     || sync_thread_levels_g(array, SYNC_BUF_BLOCK));
1089 1090
		break;
	case SYNC_REC_LOCK:
osku's avatar
osku committed
1091
		ut_a((sync_thread_levels_contain(array, SYNC_KERNEL)
1092 1093
		      && sync_thread_levels_g(array, SYNC_REC_LOCK - 1))
		     || sync_thread_levels_g(array, SYNC_REC_LOCK));
1094 1095
		break;
	case SYNC_IBUF_BITMAP:
1096 1097 1098
		/* Either the thread must own the master mutex to all
		the bitmap pages, or it is allowed to latch only ONE
		bitmap page. */
osku's avatar
osku committed
1099
		ut_a((sync_thread_levels_contain(array, SYNC_IBUF_BITMAP_MUTEX)
1100 1101
		      && sync_thread_levels_g(array, SYNC_IBUF_BITMAP - 1))
		     || sync_thread_levels_g(array, SYNC_IBUF_BITMAP));
1102 1103
		break;
	case SYNC_FSP_PAGE:
osku's avatar
osku committed
1104
		ut_a(sync_thread_levels_contain(array, SYNC_FSP));
1105 1106
		break;
	case SYNC_FSP:
osku's avatar
osku committed
1107
		ut_a(sync_thread_levels_contain(array, SYNC_FSP)
1108
		     || sync_thread_levels_g(array, SYNC_FSP));
1109 1110
		break;
	case SYNC_TRX_UNDO_PAGE:
osku's avatar
osku committed
1111
		ut_a(sync_thread_levels_contain(array, SYNC_TRX_UNDO)
1112 1113 1114
		     || sync_thread_levels_contain(array, SYNC_RSEG)
		     || sync_thread_levels_contain(array, SYNC_PURGE_SYS)
		     || sync_thread_levels_g(array, SYNC_TRX_UNDO_PAGE));
1115 1116
		break;
	case SYNC_RSEG_HEADER:
osku's avatar
osku committed
1117
		ut_a(sync_thread_levels_contain(array, SYNC_RSEG));
1118 1119
		break;
	case SYNC_RSEG_HEADER_NEW:
osku's avatar
osku committed
1120
		ut_a(sync_thread_levels_contain(array, SYNC_KERNEL)
1121
		     && sync_thread_levels_contain(array, SYNC_FSP_PAGE));
1122 1123
		break;
	case SYNC_TREE_NODE:
osku's avatar
osku committed
1124
		ut_a(sync_thread_levels_contain(array, SYNC_INDEX_TREE)
1125
		     || sync_thread_levels_contain(array, SYNC_DICT_OPERATION)
1126
		     || sync_thread_levels_g(array, SYNC_TREE_NODE - 1));
1127 1128
		break;
	case SYNC_TREE_NODE_NEW:
osku's avatar
osku committed
1129
		ut_a(sync_thread_levels_contain(array, SYNC_FSP_PAGE)
1130
		     || sync_thread_levels_contain(array, SYNC_IBUF_MUTEX));
1131 1132
		break;
	case SYNC_INDEX_TREE:
osku's avatar
osku committed
1133
		ut_a((sync_thread_levels_contain(array, SYNC_IBUF_MUTEX)
1134 1135 1136
		      && sync_thread_levels_contain(array, SYNC_FSP)
		      && sync_thread_levels_g(array, SYNC_FSP_PAGE - 1))
		     || sync_thread_levels_g(array, SYNC_TREE_NODE - 1));
1137 1138
		break;
	case SYNC_IBUF_MUTEX:
osku's avatar
osku committed
1139
		ut_a(sync_thread_levels_g(array, SYNC_FSP_PAGE - 1));
1140 1141
		break;
	case SYNC_IBUF_PESS_INSERT_MUTEX:
osku's avatar
osku committed
1142
		ut_a(sync_thread_levels_g(array, SYNC_FSP - 1)
1143
		     && !sync_thread_levels_contain(array, SYNC_IBUF_MUTEX));
1144 1145
		break;
	case SYNC_IBUF_HEADER:
osku's avatar
osku committed
1146
		ut_a(sync_thread_levels_g(array, SYNC_FSP - 1)
1147
		     && !sync_thread_levels_contain(array, SYNC_IBUF_MUTEX)
1148 1149
		     && !sync_thread_levels_contain(
			     array, SYNC_IBUF_PESS_INSERT_MUTEX));
1150 1151
		break;
	case SYNC_DICT:
osku's avatar
osku committed
1152 1153
#ifdef UNIV_DEBUG
		ut_a(buf_debug_prints
1154
		     || sync_thread_levels_g(array, SYNC_DICT));
osku's avatar
osku committed
1155 1156 1157
#else /* UNIV_DEBUG */
		ut_a(sync_thread_levels_g(array, SYNC_DICT));
#endif /* UNIV_DEBUG */
1158 1159
		break;
	default:
osku's avatar
osku committed
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
		ut_error;
	}

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

		slot = sync_thread_levels_get_nth(array, i);

		if (slot->latch == NULL) {
			slot->latch = latch;
			slot->level = level;

			break;
		}
	}

	ut_a(i < SYNC_THREAD_N_LEVELS);

	mutex_exit(&sync_thread_mutex);
}
1179

osku's avatar
osku committed
1180 1181
/**********************************************************************
Removes a latch from the thread level array if it is found there. */
1182
UNIV_INTERN
osku's avatar
osku committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
ibool
sync_thread_reset_level(
/*====================*/
			/* out: TRUE if found from the array; it is an error
			if the latch is not found */
	void*	latch)	/* in: pointer to a mutex or an rw-lock */
{
	sync_level_t*	array;
	sync_level_t*	slot;
	sync_thread_t*	thread_slot;
	ulint		i;
1194

osku's avatar
osku committed
1195 1196 1197 1198 1199 1200
	if (!sync_order_checks_on) {

		return(FALSE);
	}

	if ((latch == (void*)&sync_thread_mutex)
1201 1202 1203
	    || (latch == (void*)&mutex_list_mutex)
	    || (latch == (void*)&rw_lock_debug_mutex)
	    || (latch == (void*)&rw_lock_list_mutex)) {
osku's avatar
osku committed
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

		return(FALSE);
	}

	mutex_enter(&sync_thread_mutex);

	thread_slot = sync_thread_level_arrays_find_slot();

	if (thread_slot == NULL) {

		ut_error;

		mutex_exit(&sync_thread_mutex);
		return(FALSE);
	}

	array = thread_slot->levels;
1221

osku's avatar
osku committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
	for (i = 0; i < SYNC_THREAD_N_LEVELS; i++) {

		slot = sync_thread_levels_get_nth(array, i);

		if (slot->latch == latch) {
			slot->latch = NULL;

			mutex_exit(&sync_thread_mutex);

			return(TRUE);
		}
	}

1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
	if (((mutex_t*) latch)->magic_n != MUTEX_MAGIC_N) {
		rw_lock_t*	rw_lock;

		rw_lock = (rw_lock_t*) latch;

		if (rw_lock->level == SYNC_LEVEL_VARYING) {
			mutex_exit(&sync_thread_mutex);

			return(TRUE);
		}
	}

osku's avatar
osku committed
1247 1248 1249 1250 1251 1252
	ut_error;

	mutex_exit(&sync_thread_mutex);

	return(FALSE);
}
1253
#endif /* UNIV_SYNC_DEBUG */
1254

osku's avatar
osku committed
1255 1256
/**********************************************************************
Initializes the synchronization data structures. */
1257
UNIV_INTERN
osku's avatar
osku committed
1258 1259 1260 1261
void
sync_init(void)
/*===========*/
{
1262
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
1263 1264
	sync_thread_t*	thread_slot;
	ulint		i;
1265
#endif /* UNIV_SYNC_DEBUG */
1266

osku's avatar
osku committed
1267 1268 1269 1270 1271 1272 1273 1274
	ut_a(sync_initialized == FALSE);

	sync_initialized = TRUE;

	/* Create the primary system wait array which is protected by an OS
	mutex */

	sync_primary_wait_array = sync_array_create(OS_THREAD_MAX_N,
1275
						    SYNC_ARRAY_OS_MUTEX);
1276
#ifdef UNIV_SYNC_DEBUG
osku's avatar
osku committed
1277 1278 1279 1280
	/* Create the thread latch level array where the latch levels
	are stored for each OS thread */

	sync_thread_level_arrays = ut_malloc(OS_THREAD_MAX_N
1281
					     * sizeof(sync_thread_t));
osku's avatar
osku committed
1282 1283 1284 1285 1286
	for (i = 0; i < OS_THREAD_MAX_N; i++) {

		thread_slot = sync_thread_level_arrays_get_nth(i);
		thread_slot->levels = NULL;
	}
1287
#endif /* UNIV_SYNC_DEBUG */
1288
	/* Init the mutex list and create the mutex to protect it. */
osku's avatar
osku committed
1289 1290

	UT_LIST_INIT(mutex_list);
1291
	mutex_create(&mutex_list_mutex, SYNC_NO_ORDER_CHECK);
1292
#ifdef UNIV_SYNC_DEBUG
1293
	mutex_create(&sync_thread_mutex, SYNC_NO_ORDER_CHECK);
1294
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
1295 1296 1297 1298

	/* Init the rw-lock list and create the mutex to protect it. */

	UT_LIST_INIT(rw_lock_list);
1299
	mutex_create(&rw_lock_list_mutex, SYNC_NO_ORDER_CHECK);
osku's avatar
osku committed
1300 1301

#ifdef UNIV_SYNC_DEBUG
1302
	mutex_create(&rw_lock_debug_mutex, SYNC_NO_ORDER_CHECK);
osku's avatar
osku committed
1303 1304 1305 1306 1307 1308 1309 1310 1311

	rw_lock_debug_event = os_event_create(NULL);
	rw_lock_debug_waiters = FALSE;
#endif /* UNIV_SYNC_DEBUG */
}

/**********************************************************************
Frees the resources in InnoDB's own synchronization data structures. Use
os_sync_free() after calling this. */
1312
UNIV_INTERN
osku's avatar
osku committed
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
void
sync_close(void)
/*===========*/
{
	mutex_t*	mutex;

	sync_array_free(sync_primary_wait_array);

	mutex = UT_LIST_GET_FIRST(mutex_list);

	while (mutex) {
1324
		mutex_free(mutex);
osku's avatar
osku committed
1325 1326 1327 1328
		mutex = UT_LIST_GET_FIRST(mutex_list);
	}

	mutex_free(&mutex_list_mutex);
1329
#ifdef UNIV_SYNC_DEBUG
1330
	mutex_free(&sync_thread_mutex);
1331
#endif /* UNIV_SYNC_DEBUG */
osku's avatar
osku committed
1332 1333 1334 1335
}

/***********************************************************************
Prints wait info of the sync system. */
1336
UNIV_INTERN
osku's avatar
osku committed
1337 1338 1339 1340 1341 1342
void
sync_print_wait_info(
/*=================*/
	FILE*	file)		/* in: file where to print */
{
#ifdef UNIV_SYNC_DEBUG
1343
	fprintf(file, "Mutex exits %lu, rws exits %lu, rwx exits %lu\n",
osku's avatar
osku committed
1344 1345 1346 1347
		mutex_exit_count, rw_s_exit_count, rw_x_exit_count);
#endif

	fprintf(file,
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
		"Mutex spin waits %lu, rounds %lu, OS waits %lu\n"
		"RW-shared spins %lu, OS waits %lu;"
		" RW-excl spins %lu, OS waits %lu\n",
		(ulong) mutex_spin_wait_count,
		(ulong) mutex_spin_round_count,
		(ulong) mutex_os_wait_count,
		(ulong) rw_s_spin_wait_count,
		(ulong) rw_s_os_wait_count,
		(ulong) rw_x_spin_wait_count,
		(ulong) rw_x_os_wait_count);
osku's avatar
osku committed
1358 1359 1360 1361
}

/***********************************************************************
Prints info of the sync system. */
1362
UNIV_INTERN
osku's avatar
osku committed
1363 1364 1365 1366 1367 1368
void
sync_print(
/*=======*/
	FILE*	file)		/* in: file where to print */
{
#ifdef UNIV_SYNC_DEBUG
1369
	mutex_list_print_info(file);
osku's avatar
osku committed
1370

1371
	rw_lock_list_print_info(file);
osku's avatar
osku committed
1372 1373 1374 1375 1376 1377
#endif /* UNIV_SYNC_DEBUG */

	sync_array_print_info(file, sync_primary_wait_array);

	sync_print_wait_info(file);
}