lock_xt.cc 73.6 KB
Newer Older
Paul McCullagh's avatar
Paul McCullagh 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
/* Copyright (c) 2005 PrimeBase Technologies GmbH
 *
 * PrimeBase XT
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * 2008-01-24	Paul McCullagh
 *
 * Row lock functions.
 *
 * H&G2JCtL
 */

#include "xt_config.h"

28 29 30 31
#ifdef DRIZZLED
#include <bitset>
#endif

Paul McCullagh's avatar
Paul McCullagh committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include <stdio.h>

#include "lock_xt.h"
#include "thread_xt.h"
#include "table_xt.h"
#include "xaction_xt.h"
#include "database_xt.h"
#include "trace_xt.h"

#ifdef DEBUG
//#define XT_TRACE_LOCKS
//#define CHECK_ROWLOCK_GROUP_CONSISTENCY
#endif

46 47 48 49 50 51 52 53 54 55
/*
 * This function should never be called. It indicates a link
 * error!
 */
xtPublic void xt_log_atomic_error_and_abort(c_char *func, c_char *file, u_int line)
{
	xt_logf(NULL, func, file, line, XT_LOG_ERROR, "%s", "Atomic operations not supported\n");
	abort();
}

Paul McCullagh's avatar
Paul McCullagh committed
56 57 58 59 60 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 98 99 100 101 102 103 104 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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 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
/*
 * -----------------------------------------------------------------------
 * ROW LOCKS, LIST BASED
 */
#ifdef XT_USE_LIST_BASED_ROW_LOCKS

#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
/* 
 * Requires a spin-lock on group->lg_lock!
 */
static void check_rowlock_group(XTLockGroupPtr group)
{
	XTThreadPtr self = xt_get_self();

	char *crash = NULL;

	if (group->lg_lock.spl_locker != self)
		*crash = 1;

	if (group->lg_list_in_use > group->lg_list_size)
		*crash = 1;

	xtRowID prev_row = 0;
	XTLockItemPtr item = group->lg_list;

	for (int i = 0; i < group->lg_list_in_use; i++, item++) {

		if (!item->li_thread_id)
			*crash = 1;

		if(!xt_thr_array[item->li_thread_id]->st_xact_data)
			*crash = 1;

		if(item->li_count > XT_TEMP_LOCK_BYTES)
			*crash = 1;

		// rows per thread must obey the row_id > prev_row_id + prev_count*group_size rule
		if (prev_row >= item->li_row_id)
			*crash = 1;

		// calculate the new prev. row
		if (item->li_count < XT_TEMP_LOCK_BYTES)
			prev_row = item->li_row_id + (item->li_count - 1) * XT_ROW_LOCK_GROUP_COUNT;
		else
			prev_row = item->li_row_id;
	}
}
#endif

static int xlock_cmp_row_ids(XTThreadPtr XT_UNUSED(self), register const void *XT_UNUSED(thunk), register const void *a, register const void *b)
{
	xtRowID			row_id = *((xtTableID *) a);
	XTLockItemPtr	item = (XTLockItemPtr) b;

	if (row_id < item->li_row_id)
		return -1;
	if (row_id > item->li_row_id)
		return 1;
	return 0;
}

void XTRowLockList::xt_remove_all_locks(struct XTDatabase *, XTThreadPtr thread)
{
#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "remove all locks\n");
#endif
	if (!bl_count)
		return;

	xtThreadID			thd_id;
	XTPermRowLockPtr	plock;
#ifndef XT_USE_TABLE_REF
	XTOpenTablePtr		pot = NULL;
#endif

	thd_id = thread->t_id;
	plock = (XTPermRowLockPtr) bl_data;
	for (u_int i=0; i<bl_count; i++) {
#ifdef XT_USE_TABLE_REF
		XTTableHPtr		tab = plock->pr_table;
#else
		if (!xt_db_open_pool_table_ns(&pot, db, plock->pr_tab_id)) {
			/* Should not happen, but just in case, we just don't
			 * remove the lock. We will probably end up with a deadlock
			 * somewhere.
			 */
			xt_log_and_clear_exception_ns();
		}
		else {
#endif
			for (int j=0; j<XT_ROW_LOCK_GROUP_COUNT; j++) {
				if (plock->pr_group[j]) {
					/* Go through group j and compact. */
#ifndef XT_USE_TABLE_REF
					XTTableHPtr		tab = pot->ot_table;
#endif
					XTLockGroupPtr	group;
					XTLockItemPtr	copy;
					XTLockItemPtr	item;
					int				new_count;

					group = &tab->tab_locks.rl_groups[j];
					xt_spinlock_lock(&group->lg_lock);
					copy = group->lg_list;
					item = group->lg_list;
					new_count = 0;
					for (size_t k=0; k<group->lg_list_in_use; k++) {
						if (item->li_thread_id != thd_id) {
							if (copy != item) {
								copy->li_row_id = item->li_row_id;
								copy->li_count = item->li_count;
								copy->li_thread_id = item->li_thread_id;
							}
							new_count++;
							copy++;
						}
#ifdef XT_TRACE_LOCKS
						else {
							if (item->li_count == XT_TEMP_LOCK_BYTES)
								xt_ttracef(xt_get_self(), "remove group %d lock row_id=%d TEMP\n", j, (int) item->li_row_id);
							else
								xt_ttracef(xt_get_self(), "remove group %d locks row_id=%d (%d)\n", j, (int) item->li_row_id, (int) item->li_count);
						}
#endif
						item++;
					}
					group->lg_list_in_use = new_count;
#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
					check_rowlock_group(group);
#endif
					if (group->lg_wait_queue)
						tab->tab_locks.rl_grant_locks(group, thread);

					xt_spinlock_unlock(&group->lg_lock);
					
					xt_xn_wakeup_thread_list(thread);
				}
			}
#ifdef XT_USE_TABLE_REF
			xt_heap_release(NULL, plock->pr_table);
#else
			xt_db_return_table_to_pool_ns(pot);
		}
#endif
		plock++;
	}
	bl_count = 0;
}

#ifdef DEBUG_LOCK_QUEUE
int *dummy_ptr = 0;

void XTRowLocks::rl_check(XTLockWaitPtr no_lw)
{
	XTLockGroupPtr	group;
	XTLockWaitPtr	lw, lw_prev;

	for (int i=0; i<XT_ROW_LOCK_GROUP_COUNT; i++) {
		group = &rl_groups[i];
		xt_spinlock_lock(&group->lg_lock);

		lw = group->lg_wait_queue;
		lw_prev = NULL;
		while (lw) {
			if (lw == no_lw)
				*dummy_ptr = 1;
			if (lw->lw_prev != lw_prev)
				*dummy_ptr = 2;
			lw_prev = lw;
			lw = lw->lw_next;
		}
		xt_spinlock_unlock(&group->lg_lock);
	}
}
#endif

xtBool XTRowLocks::rl_lock_row(XTLockGroupPtr group, XTLockWaitPtr lw, XTRowLockListPtr, int *result)
{
	XTLockItemPtr	item;
	size_t			index;
	xtRowID			row_id = lw->lw_row_id;

#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
	check_rowlock_group(group);
#endif
	if (group->lg_list_size == group->lg_list_in_use) {
		if (!xt_realloc_ns((void **) &group->lg_list, (group->lg_list_size + 2) * sizeof(XTLockItemRec)))
			return FAILED;
		group->lg_list_size += 2;
	}
	item = (XTLockItemPtr) xt_bsearch(NULL, &row_id, group->lg_list, group->lg_list_in_use, sizeof(XTLockItemRec), &index, NULL, xlock_cmp_row_ids);
	
	/* There's no item with this ID, but there could be an item with a range that covers this row */
	if (!item && group->lg_list_in_use) {
		if (index > 0) {
			int count;
	
			item = group->lg_list + index - 1;

			count = item->li_count;
			if (item->li_count == XT_TEMP_LOCK_BYTES)
				count = 1;

			if (row_id >= item->li_row_id + count * XT_ROW_LOCK_GROUP_COUNT)
				item = NULL;
		}
	}
	
	if (item) {
		/* Item already exists. */
		if (item->li_thread_id == lw->lw_thread->t_id) {
			/* Already have a permanent lock: */
			*result = XT_NO_LOCK;
			lw->lw_curr_lock = XT_NO_LOCK;
			return OK;
		}
		/* {REMOVE-LOCKS}
		 * This must be valid because a thread must remove
		 * the locks before it frees its st_xact_data structure,
		 * xt_thr_array entry must also be valid, because
		 * transaction must be ended before the thread is
		 * killed.
		 */
		*result = item->li_count == XT_TEMP_LOCK_BYTES ? XT_TEMP_LOCK : XT_PERM_LOCK;
		lw->lw_xn_id = xt_thr_array[item->li_thread_id]->st_xact_data->xd_start_xn_id;
		lw->lw_curr_lock = *result;
		return OK;
	}

	/* Add the lock: */
	XT_MEMMOVE(group->lg_list, &group->lg_list[index+1], 
		&group->lg_list[index], (group->lg_list_in_use - index) * sizeof(XTLockItemRec));
	group->lg_list[index].li_row_id = row_id;
	group->lg_list[index].li_count = XT_TEMP_LOCK_BYTES;
	group->lg_list[index].li_thread_id = lw->lw_thread->t_id;
	group->lg_list_in_use++;

#ifdef XT_TRACE_LOCKS
	xt_ttracef(ot->ot_thread, "set temp lock row=%d setby=%s\n", (int) row_id, xt_get_self()->t_name);
#endif
#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
	check_rowlock_group(group);
#endif
	*result = XT_NO_LOCK;
	lw->lw_ot->ot_temp_row_lock = row_id;
	lw->lw_curr_lock = XT_NO_LOCK;
	return OK;
}

void XTRowLocks::rl_grant_locks(XTLockGroupPtr group, XTThreadPtr thread)
{
	XTLockWaitPtr	lw, lw_next, lw_prev;
	int				result;
	xtThreadID		lw_thd_id;

	thread->st_thread_list_count = 0;
	lw = group->lg_wait_queue;
	while (lw) {
		lw_next = lw->lw_next;
		lw_prev = lw->lw_prev;
		lw_thd_id = lw->lw_thread->t_id;
		/* NOTE: after lw_curr_lock is changed, lw may no longer be referenced
		 * by this function!!!
		 */
		if (!rl_lock_row(group, lw, &lw->lw_thread->st_lock_list, &result)) {
			/* We transfer the error to the other thread! */
			XTThreadPtr self = xt_get_self();

			result = XT_LOCK_ERR;
			memcpy(&lw->lw_thread->t_exception, &self->t_exception, sizeof(XTExceptionRec));
			lw->lw_curr_lock = XT_LOCK_ERR;
		}
		if (result == XT_NO_LOCK || result == XT_LOCK_ERR) {
			/* Remove from the wait queue: */
			if (lw_next)
				lw_next->lw_prev = lw_prev;
			if (lw_prev)
				lw_prev->lw_next = lw_next;
			if (group->lg_wait_queue == lw)
				group->lg_wait_queue = lw_next;
			if (group->lg_wait_queue_end == lw)
				group->lg_wait_queue_end = lw_prev;
			if (result == XT_NO_LOCK) {
				/* Add to the thread list: */
				if (thread->st_thread_list_count == thread->st_thread_list_size) {
					if (!xt_realloc_ns((void **) &thread->st_thread_list, (thread->st_thread_list_size+1) * sizeof(xtThreadID))) {
						xt_xn_wakeup_thread(lw_thd_id);
						goto done;
					}
					thread->st_thread_list_size++;
				}
				thread->st_thread_list[thread->st_thread_list_count] = lw_thd_id;
				thread->st_thread_list_count++;
				done:;
			}
		}
		lw = lw_next;
	}
}

Paul McCullagh's avatar
Paul McCullagh committed
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
void XTRowLocks::xt_cancel_temp_lock(XTLockWaitPtr lw)
{
	XTLockGroupPtr	group;

	group = &rl_groups[lw->lw_row_id % XT_ROW_LOCK_GROUP_COUNT];
	xt_spinlock_lock(&group->lg_lock);
	if (lw->lw_curr_lock == XT_TEMP_LOCK || lw->lw_curr_lock == XT_PERM_LOCK) {
		/* In case of XT_LOCK_ERR or XT_NO_LOCK, the lw structure will
		 * no longer be on the wait queue.
		 */
		XTLockWaitPtr	lw_next, lw_prev;

		lw_next = lw->lw_next;
		lw_prev = lw->lw_prev;

		/* Remove from the wait queue: */
		if (lw_next)
			lw_next->lw_prev = lw_prev;
		if (lw_prev)
			lw_prev->lw_next = lw_next;
		if (group->lg_wait_queue == lw)
			group->lg_wait_queue = lw_next;
		if (group->lg_wait_queue_end == lw)
			group->lg_wait_queue_end = lw_prev;
	}
	xt_spinlock_unlock(&group->lg_lock);
}

Paul McCullagh's avatar
Paul McCullagh committed
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 665 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
//#define QUEUE_ORDER_FIFO

/* Try to lock a row.
 * This function returns:
 * XT_NO_LOCK on success.
 * XT_TEMP_LOCK if there is a temporary lock on the row.
 * XT_PERM_LOCK if there is a permanent lock in the row.
 * XT_FAILED an error occured.
 *
 * If there is a lock on this row, the transaction ID of the
 * locker is also returned.
 *
 * The caller must wait if the row is locked. If the lock is
 * permanent, then the caller must wait for the transaction to
 * terminate. If the lock is temporary, then the caller must
 * wait for the transaction to signal that the lock has been
 * released.
 */
xtBool XTRowLocks::xt_set_temp_lock(XTOpenTablePtr ot, XTLockWaitPtr lw, XTRowLockListPtr lock_list)
{
	XTLockGroupPtr	group;
	int				result;

	if (ot->ot_temp_row_lock) {
		/* Check if we don't already have this temp lock: */
		if (ot->ot_temp_row_lock == lw->lw_row_id) {
			lw->lw_curr_lock = XT_NO_LOCK;
			return OK;
		}

		xt_make_lock_permanent(ot, lock_list);
	}

	/* Add a temporary lock. */
	group = &rl_groups[lw->lw_row_id % XT_ROW_LOCK_GROUP_COUNT];
	xt_spinlock_lock(&group->lg_lock);

	if (!rl_lock_row(group, lw, lock_list, &result)) {
		xt_spinlock_unlock(&group->lg_lock);
		return FAILED;
	}

	if (result != XT_NO_LOCK) {
		/* Add the thread to the end of the thread queue: */
#ifdef QUEUE_ORDER_FIFO
		if (group->lg_wait_queue_end) {
			group->lg_wait_queue_end->lw_next = lw;
			lw->lw_prev = group->lg_wait_queue_end;
		}
		else {
			group->lg_wait_queue = lw;
			lw->lw_prev = NULL;
		}
		lw->lw_next = NULL;
		group->lg_wait_queue_end = lw;
#else
		XTLockWaitPtr	pos = group->lg_wait_queue_end;
		xtXactID		xn_id = ot->ot_thread->st_xact_data->xd_start_xn_id;
		
		while (pos) {
			if (pos->lw_thread->st_xact_data->xd_start_xn_id < xn_id)
				break;
			pos = pos->lw_prev;
		}
		if (pos) {
			lw->lw_prev = pos;
			lw->lw_next = pos->lw_next;
			if (pos->lw_next)
				pos->lw_next->lw_prev = lw;
			else
				group->lg_wait_queue_end = lw;
			pos->lw_next = lw;
		}
		else {
			/* Front of the queue: */
			lw->lw_prev = NULL;
			lw->lw_next = group->lg_wait_queue;
			if (group->lg_wait_queue)
				group->lg_wait_queue->lw_prev = lw;
			else
				group->lg_wait_queue_end = lw;
			group->lg_wait_queue = lw;
		}
#endif
	}

	xt_spinlock_unlock(&group->lg_lock);
	return OK;
}

/*
 * Remove a temporary lock.
 * 
 * If updated is set to TRUE this means that the row was update.
 * This means that any thread waiting on the temporary lock will
 * also have to wait for the transaction to quit before
 * continuing.
 *
 * If the thread were to continue it would just hang again because
 * it will discover that the transaction has updated the row.
 *
 * So the 'updated' flag is an optimisation which prevents the
 * thread from making an unncessary retry.
 */
void XTRowLocks::xt_remove_temp_lock(XTOpenTablePtr ot, xtBool updated)
{
	xtRowID			row_id;
	XTLockGroupPtr	group;
	XTLockItemPtr	item;
	size_t			index;
	xtBool			lock_granted = FALSE;
	xtThreadID		locking_thread_id = 0;

	if (!(row_id = ot->ot_temp_row_lock))
		return;

	group = &rl_groups[row_id % XT_ROW_LOCK_GROUP_COUNT];
	xt_spinlock_lock(&group->lg_lock);
#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
	check_rowlock_group(group);
#endif

#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "remove temp lock %d\n", (int) row_id);
#endif
	item = (XTLockItemPtr) xt_bsearch(NULL, &row_id, group->lg_list, group->lg_list_in_use, sizeof(XTLockItemRec), &index, NULL, xlock_cmp_row_ids);
	if (item) {
		/* Item exists. */
		if (item->li_thread_id == ot->ot_thread->t_id &&
			item->li_count == XT_TEMP_LOCK_BYTES) {
			XTLockWaitPtr	lw;

			/* First check if there is some thread waiting to take over this lock: */
			lw = group->lg_wait_queue;
			while (lw) {
				if (lw->lw_row_id == row_id) {
					lock_granted = TRUE;
					break;
				}
				lw = lw->lw_next;
			}

			if (lock_granted) {
				/* Grant the lock just released... */
				XTLockWaitPtr	lw_next, lw_prev;
				xtXactID		locking_xact_id;

				/* Store this info, lw will soon be untouchable! */
				lw_next = lw->lw_next;
				lw_prev = lw->lw_prev;
				locking_xact_id = lw->lw_thread->st_xact_data->xd_start_xn_id;
				locking_thread_id = lw->lw_thread->t_id;

				/* Lock has moved from one thread to the next.
				 * change the thread holding this lock:
				 */
				item->li_thread_id = locking_thread_id;

				/* Remove from the wait queue: */
				if (lw_next)
					lw_next->lw_prev = lw_prev;
				if (lw_prev)
					lw_prev->lw_next = lw_next;
				if (group->lg_wait_queue == lw)
					group->lg_wait_queue = lw_next;
				if (group->lg_wait_queue_end == lw)
					group->lg_wait_queue_end = lw_prev;

				/* If the thread that release the lock updated the
				 * row then we will have to wait for the transaction
				 * to terminate:
				 */
				if (updated) {
					lw->lw_row_updated = TRUE;
					lw->lw_updating_xn_id = ot->ot_thread->st_xact_data->xd_start_xn_id;
				}

				/* The thread has the lock now: */
				lw->lw_ot->ot_temp_row_lock = row_id;
				lw->lw_curr_lock = XT_NO_LOCK;

				/* Everyone after this that is waiting for the same lock is
				 * now waiting for a different transaction:
				 */
				lw = lw_next;
				while (lw) {
					if (lw->lw_row_id == row_id) {
						lw->lw_xn_id = locking_xact_id;
						lw->lw_curr_lock = XT_TEMP_LOCK;
					}
					lw = lw->lw_next;
				}
			}
			else {
				/* Remove the lock: */
				XT_MEMMOVE(group->lg_list, &group->lg_list[index], 
					&group->lg_list[index+1], (group->lg_list_in_use - index - 1) * sizeof(XTLockItemRec));
				group->lg_list_in_use--;
			}
		}
	}
#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
	check_rowlock_group(group);
#endif
	xt_spinlock_unlock(&group->lg_lock);

	ot->ot_temp_row_lock = 0;
	if (lock_granted)
		xt_xn_wakeup_thread(locking_thread_id);
}

xtBool XTRowLocks::xt_make_lock_permanent(XTOpenTablePtr ot, XTRowLockListPtr lock_list)
{
	xtRowID			row_id;
	XTLockGroupPtr	group;
	XTLockItemPtr	item;
	size_t			index;

	if (!(row_id = ot->ot_temp_row_lock))
		return OK;

#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "make lock perm %d\n", (int) ot->ot_temp_row_lock);
#endif

	/* Add to the lock list: */
	XTPermRowLockPtr locks = (XTPermRowLockPtr) lock_list->bl_data;
	for (unsigned i=0; i<lock_list->bl_count; i++) {
#ifdef XT_USE_TABLE_REF
		if (locks->pr_table == ot->ot_table) {
#else
		if (locks->pr_tab_id == ot->ot_table->tab_id) {
#endif
			locks->pr_group[row_id % XT_ROW_LOCK_GROUP_COUNT] = 1;
			goto done;
		}
		locks++;
	}

	/* Add new to lock list: */
	{
		XTPermRowLockRec perm_lock;
		
#ifdef XT_USE_TABLE_REF
		perm_lock.pr_table = ot->ot_table;
		xt_heap_reference(NULL, perm_lock.pr_table);
#else
		perm_lock.pr_tab_id = ot->ot_table->tab_id;
#endif
		memset(perm_lock.pr_group, 0, XT_ROW_LOCK_GROUP_COUNT);
		perm_lock.pr_group[row_id % XT_ROW_LOCK_GROUP_COUNT] = 1;
		if (!xt_bl_append(NULL, lock_list, &perm_lock)) {
			xt_remove_temp_lock(ot, FALSE);
			return FAILED;
		}
	}

	done:
	group = &rl_groups[row_id % XT_ROW_LOCK_GROUP_COUNT];
	xt_spinlock_lock(&group->lg_lock);

	item = (XTLockItemPtr) xt_bsearch(NULL, &row_id, group->lg_list, group->lg_list_in_use, sizeof(XTLockItemRec), &index, NULL, xlock_cmp_row_ids);
	ASSERT_NS(item);
#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
	check_rowlock_group(group);
#endif
	if (item) {
		/* Lock exists (it should!). */
		if (item->li_thread_id == ot->ot_thread->t_id &&
			item->li_count == XT_TEMP_LOCK_BYTES) {
			if (index > 0 &&
				group->lg_list[index-1].li_thread_id == ot->ot_thread->t_id &&
				group->lg_list[index-1].li_count < XT_TEMP_LOCK_BYTES-2 &&
				group->lg_list[index-1].li_row_id == row_id - (XT_ROW_LOCK_GROUP_COUNT * group->lg_list[index-1].li_count)) {
				group->lg_list[index-1].li_count++;
				/* Combine with the left: */
				if (index + 1 < group->lg_list_in_use &&
					group->lg_list[index+1].li_thread_id == ot->ot_thread->t_id &&
					group->lg_list[index+1].li_count != XT_TEMP_LOCK_BYTES &&
					group->lg_list[index+1].li_row_id == row_id + XT_ROW_LOCK_GROUP_COUNT) {
					/* And combine with the right */
					u_int left = group->lg_list[index-1].li_count + group->lg_list[index+1].li_count;
					u_int right;

					if (left > XT_TEMP_LOCK_BYTES-1) {
						right = left - (XT_TEMP_LOCK_BYTES-1);
						left = XT_TEMP_LOCK_BYTES-1;
					}
					else
						right = 0;

					group->lg_list[index-1].li_count = left;
					if (right) {
						/* There is something left over on the right: */
						group->lg_list[index+1].li_count = right;
						group->lg_list[index+1].li_row_id = group->lg_list[index-1].li_row_id + left * XT_ROW_LOCK_GROUP_COUNT;
						XT_MEMMOVE(group->lg_list, &group->lg_list[index], 
							&group->lg_list[index+1], (group->lg_list_in_use - index - 1) * sizeof(XTLockItemRec));
						group->lg_list_in_use--;
					}
					else {
						XT_MEMMOVE(group->lg_list, &group->lg_list[index], 
							&group->lg_list[index+2], (group->lg_list_in_use - index - 2) * sizeof(XTLockItemRec));
						group->lg_list_in_use -= 2;
					}
				}
				else {
					XT_MEMMOVE(group->lg_list, &group->lg_list[index], 
						&group->lg_list[index+1], (group->lg_list_in_use - index - 1) * sizeof(XTLockItemRec));
					group->lg_list_in_use--;
				}
			}
			else if (index + 1 < group->lg_list_in_use &&
					group->lg_list[index+1].li_thread_id == ot->ot_thread->t_id &&
					group->lg_list[index+1].li_count < XT_TEMP_LOCK_BYTES-2 &&
					group->lg_list[index+1].li_row_id == row_id + XT_ROW_LOCK_GROUP_COUNT) {
				/* Combine with the right: */
				group->lg_list[index+1].li_count++;
				group->lg_list[index+1].li_row_id = row_id;
				XT_MEMMOVE(group->lg_list, &group->lg_list[index], 
					&group->lg_list[index+1], (group->lg_list_in_use - index - 1) * sizeof(XTLockItemRec));
				group->lg_list_in_use--;
			}
			else
				group->lg_list[index].li_count = 1;
		}
	}
#ifdef CHECK_ROWLOCK_GROUP_CONSISTENCY
	check_rowlock_group(group);
#endif
	xt_spinlock_unlock(&group->lg_lock);

	ot->ot_temp_row_lock = 0;
	return OK;
}

xtBool xt_init_row_locks(XTRowLocksPtr rl)
{
	for (int i=0; i<XT_ROW_LOCK_GROUP_COUNT; i++) {
		xt_spinlock_init_with_autoname(NULL, &rl->rl_groups[i].lg_lock);
		rl->rl_groups[i].lg_wait_queue = NULL;
		rl->rl_groups[i].lg_list_size = 0;
		rl->rl_groups[i].lg_list_in_use = 0;
		rl->rl_groups[i].lg_list = NULL;
	}
729
	rl->valid = 1;
Paul McCullagh's avatar
Paul McCullagh committed
730 731 732
	return OK;
}

733
void xt_exit_row_locks(XTRowLocksPtr rl)
Paul McCullagh's avatar
Paul McCullagh committed
734
{
735 736 737
	if (!rl->valid)
		return;

Paul McCullagh's avatar
Paul McCullagh committed
738 739 740 741 742 743 744 745 746 747
	for (int i=0; i<XT_ROW_LOCK_GROUP_COUNT; i++) {
		xt_spinlock_free(NULL, &rl->rl_groups[i].lg_lock);
		rl->rl_groups[i].lg_wait_queue = NULL;
		rl->rl_groups[i].lg_list_size = 0;
		rl->rl_groups[i].lg_list_in_use = 0;
		if (rl->rl_groups[i].lg_list) {
			xt_free_ns(rl->rl_groups[i].lg_list);
			rl->rl_groups[i].lg_list = NULL;
		}
	}
748
	rl->valid = 0;
Paul McCullagh's avatar
Paul McCullagh committed
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 860 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 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
}

/*
 * -----------------------------------------------------------------------
 * ROW LOCKS, HASH BASED
 */
#else // XT_USE_LIST_BASED_ROW_LOCKS

void XTRowLockList::old_xt_remove_all_locks(struct XTDatabase *db, xtThreadID thd_id)
{
#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "remove all locks\n");
#endif
	if (!bl_count)
		return;

	int					pgroup;
	xtTableID			ptab_id;
	XTPermRowLockPtr	plock;
	XTOpenTablePtr		pot = NULL;

	plock = (XTPermRowLockPtr) &bl_data[bl_count * bl_item_size];
	for (u_int i=0; i<bl_count; i++) {
		plock--;
		pgroup = plock->pr_group;
		ptab_id = plock->pr_tab_id;
		if (pot) {
			if (pot->ot_table->tab_id == ptab_id)
				goto remove_lock;
			xt_db_return_table_to_pool_ns(pot);
			pot = NULL;
		}

		if (!xt_db_open_pool_table_ns(&pot, db, ptab_id)) {
			/* Should not happen, but just in case, we just don't
			 * remove the lock. We will probably end up with a deadlock
			 * somewhere.
			 */
			xt_log_and_clear_exception_ns();
			goto skip_remove_lock;
		}
		if (!pot)
			/* Can happen of the table has been dropped: */
			goto skip_remove_lock;

		remove_lock:
#ifdef XT_TRACE_LOCKS
		xt_ttracef(xt_get_self(), "remove lock group=%d\n", pgroup);
#endif
		pot->ot_table->tab_locks.tab_row_locks[pgroup] = NULL;
		pot->ot_table->tab_locks.tab_lock_perm[pgroup] = 0;
		skip_remove_lock:;
	}
	bl_count = 0;

	if (pot)
		xt_db_return_table_to_pool_ns(pot);
}

/* Try to lock a row.
 * This function returns:
 * XT_NO_LOCK on success.
 * XT_TEMP_LOCK if there is a temporary lock on the row.
 * XT_PERM_LOCK if there is a permanent lock in the row.
 *
 * If there is a lock on this row, the transaction ID of the
 * locker is also returned.
 *
 * The caller must wait if the row is locked. If the lock is
 * permanent, then the caller must wait for the transaction to
 * terminate. If the lock is temporary, then the caller must
 * wait for the transaction to signal that the lock has been
 * released.
 */
int XTRowLocks::old_xt_set_temp_lock(XTOpenTablePtr ot, xtRowID row, xtXactID *xn_id, XTRowLockListPtr lock_list)
{
	int				group;
	XTXactDataPtr	xact, my_xact;

	if (ot->ot_temp_row_lock) {
		/* Check if we don't already have this temp lock: */
		if (ot->ot_temp_row_lock == row) {
			gl->lw_curr_lock = XT_NO_LOCK;
			return XT_NO_LOCK;
		}

		xt_make_lock_permanent(ot, lock_list);
	}

	my_xact = ot->ot_thread->st_xact_data;
	group = row % XT_ROW_LOCK_COUNT;
	if ((xact = tab_row_locks[group])) {
		if (xact == my_xact)
			return XT_NO_LOCK;
		*xn_id = xact->xd_start_xn_id;
		return tab_lock_perm[group] ? XT_PERM_LOCK : XT_TEMP_LOCK;
	}

	tab_row_locks[row % XT_ROW_LOCK_COUNT] = my_xact;

#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "set temp lock %d group=%d for %s\n", (int) row, (int) row % XT_ROW_LOCK_COUNT, ot->ot_thread->t_name);
#endif
	ot->ot_temp_row_lock = row;
	return XT_NO_LOCK;
}

/* Just check if there is a lock on the row.
 * This function returns:
 * XT_NO_LOCK if there is no lock.
 * XT_TEMP_LOCK if there is a temporary lock on the row.
 * XT_PERM_LOCK if a lock is a permanent lock in the row.
 */
int XTRowLocks::old_xt_is_locked(struct XTOpenTable *ot, xtRowID row, xtXactID *xn_id)
{
	int				group;
	XTXactDataPtr	xact;

	group = row % XT_ROW_LOCK_COUNT;
	if ((xact = tab_row_locks[group])) {
		if (xact == ot->ot_thread->st_xact_data)
			return XT_NO_LOCK;
		*xn_id = xact->xd_start_xn_id;
		if (tab_lock_perm[group])
			return XT_PERM_LOCK;
		return XT_TEMP_LOCK;
	}
	return XT_NO_LOCK;
}

void XTRowLocks::old_xt_remove_temp_lock(XTOpenTablePtr ot)
{
	int				group;
	XTXactDataPtr	xact, my_xact;

	if (!ot->ot_temp_row_lock)
		return;

	my_xact = ot->ot_thread->st_xact_data;
	group = ot->ot_temp_row_lock % XT_ROW_LOCK_COUNT;
#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "remove temp lock %d group=%d\n", (int) ot->ot_temp_row_lock, (int) ot->ot_temp_row_lock % XT_ROW_LOCK_COUNT);
#endif
	ot->ot_temp_row_lock = 0;
	if ((xact = tab_row_locks[group])) {
		if (xact == my_xact)
			tab_row_locks[group] = NULL;
	}

	if (ot->ot_table->tab_db->db_xn_wait_count)
		xt_xn_wakeup_transactions(ot->ot_table->tab_db, ot->ot_thread);
}

xtBool XTRowLocks::old_xt_make_lock_permanent(XTOpenTablePtr ot, XTRowLockListPtr lock_list)
{
	int group;

	if (!ot->ot_temp_row_lock)
		return OK;

#ifdef XT_TRACE_LOCKS
	xt_ttracef(xt_get_self(), "make lock perm %d group=%d\n", (int) ot->ot_temp_row_lock, (int) ot->ot_temp_row_lock % XT_ROW_LOCK_COUNT);
#endif
	/* Check if the lock is already permanent: */
	group = ot->ot_temp_row_lock % XT_ROW_LOCK_COUNT;
	if (!tab_lock_perm[group]) {
		XTPermRowLockRec plock;

		plock.pr_tab_id = ot->ot_table->tab_id;
		plock.pr_group = group;
		if (!xt_bl_append(NULL, lock_list, &plock)) {
			xt_remove_temp_lock(ot);
			return FAILED;
		}
		tab_lock_perm[group] = 1;
	}

	ot->ot_temp_row_lock = 0;
	return OK;
}

/* Release this lock, and all locks gained after this lock
 * on this table.
 *
 * The locks are only released temporarily. The will be regained
 * below using regain locks.
 *
 * Returns:
 * XT_NO_LOCK if no lock is released.
 * XT_PERM_LOCK if a lock is released.
 *
 * Note that only permanent locks can be released in this way.
 * So if the thread has a temporary lock, it will first be made
 * permanent.
 *
 * {RELEASING-LOCKS}
 * The idea of the releasing locks comes from the fact that each
 * lock, locks a group of records.
 * So if T1 has a lock (e.g. when doing SELECT FOR UPDATE),
 * and then encounters an updated record x
 * from T2, and it must wait for T2, it firsts releases the
 * lock, just in case T2 tries to gain a lock on another
 * record y in the same group, which will cause it to
 * wait on T1.
 *
 * However, there are several problems with releasing
 * locks.
 * - It can cause a "live-lock", where another transation
 * keeps getting in before.
 * - It may not solve the problem in all cases because
 * the SELECT FOR UPDATE has locked other record groups
 * before it encountered record x.
 * - Further problems occur when locks are granted by
 * callback:
 * T1 waits for T2, because it has a lock on record x
 * T2 releases the lock because it must wait for T3
 * T1 is granted the lock (but does not know about this yet)
 * T2 tries to regain lock (after T3 quits) and
 * must wait for T1 - DEADLOCK
 *
 * In general, it does not make sense to release locks
 * when it can be granted again by a callback.
 *
 * TODO: 2 possible solutions:
 * - Do not lock groups, lock rows.
 *   UPDATE INTENSION ROW LOCK
 * - Use multiple lock types:
 *   UPDATE INTENSION LOCK (required first)
 *   SHARED UPDATE LOCK (used by INSERT or DELETE)
 *   EXCLUSIVE UPDATE LOCK (used by SELECT FOR UPDATE)
 *
 * Temporary solution. Do not release any locks.
int XTRowLocks::xt_release_locks(struct XTOpenTable *ot, xtRowID row, XTRowLockListPtr lock_list)
 */ 

/*
 * Regain a lock previously held. This function regains locks
 * released by xt_release_locks().
 *
 * It will return lock_type and xn_id if the row is locked, and therefore
 * regain cannot continue. In this case, the caller must wait.
 * It returns XT_NO_LOCK if there are no more locks to be regained.
 *
 * Locks are always regained in the order in which they were originally
 * taken.
xtBool XTRowLocks::xt_regain_locks(struct XTOpenTable *ot, int *lock_type, xtXactID *xn_id, XTRowLockListPtr lock_list)
 */

xtBool old_xt_init_row_locks(XTRowLocksPtr rl)
{
	memset(rl->tab_lock_perm, 0, XT_ROW_LOCK_COUNT);
	memset(rl->tab_row_locks, 0, XT_ROW_LOCK_COUNT * sizeof(XTXactDataPtr));
	return OK;
}

1004
void old_xt_exit_row_locks(XTRowLocksPtr XT_UNUSED(rl))
Paul McCullagh's avatar
Paul McCullagh committed
1005 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
{
}

#endif // XT_USE_LIST_BASED_ROW_LOCKS

xtPublic xtBool xt_init_row_lock_list(XTRowLockListPtr lock_list)
{
	lock_list->bl_item_size = sizeof(XTPermRowLockRec);
	lock_list->bl_size = 0;
	lock_list->bl_count = 0;
	lock_list->bl_data = NULL;
	return OK;
}

xtPublic void xt_exit_row_lock_list(XTRowLockListPtr lock_list)
{
	xt_bl_set_size(NULL, lock_list, 0);
}

/*
 * -----------------------------------------------------------------------
 * SPECIAL EXCLUSIVE/SHARED (XS) LOCK
 */

#ifdef XT_THREAD_LOCK_INFO
xtPublic void xt_rwmutex_init(struct XTThread *self, XTRWMutexPtr xsl, const char *n)
#else
xtPublic void xt_rwmutex_init(XTThreadPtr self, XTRWMutexPtr xsl)
#endif
{
#ifdef DEBUG
	xsl->xs_lock_thread = 0;
	xsl->xs_inited = 12345;
#endif
	xt_init_mutex_with_autoname(self, &xsl->xs_lock);
	xt_init_cond(self, &xsl->xs_cond);
1041
	xt_atomic_set4(&xsl->xs_state, 0);
Paul McCullagh's avatar
Paul McCullagh committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
	xsl->xs_xlocker = 0;
	/* Must be aligned! */
	ASSERT(xt_thr_maximum_threads == xt_align_size(xt_thr_maximum_threads, XT_XS_LOCK_ALIGN));
	xsl->x.xs_rlock = (xtWord1 *) xt_calloc(self, xt_thr_maximum_threads);
#ifdef XT_THREAD_LOCK_INFO
	xsl->xs_name = n;
	xt_thread_lock_info_init(&xsl->xs_lock_info, xsl);
#endif
}

xtPublic void xt_rwmutex_free(XTThreadPtr self, XTRWMutexPtr xsl)
{
#ifdef DEBUG
	ASSERT(!xsl->xs_lock_thread);
	ASSERT(xsl->xs_inited == 12345);
	xsl->xs_inited = 0;
#endif
	if (xsl->x.xs_rlock)
		xt_free(self, (void *) xsl->x.xs_rlock);
	xt_free_mutex(&xsl->xs_lock);
	xt_free_cond(&xsl->xs_cond);
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&xsl->xs_lock_info);
#endif
}

xtPublic xtBool xt_rwmutex_xlock(XTRWMutexPtr xsl, xtThreadID thd_id)
{
#ifdef DEBUG
	ASSERT_NS(xsl->xs_inited == 12345);
#endif
	ASSERT_NS(xt_get_self()->t_id == thd_id);
	xt_lock_mutex_ns(&xsl->xs_lock);
	ASSERT_NS(xsl->x.xs_rlock[thd_id] == XT_NO_LOCK);
	
	/* Wait for exclusive locker: */
	while (xsl->xs_xlocker) {
		if (!xt_timed_wait_cond_ns(&xsl->xs_cond, &xsl->xs_lock, 10000)) {
			xt_unlock_mutex_ns(&xsl->xs_lock);
			return FAILED;
		}
	}

	/* I am the locker (set state before locker!): */
1086
	xt_atomic_set4(&xsl->xs_state, 0);
Paul McCullagh's avatar
Paul McCullagh committed
1087 1088 1089 1090 1091 1092 1093 1094 1095
	xsl->xs_xlocker = thd_id;

	/* Wait for all the read lockers: */
	while (xsl->xs_state < xt_thr_current_max_threads) {
		while (xsl->x.xs_rlock[xsl->xs_state]) {
			/* {RACE-WR_MUTEX}
			 * Just in case of this, we keep the wait time down!
			 */
			if (!xt_timed_wait_cond_ns(&xsl->xs_cond, &xsl->xs_lock, 10)) {
1096
				xt_atomic_set4(&xsl->xs_state, 0);
Paul McCullagh's avatar
Paul McCullagh committed
1097 1098 1099 1100 1101 1102 1103 1104
				xsl->xs_xlocker = 0;
				xt_unlock_mutex_ns(&xsl->xs_lock);
				return FAILED;
			}
		}
		/* State can be incremented in parallel by a reader
		 * thread!
		 */
1105
		xt_atomic_set4(&xsl->xs_state, xsl->xs_state + 1);
Paul McCullagh's avatar
Paul McCullagh committed
1106 1107 1108
	}

	/* I have waited for all: */
1109
	xt_atomic_set4(&xsl->xs_state, xt_thr_maximum_threads);
Paul McCullagh's avatar
Paul McCullagh committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_add_owner(&xsl->xs_lock_info);
#endif

	return OK;
}

xtPublic xtBool xt_rwmutex_slock(XTRWMutexPtr xsl, xtThreadID thd_id)
{
#ifdef DEBUG
	ASSERT_NS(xsl->xs_inited == 12345);
#endif
	ASSERT_NS(xt_get_self()->t_id == thd_id);

1125
	xt_atomic_inc1(&xsl->x.xs_rlock[thd_id]);
Paul McCullagh's avatar
Paul McCullagh committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

	if (xsl->x.xs_rlock[thd_id] > 1)
		return OK;

	/* Check if there could be an X locker: */
	if (xsl->xs_xlocker) {
		/* There is an X locker.
		 * If xs_state < thd_id then the X locker will wait for me.
		 * So I should not wait!
		 */
		if (xsl->xs_state >= thd_id) {
			/* If xsl->xs_state >= thd_id, then the locker has already
			 * checked me, and I will have to wait.
			 *
			 * Otherwise, xs_state <= thd_id, which means the
			 * X locker has not checked me, and will still wait for me (or 
			 * is already waiting for me). In this case, I will have to
			 * take the mutex to make sure exactly how far he
			 * is with the checking.
			 */
			xt_lock_mutex_ns(&xsl->xs_lock);
			while (xsl->xs_state > thd_id && xsl->xs_xlocker) {
				if (!xt_timed_wait_cond_ns(&xsl->xs_cond, &xsl->xs_lock, 10000)) {
					xt_unlock_mutex_ns(&xsl->xs_lock);
					xsl->x.xs_rlock[thd_id]--;
					return FAILED;
				}
			}
			xt_unlock_mutex_ns(&xsl->xs_lock);
		}
	}

	/* There is no exclusive locker, so we have the read lock: */
	ASSERT_NS(xsl->xs_state != xt_thr_maximum_threads);
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_add_owner(&xsl->xs_lock_info);
#endif
	return OK;
}

xtPublic xtBool xt_rwmutex_unlock(XTRWMutexPtr xsl, xtThreadID thd_id)
{
#ifdef DEBUG
	ASSERT_NS(xsl->xs_inited == 12345);
#endif
	ASSERT_NS(xt_get_self()->t_id == thd_id);
	if (xsl->xs_xlocker == thd_id) {
		/* I have an X lock. */
		ASSERT_NS(xsl->x.xs_rlock[thd_id] == XT_NO_LOCK);
		ASSERT_NS(xsl->xs_state == xt_thr_maximum_threads);
1176
		xt_atomic_set4(&xsl->xs_state, 0);
Paul McCullagh's avatar
Paul McCullagh committed
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 1213 1214 1215 1216 1217 1218
		xsl->xs_xlocker = 0;
		xt_unlock_mutex_ns(&xsl->xs_lock);
		/* Wake up any other X or shared lockers: */
		if (!xt_broadcast_cond_ns(&xsl->xs_cond))
			return FAILED;
	}
	else {
		/* I have a shared lock: */
		ASSERT_NS(xsl->x.xs_rlock[thd_id] > 0);
		ASSERT_NS(xsl->xs_state != xt_thr_maximum_threads); /* TODO: PMC - HOW can this fail?! - but it does? */
		if (xsl->x.xs_rlock[thd_id] > 1)
			xsl->x.xs_rlock[thd_id]--;
		else {
			/* {RACE-WR_MUTEX}.
			 * A BUG FIX:
			 *
			 * Previously I was checking "xsl->xs_xlocker" after,
			 * descrementing the READ lock.
			 *
			 * This resulted in a race condition that could cause the
			 * unlocking reader to hang in xt_lock_mutex_ns().
			 * This was because the X locker, grabbed the mutex (xs_lock)
			 * but did not wait for the reader.
			 *
			 * The result was that the reader had to wait in UNLOCK
			 * until the X locker did an unlock!
			 *
			 * This only became obvious when it caused a deadlock (because
			 * the reader was waiting for the locker, which it should not
			 * have been, of course).
			 */
			if (xsl->xs_xlocker) {
				xt_lock_mutex_ns(&xsl->xs_lock);
				if (xsl->xs_xlocker && xsl->xs_state == thd_id) {
					/* If the X locker is waiting for me,
					 * then allow him to continue. 
					 */
					if (!xt_broadcast_cond_ns(&xsl->xs_cond)) {
						xt_unlock_mutex_ns(&xsl->xs_lock);
						return FAILED;
					}
				}
1219
				xt_atomic_dec1(&xsl->x.xs_rlock[thd_id]);
Paul McCullagh's avatar
Paul McCullagh committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
				xt_unlock_mutex_ns(&xsl->xs_lock);
			}
			else
				/* {RACE-WR_MUTEX}
				 * There is a race condition between the check above, and the
				 * the decrement here.
				 *
				 * However, if I check xsl->xs_xlocker afterwards, and then
				 * try to get the lock xs_lock, I could hand for the duration
				 * of the X lock.
				 */
1231
				xt_atomic_dec1(&xsl->x.xs_rlock[thd_id]);
Paul McCullagh's avatar
Paul McCullagh committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
		}
	}
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_release_owner(&xsl->xs_lock_info);
#endif
	return OK;
}

/*
 * -----------------------------------------------------------------------
 * SPIN LOCK
 */

#ifdef XT_THREAD_LOCK_INFO
1246
xtPublic void xt_spinlock_init(XTThreadPtr self, XTSpinLockPtr spl, const char *n)
Paul McCullagh's avatar
Paul McCullagh committed
1247
#else
1248
xtPublic void xt_spinlock_init(XTThreadPtr self, XTSpinLockPtr spl)
Paul McCullagh's avatar
Paul McCullagh committed
1249 1250
#endif
{
1251
	(void) self;
Paul McCullagh's avatar
Paul McCullagh committed
1252
	spl->spl_lock = 0;
1253
#ifdef XT_NO_ATOMICS
1254
	xt_init_mutex_with_autoname(self, &spl->spl_mutex);
Paul McCullagh's avatar
Paul McCullagh committed
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
#endif
#ifdef DEBUG
	spl->spl_locker = 0;
#endif
#ifdef XT_THREAD_LOCK_INFO
	spl->spl_name = n;
	xt_thread_lock_info_init(&spl->spl_lock_info, spl);
#endif
}

1265
xtPublic void xt_spinlock_free(XTThreadPtr XT_UNUSED(self), XTSpinLockPtr spl)
Paul McCullagh's avatar
Paul McCullagh committed
1266
{
1267 1268
	(void) spl;
#ifdef XT_NO_ATOMICS
Paul McCullagh's avatar
Paul McCullagh committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
	xt_free_mutex(&spl->spl_mutex);
#endif
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&spl->spl_lock_info);
#endif
}

xtPublic xtBool xt_spinlock_spin(XTSpinLockPtr spl)
{
	volatile xtWord4	*lck = &spl->spl_lock;

	for (;;) {
		for (int i=0; i<10; i++) {
			/* Check the lock variable: */
			if (!*lck) {
				/* Try to get the lock: */
				if (!xt_spinlock_set(spl))
1286
					goto done_ok;
Paul McCullagh's avatar
Paul McCullagh committed
1287 1288 1289 1290 1291 1292 1293
			}
		}

		/* Go to "sleep" */
		xt_critical_wait();
	}

1294
	done_ok:
Paul McCullagh's avatar
Paul McCullagh committed
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 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
	return OK;
}

#ifdef DEBUG
xtPublic void xt_spinlock_set_thread(XTSpinLockPtr spl)
{
	spl->spl_locker = xt_get_self();
}
#endif

/*
 * -----------------------------------------------------------------------
 * FAST LOCK
 */

#ifdef XT_THREAD_LOCK_INFO
xtPublic void xt_fastlock_init(XTThreadPtr self, XTFastLockPtr fal, const char *n)
#else
xtPublic void xt_fastlock_init(XTThreadPtr self, XTFastLockPtr fal)
#endif
{
	xt_spinlock_init_with_autoname(self, &fal->fal_spinlock);
	xt_spinlock_init_with_autoname(self, &fal->fal_wait_lock);
	for (u_int i=0; i<XT_FAST_LOCK_MAX_WAIT; i++)
		fal->fal_wait_list[i] = NULL;
	fal->fal_wait_count = 0;
	fal->fal_wait_wakeup = 0;
	fal->fal_wait_alloc = 0;
#ifdef XT_THREAD_LOCK_INFO
	fal->fal_name = n;
	xt_thread_lock_info_init(&fal->fal_lock_info, fal);
#endif
}

xtPublic void xt_fastlock_free(XTThreadPtr self, XTFastLockPtr fal)
{
	xt_spinlock_free(self, &fal->fal_spinlock);
	xt_spinlock_free(self, &fal->fal_wait_lock);
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&fal->fal_lock_info);
#endif
}

xtPublic xtBool xt_fastlock_spin(XTFastLockPtr fal, XTThreadPtr thread)
{
	volatile xtWord4	*lck = &fal->fal_spinlock.spl_lock;

	do {
		for (int i=0; i<10; i++) {
			/* Check the lock variable: */
			if (!*lck) {
				/* Try to get the lock: */
				if (!xt_spinlock_set(&fal->fal_spinlock)) {
					fal->fal_locker = thread;
					return OK;
				}
			}
		}

		for (int i=0; i<10; i++) {
			xt_critical_wait();
			if (!*lck) {
				/* Try to get the lock: */
				if (!xt_spinlock_set(&fal->fal_spinlock)) {
					fal->fal_locker = thread;
					return OK;
				}
			}
		}

		/* Wait for a wakeup */
		xt_spinlock_lock(&fal->fal_wait_lock);
		if (fal->fal_wait_count == XT_FAST_LOCK_MAX_WAIT) {
			xt_register_ulxterr(XT_REG_CONTEXT, XT_ERR_TOO_MANY_WAITERS, (u_long) XT_FAST_LOCK_MAX_WAIT+1);
			xt_spinlock_unlock(&fal->fal_wait_lock);
			return FAILED;
		}
		while (fal->fal_wait_list[fal->fal_wait_alloc])
			fal->fal_wait_alloc = (fal->fal_wait_alloc + 1) % XT_FAST_LOCK_MAX_WAIT;
		fal->fal_wait_list[fal->fal_wait_alloc] = thread;
		fal->fal_wait_alloc = (fal->fal_wait_alloc + 1) % XT_FAST_LOCK_MAX_WAIT;
		fal->fal_wait_count++;
		xt_lock_thread(thread);
		xt_spinlock_unlock(&fal->fal_wait_lock);
		if (!xt_wait_thread(thread)) {
			xt_unlock_thread(thread);
			if (fal->fal_locker == thread)
				xt_fastlock_unlock(fal, thread);
			return FAILED;
		}
		xt_unlock_thread(thread);
	} while (fal->fal_locker != thread);
	return OK;
}

/* Wake up one of the waiters. */
xtPublic void xt_fastlock_wakeup(XTFastLockPtr fal)
{
	xt_spinlock_lock(&fal->fal_wait_lock);
	if (fal->fal_wait_count) {
		XTThreadPtr thread;

		/* Find a waiting thread, and give it the exclusive lock: */
		while (!fal->fal_wait_list[fal->fal_wait_wakeup])
			fal->fal_wait_wakeup = (fal->fal_wait_wakeup + 1) % XT_FAST_LOCK_MAX_WAIT;
		thread = fal->fal_wait_list[fal->fal_wait_wakeup];
		fal->fal_wait_list[fal->fal_wait_wakeup] = NULL;
		fal->fal_wait_wakeup = (fal->fal_wait_wakeup + 1) % XT_FAST_LOCK_MAX_WAIT;
		fal->fal_wait_count--;
		fal->fal_locker = thread;

		xt_lock_thread(thread);
		xt_spinlock_unlock(&fal->fal_wait_lock);
		xt_signal_thread(thread);
		xt_unlock_thread(thread);
	}
	else {
		xt_spinlock_unlock(&fal->fal_wait_lock);
		fal->fal_locker = NULL;
		xt_spinlock_reset(&fal->fal_spinlock);
	}
}

/*
 * -----------------------------------------------------------------------
 * READ/WRITE SPIN LOCK
1421 1422
 *
 * An extremely genius very fast read/write lock based on atomics!
Paul McCullagh's avatar
Paul McCullagh committed
1423 1424 1425
 */

#ifdef XT_THREAD_LOCK_INFO
1426
xtPublic void xt_spinxslock_init(struct XTThread *XT_UNUSED(self), XTSpinXSLockPtr sxs, const char *name)
Paul McCullagh's avatar
Paul McCullagh committed
1427
#else
1428
xtPublic void xt_spinxslock_init(struct XTThread *XT_UNUSED(self), XTSpinXSLockPtr sxs)
Paul McCullagh's avatar
Paul McCullagh committed
1429 1430
#endif
{
1431
	sxs->sxs_xlocked = 0;
1432
	sxs->sxs_xwaiter = 0;
1433 1434 1435 1436 1437
	sxs->sxs_rlock_count = 0;
	sxs->sxs_wait_count = 0;
#ifdef DEBUG
	sxs->sxs_locker = 0;
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1438
#ifdef XT_THREAD_LOCK_INFO
1439 1440
	sxs->sxs_name = name;
	xt_thread_lock_info_init(&sxs->sxs_lock_info, sxs);
Paul McCullagh's avatar
Paul McCullagh committed
1441 1442 1443
#endif
}

1444
xtPublic void xt_spinxslock_free(struct XTThread *XT_UNUSED(self), XTSpinXSLockPtr sxs)
Paul McCullagh's avatar
Paul McCullagh committed
1445 1446
{
#ifdef XT_THREAD_LOCK_INFO
1447 1448 1449
	xt_thread_lock_info_free(&sxs->sxs_lock_info);
#else
	(void) sxs;
Paul McCullagh's avatar
Paul McCullagh committed
1450 1451 1452
#endif
}

Paul McCullagh's avatar
Paul McCullagh committed
1453
xtPublic xtBool xt_spinxslock_xlock(XTSpinXSLockPtr sxs, xtBool try_lock, xtThreadID XT_NDEBUG_UNUSED(thd_id))
Paul McCullagh's avatar
Paul McCullagh committed
1454
{
1455
	register xtWord2 set;
Paul McCullagh's avatar
Paul McCullagh committed
1456

1457 1458 1459 1460 1461
	/* Wait for exclusive locker: */
	for (;;) {
		set = xt_atomic_tas2(&sxs->sxs_xlocked, 1);
		if (!set)
			break;
Paul McCullagh's avatar
Paul McCullagh committed
1462 1463
		if (try_lock)
			return FALSE;
1464
		xt_yield();
Paul McCullagh's avatar
Paul McCullagh committed
1465 1466
	}

1467 1468 1469
#ifdef DEBUG
	sxs->sxs_locker = thd_id;
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1470

Paul McCullagh's avatar
Paul McCullagh committed
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	/* Wait for all the readers to wait! */
	while (sxs->sxs_wait_count < sxs->sxs_rlock_count) {
		sxs->sxs_xwaiter = 1;
		xt_yield(); //*
		/* This should not be required, because there is only one thread
		 * accessing this value. However, the lock fails if this
		 * is not done with an atomic op.
		 *
		 * This is because threads on other processors have the
		 * value in processor cache. So they do not
		 * notice that the value has been set to zero.
		 * They think it is still 1 and march through
		 * the barrier (sxs->sxs_xwaiter < sxs->sxs_xlocked) below.
		 *
		 * In the meantime, this X locker has gone on thinking
		 * all is OK.
		 */
		xt_atomic_tas2(&sxs->sxs_xwaiter, 0);
	}
Paul McCullagh's avatar
Paul McCullagh committed
1490 1491

#ifdef XT_THREAD_LOCK_INFO
1492
	xt_thread_lock_info_add_owner(&sxs->sxs_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1493 1494 1495 1496
#endif
	return OK;
}

1497
xtPublic xtBool xt_spinxslock_slock(XTSpinXSLockPtr sxs)
Paul McCullagh's avatar
Paul McCullagh committed
1498
{
1499 1500
	xt_atomic_inc2(&sxs->sxs_rlock_count);

Paul McCullagh's avatar
Paul McCullagh committed
1501 1502
	/* Wait as long as the locker is not waiting: */
	while (sxs->sxs_xwaiter < sxs->sxs_xlocked) {
1503
		xt_atomic_inc2(&sxs->sxs_wait_count);
Paul McCullagh's avatar
Paul McCullagh committed
1504
		while (sxs->sxs_xwaiter < sxs->sxs_xlocked) {
1505
			xt_yield();
Paul McCullagh's avatar
Paul McCullagh committed
1506
		}
1507
		xt_atomic_dec2(&sxs->sxs_wait_count);
Paul McCullagh's avatar
Paul McCullagh committed
1508 1509 1510
	}

#ifdef XT_THREAD_LOCK_INFO
1511
	xt_thread_lock_info_add_owner(&sxs->sxs_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1512 1513 1514 1515
#endif
	return OK;
}

1516
xtPublic xtBool xt_spinxslock_unlock(XTSpinXSLockPtr sxs, xtBool xlocked)
Paul McCullagh's avatar
Paul McCullagh committed
1517
{
1518 1519
	if (xlocked) {
#ifdef DEBUG
Paul McCullagh's avatar
Paul McCullagh committed
1520
		ASSERT_NS(sxs->sxs_locker && sxs->sxs_xlocked);
1521 1522 1523
		sxs->sxs_locker = 0;
#endif
		sxs->sxs_xlocked = 0;
Paul McCullagh's avatar
Paul McCullagh committed
1524
	}
Paul McCullagh's avatar
Paul McCullagh committed
1525 1526 1527 1528
	else {
#ifdef DEBUG
		ASSERT_NS(sxs->sxs_rlock_count > 0);
#endif
1529
		xt_atomic_dec2(&sxs->sxs_rlock_count);
Paul McCullagh's avatar
Paul McCullagh committed
1530
	}
Paul McCullagh's avatar
Paul McCullagh committed
1531 1532

#ifdef XT_THREAD_LOCK_INFO
1533
	xt_thread_lock_info_release_owner(&sxs->sxs_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
#endif
	return OK;
}

/*
 * -----------------------------------------------------------------------
 * FAST READ/WRITE LOCK (BASED ON FAST MUTEX)
 */

#ifdef XT_THREAD_LOCK_INFO
1544
xtPublic void xt_xsmutex_init(struct XTThread *self, XTXSMutexLockPtr xsm, const char *name)
Paul McCullagh's avatar
Paul McCullagh committed
1545
#else
1546
xtPublic void xt_xsmutex_init(struct XTThread *self, XTXSMutexLockPtr xsm)
Paul McCullagh's avatar
Paul McCullagh committed
1547 1548
#endif
{
1549 1550 1551 1552 1553 1554 1555 1556 1557
	xt_init_mutex_with_autoname(self, &xsm->xsm_lock);
	xt_init_cond(self, &xsm->xsm_cond);
	xt_init_cond(self, &xsm->xsm_cond_2);
	xsm->xsm_xlocker = 0;
	xsm->xsm_rlock_count = 0;
	xsm->xsm_wait_count = 0;
#ifdef DEBUG
	xsm->xsm_locker = 0;
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1558
#ifdef XT_THREAD_LOCK_INFO
1559 1560
	xsm->xsm_name = name;
	xt_thread_lock_info_init(&xsm->xsm_lock_info, xsm);
Paul McCullagh's avatar
Paul McCullagh committed
1561 1562 1563
#endif
}

1564
xtPublic void xt_xsmutex_free(struct XTThread *XT_UNUSED(self), XTXSMutexLockPtr xsm)
Paul McCullagh's avatar
Paul McCullagh committed
1565
{
1566 1567 1568
	xt_free_mutex(&xsm->xsm_lock);
	xt_free_cond(&xsm->xsm_cond);
	xt_free_cond(&xsm->xsm_cond_2);
Paul McCullagh's avatar
Paul McCullagh committed
1569
#ifdef XT_THREAD_LOCK_INFO
1570
	xt_thread_lock_info_free(&xsm->xsm_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1571 1572 1573
#endif
}

1574
xtPublic xtBool xt_xsmutex_xlock(XTXSMutexLockPtr xsm, xtThreadID thd_id)
Paul McCullagh's avatar
Paul McCullagh committed
1575
{
1576
	xt_lock_mutex_ns(&xsm->xsm_lock);
Paul McCullagh's avatar
Paul McCullagh committed
1577

1578 1579 1580 1581 1582
	/* Wait for exclusive locker: */
	while (xsm->xsm_xlocker) {
		if (!xt_timed_wait_cond_ns(&xsm->xsm_cond, &xsm->xsm_lock, 10000)) {
			xt_unlock_mutex_ns(&xsm->xsm_lock);
			return FAILED;
Paul McCullagh's avatar
Paul McCullagh committed
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
	/* GOTCHA: You would think this is not necessary...
	 * But is does not always work, if a normal insert is used.
	 * The reason is, I guess, on MMP the assignment is not
	 * always immediately visible to other processors, because they
	 * have old versions of this variable in there cache.
	 *
	 * But this is required, because the locking mechanism is based
	 * on:
	 * Locker: sets xlocker, tests rlock_count
	 * Reader: incs rlock_count, tests xlocker
	 *
	 * The test, in both cases, may not read stale values.
	 * volatile does not help, because this just turns compiler
	 * optimisations off.
	 */
	xt_atomic_set4(&xsm->xsm_xlocker, thd_id);

	/* Wait for all the reader to wait! */
	while (xsm->xsm_wait_count < xsm->xsm_rlock_count) {
		/* {RACE-WR_MUTEX} Here as well: */
		if (!xt_timed_wait_cond_ns(&xsm->xsm_cond, &xsm->xsm_lock, 100)) {
			xsm->xsm_xlocker = 0;
			xt_unlock_mutex_ns(&xsm->xsm_lock);
			return FAILED;
		}
	}
Paul McCullagh's avatar
Paul McCullagh committed
1612 1613

#ifdef XT_THREAD_LOCK_INFO
1614
	xt_thread_lock_info_add_owner(&xsm->xsm_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1615 1616 1617 1618
#endif
	return OK;
}

1619
xtPublic xtBool xt_xsmutex_slock(XTXSMutexLockPtr xsm, xtThreadID XT_UNUSED(thd_id))
Paul McCullagh's avatar
Paul McCullagh committed
1620
{
1621
	xt_atomic_inc2(&xsm->xsm_rlock_count);
Paul McCullagh's avatar
Paul McCullagh committed
1622 1623

	/* Check if there could be an X locker: */
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
	if (xsm->xsm_xlocker) {
		/* I am waiting... */
		xt_lock_mutex_ns(&xsm->xsm_lock);
		xsm->xsm_wait_count++;
		/* Wake up the xlocker: */
		if (xsm->xsm_xlocker && xsm->xsm_wait_count == xsm->xsm_rlock_count) {
			if (!xt_broadcast_cond_ns(&xsm->xsm_cond)) {
				xsm->xsm_wait_count--;
				xt_unlock_mutex_ns(&xsm->xsm_lock);
				return FAILED;
			}
		}
		while (xsm->xsm_xlocker) {
			if (!xt_timed_wait_cond_ns(&xsm->xsm_cond_2, &xsm->xsm_lock, 10000)) {
				xsm->xsm_wait_count--;
				xt_unlock_mutex_ns(&xsm->xsm_lock);
				return FAILED;
Paul McCullagh's avatar
Paul McCullagh committed
1641 1642
			}
		}
1643 1644
		xsm->xsm_wait_count--;
		xt_unlock_mutex_ns(&xsm->xsm_lock);
Paul McCullagh's avatar
Paul McCullagh committed
1645 1646 1647
	}

#ifdef XT_THREAD_LOCK_INFO
1648
	xt_thread_lock_info_add_owner(&xsm->xsm_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1649 1650 1651 1652
#endif
	return OK;
}

1653
xtPublic xtBool xt_xsmutex_unlock(XTXSMutexLockPtr xsm, xtThreadID thd_id)
Paul McCullagh's avatar
Paul McCullagh committed
1654
{
1655 1656 1657 1658 1659 1660
	if (xsm->xsm_xlocker == thd_id) {
		xsm->xsm_xlocker = 0;
		if (xsm->xsm_wait_count) {
			if (!xt_broadcast_cond_ns(&xsm->xsm_cond_2)) {
				xt_unlock_mutex_ns(&xsm->xsm_lock);
				return FAILED;
Paul McCullagh's avatar
Paul McCullagh committed
1661 1662
			}
		}
1663 1664 1665 1666 1667 1668 1669 1670
		else {
			/* Wake up any other X or shared lockers: */
			if (!xt_broadcast_cond_ns(&xsm->xsm_cond)) {
				xt_unlock_mutex_ns(&xsm->xsm_lock);
				return FAILED;
			}
		}
		xt_unlock_mutex_ns(&xsm->xsm_lock);
Paul McCullagh's avatar
Paul McCullagh committed
1671 1672
	}
	else {
1673 1674 1675 1676 1677 1678 1679
		/* Taking the advice from {RACE-WR_MUTEX} I do the decrement
		 * after I have a lock!
		 */
		if (xsm->xsm_xlocker) {
			xt_lock_mutex_ns(&xsm->xsm_lock);
			xt_atomic_dec2(&xsm->xsm_rlock_count);
			if (xsm->xsm_xlocker && xsm->xsm_wait_count == xsm->xsm_rlock_count) {
Paul McCullagh's avatar
Paul McCullagh committed
1680 1681 1682
				/* If the X locker is waiting for me,
				 * then allow him to continue. 
				 */
1683 1684 1685 1686
				if (!xt_broadcast_cond_ns(&xsm->xsm_cond)) {
					xt_unlock_mutex_ns(&xsm->xsm_lock);
					return FAILED;
				}
Paul McCullagh's avatar
Paul McCullagh committed
1687
			}
1688
			xt_unlock_mutex_ns(&xsm->xsm_lock);
Paul McCullagh's avatar
Paul McCullagh committed
1689
		}
1690 1691
		else
			xt_atomic_dec2(&xsm->xsm_rlock_count);
Paul McCullagh's avatar
Paul McCullagh committed
1692 1693 1694
	}

#ifdef XT_THREAD_LOCK_INFO
1695
	xt_thread_lock_info_release_owner(&xsm->xsm_lock_info);
Paul McCullagh's avatar
Paul McCullagh committed
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
#endif
	return OK;
}

/*
 * -----------------------------------------------------------------------
 * ATOMIC READ/WRITE LOCK (BASED ON ATOMIC OPERATIONS)
 */

#ifdef XT_THREAD_LOCK_INFO
1706
xtPublic void xt_atomicrwlock_init(struct XTThread *XT_UNUSED(self), XTAtomicRWLockPtr arw, const char *n)
Paul McCullagh's avatar
Paul McCullagh committed
1707
#else
1708
xtPublic void xt_atomicrwlock_init(struct XTThread *XT_UNUSED(self), XTAtomicRWLockPtr arw)
Paul McCullagh's avatar
Paul McCullagh committed
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
#endif
{
	arw->arw_reader_count = 0;
	arw->arw_xlock_set = 0;
#ifdef XT_THREAD_LOCK_INFO
	arw->arw_name = n;
	xt_thread_lock_info_init(&arw->arw_lock_info, arw);
#endif
}

1719 1720 1721
#ifdef XT_THREAD_LOCK_INFO
xtPublic void xt_atomicrwlock_free(struct XTThread *, XTAtomicRWLockPtr arw)
#else
Paul McCullagh's avatar
Paul McCullagh committed
1722
xtPublic void xt_atomicrwlock_free(struct XTThread *, XTAtomicRWLockPtr XT_UNUSED(arw))
1723
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1724 1725 1726 1727 1728 1729
{
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&arw->arw_lock_info);
#endif
}

Paul McCullagh's avatar
Paul McCullagh committed
1730
xtPublic xtBool xt_atomicrwlock_xlock(XTAtomicRWLockPtr arw, xtBool try_lock, xtThreadID XT_NDEBUG_UNUSED(thr_id))
Paul McCullagh's avatar
Paul McCullagh committed
1731 1732 1733 1734 1735 1736 1737 1738
{
	register xtWord2 set;

	/* First get an exclusive lock: */
	for (;;) {
		set = xt_atomic_tas2(&arw->arw_xlock_set, 1);
		if (!set)
			break;
Paul McCullagh's avatar
Paul McCullagh committed
1739 1740
		if (try_lock)
			return FALSE;
Paul McCullagh's avatar
Paul McCullagh committed
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
		xt_yield();
	}

	/* Wait for the remaining readers: */
	while (arw->arw_reader_count)
		xt_yield();

#ifdef DEBUG
	arw->arw_locker = thr_id;
#endif

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_add_owner(&arw->arw_lock_info);
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1755
	return TRUE;
Paul McCullagh's avatar
Paul McCullagh committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
}

xtPublic xtBool xt_atomicrwlock_slock(XTAtomicRWLockPtr arw)
{
	register xtWord2 set;

	/* First get an exclusive lock: */
	for (;;) {
		set = xt_atomic_tas2(&arw->arw_xlock_set, 1);
		if (!set)
			break;
		xt_yield();
	}

	/* Add a reader: */
	xt_atomic_inc2(&arw->arw_reader_count);

	/* Release the xlock: */
	arw->arw_xlock_set = 0;

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_add_owner(&arw->arw_lock_info);
#endif
	return OK;
}

xtPublic xtBool xt_atomicrwlock_unlock(XTAtomicRWLockPtr arw, xtBool xlocked)
{
1784 1785 1786 1787
	if (xlocked) {
#ifdef DEBUG
		arw->arw_locker = 0;
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1788
		arw->arw_xlock_set = 0;
1789
	}
Paul McCullagh's avatar
Paul McCullagh committed
1790 1791 1792 1793 1794 1795
	else
		xt_atomic_dec2(&arw->arw_reader_count);

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_release_owner(&arw->arw_lock_info);
#endif
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832

	return OK;
}

/*
 * -----------------------------------------------------------------------
 * "SKEW" ATOMITC READ/WRITE LOCK (BASED ON ATOMIC OPERATIONS)
 *
 * This lock type favors writers. It only works if the proportion of readers
 * to writer is high.
 */

#ifdef XT_THREAD_LOCK_INFO
xtPublic void xt_skewrwlock_init(struct XTThread *XT_UNUSED(self), XTSkewRWLockPtr srw, const char *n)
#else
xtPublic void xt_skewrwlock_init(struct XTThread *XT_UNUSED(self), XTSkewRWLockPtr srw)
#endif
{
	srw->srw_reader_count = 0;
	srw->srw_xlock_set = 0;
#ifdef XT_THREAD_LOCK_INFO
	srw->srw_name = n;
	xt_thread_lock_info_init(&srw->srw_lock_info, srw);
#endif
}

#ifdef XT_THREAD_LOCK_INFO
xtPublic void xt_skewrwlock_free(struct XTThread *, XTSkewRWLockPtr srw)
#else
xtPublic void xt_skewrwlock_free(struct XTThread *, XTSkewRWLockPtr XT_UNUSED(srw))
#endif
{
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&srw->srw_lock_info);
#endif
}

Paul McCullagh's avatar
Paul McCullagh committed
1833
xtPublic xtBool xt_skewrwlock_xlock(XTSkewRWLockPtr srw, xtBool try_lock, xtThreadID XT_NDEBUG_UNUSED(thr_id))
1834 1835 1836 1837 1838 1839 1840 1841
{
	register xtWord2 set;

	/* First get an exclusive lock: */
	for (;;) {
		set = xt_atomic_tas2(&srw->srw_xlock_set, 1);
		if (!set)
			break;
Paul McCullagh's avatar
Paul McCullagh committed
1842 1843
		if (try_lock)
			return FALSE;
1844 1845 1846 1847 1848 1849 1850
		xt_yield();
	}

	/* Wait for the remaining readers: */
	while (srw->srw_reader_count)
		xt_yield();

Paul McCullagh's avatar
Paul McCullagh committed
1851
#ifdef DEBUG
1852 1853 1854 1855 1856 1857
	srw->srw_locker = thr_id;
#endif

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_add_owner(&srw->srw_lock_info);
#endif
Paul McCullagh's avatar
Paul McCullagh committed
1858
	return TRUE;
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
}

xtPublic xtBool xt_skewrwlock_slock(XTSkewRWLockPtr srw)
{
	/* Wait for an exclusive lock: */
	retry:
	for (;;) {
		if (!srw->srw_xlock_set)
			break;
		xt_yield();
	}

	/* Add a reader: */
	xt_atomic_inc2(&srw->srw_reader_count);

	/* Check for xlock again: */
	if (srw->srw_xlock_set) {
		xt_atomic_dec2(&srw->srw_reader_count);
		goto retry;
	}

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_add_owner(&srw->srw_lock_info);
#endif
	return OK;
}

xtPublic xtBool xt_skewrwlock_unlock(XTSkewRWLockPtr srw, xtBool xlocked)
{
	if (xlocked)
		srw->srw_xlock_set = 0;
	else
		xt_atomic_dec2(&srw->srw_reader_count);

#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_release_owner(&srw->srw_lock_info);
#endif
#ifdef DEBUG
	srw->srw_locker = 0;
Paul McCullagh's avatar
Paul McCullagh committed
1898 1899 1900 1901 1902
#endif

	return OK;
}

Paul McCullagh's avatar
Paul McCullagh committed
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 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 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 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
/*
 * -----------------------------------------------------------------------
 * RECURSIVE R/W LOCK (allows X lockers to lock again)
 */

#ifdef XT_THREAD_LOCK_INFO
void xt_recursivemutex_init(XTThreadPtr self, XTRecursiveMutexPtr rm, const char *name)
{
	rm->rm_locker = NULL;
	rm->rm_lock_count = 0;
	xt_init_mutex(self, &rm->rm_mutex, name);
}
#else
xtPublic void xt_recursivemutex_init(XTThreadPtr self, XTRecursiveMutexPtr rm)
{
	rm->rm_locker = NULL;
	rm->rm_lock_count = 0;
	xt_init_mutex(self, &rm->rm_mutex);
}
#endif

xtPublic void xt_recursivemutex_free(XTRecursiveMutexPtr rm)
{
	xt_free_mutex(&rm->rm_mutex);
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&rm->rm_lock_info);
#endif
}

xtPublic void xt_recursivemutex_lock(XTThreadPtr self, XTRecursiveMutexPtr rm)
{
	if (self != rm->rm_locker) {
		xt_lock_mutex(self, &rm->rm_mutex);
		rm->rm_locker = self;
	}
	rm->rm_lock_count++;
}

xtPublic void xt_recursivemutex_unlock(XTThreadPtr self, XTRecursiveMutexPtr rm)
{
	ASSERT(self == rm->rm_locker);
	ASSERT(rm->rm_lock_count > 0);
	rm->rm_lock_count--;
	if (!rm->rm_lock_count) {
		rm->rm_locker = NULL;
		xt_unlock_mutex(self, &rm->rm_mutex);
	}
}

/*
 * -----------------------------------------------------------------------
 * RECURSIVE MUTEX (allows lockers to lock again)
 */

#ifdef XT_THREAD_LOCK_INFO
void xt_recurrwlock_init(struct XTThread *self, XTRecurRWLockPtr rrw, const char *name)
{
	rrw->rrw_locker = NULL;
	rrw->rrw_lock_count = 0;
	xt_init_rwlock(self, &rrw->rrw_lock, name);
}
#else
void xt_recurrwlock_init(struct XTThread *self, XTRecurRWLockPtr rrw)
{
	rrw->rrw_locker = NULL;
	rrw->rrw_lock_count = 0;
	xt_init_rwlock(self, &rrw->rrw_lock);
}
#endif

void xt_recurrwlock_free(XTRecurRWLockPtr rrw)
{
	xt_free_rwlock(&rrw->rrw_lock);
#ifdef XT_THREAD_LOCK_INFO
	xt_thread_lock_info_free(&rrw->rrw_lock_info);
#endif
}

void xt_recurrwlock_xlock(struct XTThread *self, XTRecurRWLockPtr rrw)
{
	if (self != rrw->rrw_locker) {
		xt_xlock_rwlock(self, &rrw->rrw_lock);
		rrw->rrw_locker = self;
	}
	rrw->rrw_lock_count++;
}

void xt_recurrwlock_slock(struct XTThread *self, XTRecurRWLockPtr rrw)
{
	xt_slock_rwlock(self, &rrw->rrw_lock);
}

void xt_recurrwlock_slock_ns(XTRecurRWLockPtr rrw)
{
	xt_slock_rwlock_ns(&rrw->rrw_lock);
}

void xt_recurrwlock_unxlock(struct XTThread *self, XTRecurRWLockPtr rrw)
{
	ASSERT(self == rrw->rrw_locker);
	ASSERT(rrw->rrw_lock_count > 0);
	rrw->rrw_lock_count--;
	if (!rrw->rrw_lock_count) {
		rrw->rrw_locker = NULL;
		xt_unlock_rwlock(self, &rrw->rrw_lock);
	}
}

void xt_recurrwlock_unslock(struct XTThread *self, XTRecurRWLockPtr rrw)
{
	xt_unlock_rwlock(self, &rrw->rrw_lock);
}

void xt_recurrwlock_unslock_ns(XTRecurRWLockPtr rrw)
{
	xt_unlock_rwlock_ns(&rrw->rrw_lock);
}

Paul McCullagh's avatar
Paul McCullagh committed
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
/*
 * -----------------------------------------------------------------------
 * UNIT TESTS
 */

#define JOB_MEMCPY			1
#define JOB_SLEEP			2
#define JOB_PRINT			3
#define JOB_INCREMENT		4
#define JOB_SNOOZE			5
2031
#define JOB_DOUBLE_INC		6
Paul McCullagh's avatar
Paul McCullagh committed
2032 2033 2034

#define LOCK_PTHREAD_RW		1
#define LOCK_PTHREAD_MUTEX	2
2035
#define LOCK_RWMUTEX		3
Paul McCullagh's avatar
Paul McCullagh committed
2036 2037
#define LOCK_SPINLOCK		4
#define LOCK_FASTLOCK		5
2038 2039
#define LOCK_SPINXSLOCK		6
#define LOCK_XSMUTEX		7
Paul McCullagh's avatar
Paul McCullagh committed
2040
#define LOCK_ATOMICRWLOCK	8
2041
#define LOCK_SKEWRWLOCK		9
Paul McCullagh's avatar
Paul McCullagh committed
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052

typedef struct XSLockTest {
	u_int			xs_interations;
	xtBool			xs_which_lock;
	xtBool			xs_which_job;
	xtBool			xs_debug_print;
	XTRWMutexRec	xs_lock;
	xt_rwlock_type	xs_plock;
	XTSpinLockRec	xs_spinlock;
	xt_mutex_type	xs_mutex;
	XTFastLockRec	xs_fastlock;
2053 2054
	XTSpinXSLockRec	xs_spinrwlock;
	XTXSMutexRec	xs_fastrwlock;
Paul McCullagh's avatar
Paul McCullagh committed
2055
	XTAtomicRWLockRec xs_atomicrwlock;
2056
	XTSkewRWLockRec xs_skewrwlock;
Paul McCullagh's avatar
Paul McCullagh committed
2057 2058 2059 2060
	int				xs_progress;
	xtWord4			xs_inc;
} XSLockTestRec, *XSLockTestPtr;

2061
static void lck_free_thread_data(XTThreadPtr XT_UNUSED(self), void *XT_UNUSED(data))
Paul McCullagh's avatar
Paul McCullagh committed
2062 2063 2064
{
}

2065
static void lck_do_job(XTThreadPtr self, int job, XSLockTestPtr data, xtBool reader)
Paul McCullagh's avatar
Paul McCullagh committed
2066
{
Michael Widenius's avatar
Michael Widenius committed
2067
	char b1[1024], b2[1024];
Paul McCullagh's avatar
Paul McCullagh committed
2068 2069 2070

	switch (job) {
		case JOB_MEMCPY:
Michael Widenius's avatar
Michael Widenius committed
2071 2072
                        memset(b1, 0, sizeof(b1));
                        memset(b2, 1, sizeof(b2));
Paul McCullagh's avatar
Paul McCullagh committed
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
			data->xs_inc++;
			break;
		case JOB_SLEEP:
			xt_sleep_milli_second(1);
			data->xs_inc++;
			break;
		case JOB_PRINT:
			printf("- %s got lock\n", self->t_name);
			xt_sleep_milli_second(10);
			data->xs_inc++;
			break;
		case JOB_INCREMENT:
			data->xs_inc++;
			break;
		case JOB_SNOOZE:
			xt_sleep_milli_second(10);
			data->xs_inc++;
			break;
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
		case JOB_DOUBLE_INC:
			if (reader) {
				if ((data->xs_inc & 1) != 0)
					printf("Noooo!\n");
			}
			else {
				data->xs_inc++;
				data->xs_inc++;
			}
			break;
Paul McCullagh's avatar
Paul McCullagh committed
2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
	}
}

#if 0
static void *lck_run_dumper(XTThreadPtr self)
{
	int state = 0;

	while (state != 1) {
		sleep(1);
		if (state == 2) {
			xt_dump_trace();
			state = 0;
		}
	}
}
#endif

static void *lck_run_reader(XTThreadPtr self)
{
	XSLockTestRec	*data = (XSLockTestRec *) self->t_data;

	if (data->xs_debug_print)
		printf("- %s start\n", self->t_name);
	for (u_int i=0; i<data->xs_interations; i++) {
		if (data->xs_progress && ((i+1) % data->xs_progress) == 0)
			printf("- %s %d\n", self->t_name, i+1);
		if (data->xs_which_lock == LOCK_PTHREAD_RW) {
			xt_slock_rwlock_ns(&data->xs_plock);
2130
			lck_do_job(self, data->xs_which_job, data, TRUE);
Paul McCullagh's avatar
Paul McCullagh committed
2131 2132
			xt_unlock_rwlock_ns(&data->xs_plock);
		}
2133
		else if (data->xs_which_lock == LOCK_RWMUTEX) {
Paul McCullagh's avatar
Paul McCullagh committed
2134
			xt_rwmutex_slock(&data->xs_lock, self->t_id);
2135
			lck_do_job(self, data->xs_which_job, data, TRUE);
Paul McCullagh's avatar
Paul McCullagh committed
2136 2137
			xt_rwmutex_unlock(&data->xs_lock, self->t_id);
		}
2138 2139 2140 2141
		else if (data->xs_which_lock == LOCK_SPINXSLOCK) {
			xt_spinxslock_slock(&data->xs_spinrwlock);
			lck_do_job(self, data->xs_which_job, data, TRUE);
			xt_spinxslock_unlock(&data->xs_spinrwlock, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2142
		}
2143 2144 2145 2146
		else if (data->xs_which_lock == LOCK_XSMUTEX) {
			xt_xsmutex_slock(&data->xs_fastrwlock, self->t_id);
			lck_do_job(self, data->xs_which_job, data, TRUE);
			xt_xsmutex_unlock(&data->xs_fastrwlock, self->t_id);
Paul McCullagh's avatar
Paul McCullagh committed
2147 2148 2149
		}
		else if (data->xs_which_lock == LOCK_ATOMICRWLOCK) {
			xt_atomicrwlock_slock(&data->xs_atomicrwlock);
2150
			lck_do_job(self, data->xs_which_job, data, TRUE);
Paul McCullagh's avatar
Paul McCullagh committed
2151 2152
			xt_atomicrwlock_unlock(&data->xs_atomicrwlock, FALSE);
		}
2153 2154 2155 2156 2157
		else if (data->xs_which_lock == LOCK_SKEWRWLOCK) {
			xt_skewrwlock_slock(&data->xs_skewrwlock);
			lck_do_job(self, data->xs_which_job, data, TRUE);
			xt_skewrwlock_unlock(&data->xs_skewrwlock, FALSE);
		}
Paul McCullagh's avatar
Paul McCullagh committed
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
		else
			ASSERT(FALSE);
	}
	if (data->xs_debug_print)
		printf("- %s stop\n", self->t_name);
	return NULL;
}

static void *lck_run_writer(XTThreadPtr self)
{
	XSLockTestRec	*data = (XSLockTestRec *) self->t_data;

	if (data->xs_debug_print)
		printf("- %s start\n", self->t_name);
	for (u_int i=0; i<data->xs_interations; i++) {
		if (data->xs_progress && ((i+1) % data->xs_progress) == 0)
			printf("- %s %d\n", self->t_name, i+1);
		if (data->xs_which_lock == LOCK_PTHREAD_RW) {
			xt_xlock_rwlock_ns(&data->xs_plock);
2177
			lck_do_job(self, data->xs_which_job, data, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2178 2179
			xt_unlock_rwlock_ns(&data->xs_plock);
		}
2180
		else if (data->xs_which_lock == LOCK_RWMUTEX) {
Paul McCullagh's avatar
Paul McCullagh committed
2181
			xt_rwmutex_xlock(&data->xs_lock, self->t_id);
2182
			lck_do_job(self, data->xs_which_job, data, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2183 2184
			xt_rwmutex_unlock(&data->xs_lock, self->t_id);
		}
2185
		else if (data->xs_which_lock == LOCK_SPINXSLOCK) {
Paul McCullagh's avatar
Paul McCullagh committed
2186
			xt_spinxslock_xlock(&data->xs_spinrwlock, FALSE, self->t_id);
2187 2188
			lck_do_job(self, data->xs_which_job, data, FALSE);
			xt_spinxslock_unlock(&data->xs_spinrwlock, TRUE);
Paul McCullagh's avatar
Paul McCullagh committed
2189
		}
2190 2191 2192 2193
		else if (data->xs_which_lock == LOCK_XSMUTEX) {
			xt_xsmutex_xlock(&data->xs_fastrwlock, self->t_id);
			lck_do_job(self, data->xs_which_job, data, FALSE);
			xt_xsmutex_unlock(&data->xs_fastrwlock, self->t_id);
Paul McCullagh's avatar
Paul McCullagh committed
2194 2195
		}
		else if (data->xs_which_lock == LOCK_ATOMICRWLOCK) {
Paul McCullagh's avatar
Paul McCullagh committed
2196
			xt_atomicrwlock_xlock(&data->xs_atomicrwlock, FALSE, self->t_id);
2197
			lck_do_job(self, data->xs_which_job, data, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2198 2199
			xt_atomicrwlock_unlock(&data->xs_atomicrwlock, TRUE);
		}
2200
		else if (data->xs_which_lock == LOCK_SKEWRWLOCK) {
Paul McCullagh's avatar
Paul McCullagh committed
2201
			xt_skewrwlock_xlock(&data->xs_skewrwlock, FALSE, self->t_id);
2202 2203 2204
			lck_do_job(self, data->xs_which_job, data, FALSE);
			xt_skewrwlock_unlock(&data->xs_skewrwlock, TRUE);
		}
Paul McCullagh's avatar
Paul McCullagh committed
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
		else
			ASSERT(FALSE);
	}
	if (data->xs_debug_print)
		printf("- %s stop\n", self->t_name);
	return NULL;
}

static void lck_print_test(XSLockTestRec *data)
{
	switch (data->xs_which_lock) {
		case LOCK_PTHREAD_RW:
			printf("pthread read/write");
			break;
		case LOCK_PTHREAD_MUTEX:
			printf("pthread mutex");
			break;
2222
		case LOCK_RWMUTEX:
Paul McCullagh's avatar
Paul McCullagh committed
2223 2224 2225 2226 2227 2228 2229 2230
			printf("fast read/write mutex");
			break;
		case LOCK_SPINLOCK:
			printf("spin mutex");
			break;
		case LOCK_FASTLOCK:
			printf("fast mutex");
			break;
2231
		case LOCK_SPINXSLOCK:
Paul McCullagh's avatar
Paul McCullagh committed
2232 2233
			printf("spin read/write lock");
			break;
2234 2235
		case LOCK_XSMUTEX:
			printf("fast x/s mutex");
Paul McCullagh's avatar
Paul McCullagh committed
2236 2237 2238 2239
			break;
		case LOCK_ATOMICRWLOCK:
			printf("atomic read/write lock");
			break;
2240 2241 2242
		case LOCK_SKEWRWLOCK:
			printf("skew read/write lock");
			break;
Paul McCullagh's avatar
Paul McCullagh committed
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
	}

	switch (data->xs_which_job) {
		case JOB_MEMCPY:
			printf(" MEMCPY 2K");
			break;
		case JOB_SLEEP:
			printf(" SLEEP 1/1000s");
			break;
		case JOB_PRINT:
			printf(" PRINT DEBUG");
			break;
		case JOB_INCREMENT:
			printf(" INCREMENT");
			break;
		case JOB_SNOOZE:
			printf(" SLEEP 1/100s");
			break;
	}
	
	printf(" %d interations", data->xs_interations);
}

static void *lck_run_mutex_locker(XTThreadPtr self)
{
	XSLockTestRec *data = (XSLockTestRec *) self->t_data;

	if (data->xs_debug_print)
		printf("- %s start\n", self->t_name);
	for (u_int i=0; i<data->xs_interations; i++) {
		if (data->xs_progress && ((i+1) % data->xs_progress) == 0)
			printf("- %s %d\n", self->t_name, i+1);
		if (data->xs_which_lock == LOCK_PTHREAD_MUTEX) {
			xt_lock_mutex_ns(&data->xs_mutex);
2277
			lck_do_job(self, data->xs_which_job, data, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2278 2279 2280 2281
			xt_unlock_mutex_ns(&data->xs_mutex);
		}
		else if (data->xs_which_lock == LOCK_SPINLOCK) {
			xt_spinlock_lock(&data->xs_spinlock);
2282
			lck_do_job(self, data->xs_which_job, data, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2283 2284 2285 2286
			xt_spinlock_unlock(&data->xs_spinlock);
		}
		else if (data->xs_which_lock == LOCK_FASTLOCK) {
			xt_fastlock_lock(&data->xs_fastlock, self);
2287
			lck_do_job(self, data->xs_which_job, data, FALSE);
Paul McCullagh's avatar
Paul McCullagh committed
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
			xt_fastlock_unlock(&data->xs_fastlock, self);
		}
		else
			ASSERT(FALSE);
	}
	if (data->xs_debug_print)
		printf("- %s stop\n", self->t_name);
	return NULL;
}

typedef struct LockThread {
	xtThreadID		id;
	XTThreadPtr		ptr;
} LockThreadRec, *LockThreadPtr;

static void lck_reader_writer_test(XTThreadPtr self, XSLockTestRec *data, int reader_cnt, int writer_cnt)
{
	xtWord8			start;
	LockThreadPtr	threads;
	int				thread_cnt = reader_cnt + writer_cnt;
	char			buffer[40];

	//XTThreadPtr dumper = xt_create_daemon(self, "DUMPER");
	//xt_run_thread(self, dumper, lck_run_dumper);

	printf("READ/WRITE TEST: ");
	lck_print_test(data);
	printf(", %d readers, %d writers\n", reader_cnt, writer_cnt);
	threads = (LockThreadPtr) xt_malloc(self, thread_cnt * sizeof(LockThreadRec));

	for (int i=0; i<thread_cnt; i++) {
		sprintf(buffer, "%s%d", i < reader_cnt ? "READER-" : "WRITER-", i+1);
		threads[i].ptr = xt_create_daemon(self, buffer);
		threads[i].id = threads[i].ptr->t_id;
		xt_set_thread_data(threads[i].ptr, data, lck_free_thread_data);
	}

	start = xt_trace_clock();
	for (int i=0; i<reader_cnt; i++)
		xt_run_thread(self, threads[i].ptr, lck_run_reader);
	for (int i=reader_cnt; i<thread_cnt; i++)
		xt_run_thread(self, threads[i].ptr, lck_run_writer);

	for (int i=0; i<thread_cnt; i++)
		xt_wait_for_thread(threads[i].id, TRUE);
	printf("----- %d reader, %d writer time=%s\n", reader_cnt, writer_cnt, xt_trace_clock_diff(buffer, start));

	xt_free(self, threads);
	printf("TEST RESULT = %d\n", data->xs_inc);

	//xt_wait_for_thread(dumper, TRUE);
}

static void lck_mutex_lock_test(XTThreadPtr self, XSLockTestRec *data, int thread_cnt)
{
	xtWord8			start;
	LockThreadPtr	threads;
	char			buffer[40];

	printf("LOCK MUTEX TEST: ");
	lck_print_test(data);
	printf(", %d threads\n", thread_cnt);
	threads = (LockThreadPtr) xt_malloc(self, thread_cnt * sizeof(LockThreadRec));

	for (int i=0; i<thread_cnt; i++) {
		sprintf(buffer, "THREAD%d", i+1);
		threads[i].ptr = xt_create_daemon(self, buffer);
		threads[i].id = threads[i].ptr->t_id;
		xt_set_thread_data(threads[i].ptr, data, lck_free_thread_data);
	}

	start = xt_trace_clock();
	for (int i=0; i<thread_cnt; i++)
		xt_run_thread(self, threads[i].ptr, lck_run_mutex_locker);

	for (int i=0; i<thread_cnt; i++)
		xt_wait_for_thread(threads[i].id, TRUE);
	printf("----- %d threads time=%s\n", thread_cnt, xt_trace_clock_diff(buffer, start));

	xt_free(self, threads);
	printf("TEST RESULT = %d\n", data->xs_inc);
}

xtPublic void xt_unit_test_read_write_locks(XTThreadPtr self)
{
	XSLockTestRec	data;

	memset(&data, 0, sizeof(data));

	printf("TEST: xt_unit_test_read_write_locks\n");
2378 2379 2380
	printf("size of XTXSMutexRec = %d\n", (int) sizeof(XTXSMutexRec));
	printf("size of pthread_cond_t = %d\n", (int) sizeof(pthread_cond_t));
	printf("size of pthread_mutex_t = %d\n", (int) sizeof(pthread_mutex_t));
Paul McCullagh's avatar
Paul McCullagh committed
2381 2382
	xt_rwmutex_init_with_autoname(self, &data.xs_lock);
	xt_init_rwlock_with_autoname(self, &data.xs_plock);
2383 2384
	xt_spinxslock_init_with_autoname(self, &data.xs_spinrwlock);
	xt_xsmutex_init_with_autoname(self, &data.xs_fastrwlock);
Paul McCullagh's avatar
Paul McCullagh committed
2385
	xt_atomicrwlock_init_with_autoname(self, &data.xs_atomicrwlock);
2386
	xt_skewrwlock_init_with_autoname(self, &data.xs_skewrwlock);
Paul McCullagh's avatar
Paul McCullagh committed
2387 2388 2389

	/**
	data.xs_interations = 10;
2390
	data.xs_which_lock = LOCK_RWMUTEX; // LOCK_PTHREAD_RW, LOCK_RWMUTEX, LOCK_SPINXSLOCK, LOCK_XSMUTEX
Paul McCullagh's avatar
Paul McCullagh committed
2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
	data.xs_which_job = JOB_PRINT;
	data.xs_debug_print = TRUE;
	data.xs_progress = 0;
	lck_reader_writer_test(self, &data, 4, 0);
	lck_reader_writer_test(self, &data, 0, 2);
	lck_reader_writer_test(self, &data, 1, 1);
	lck_reader_writer_test(self, &data, 4, 2);
	**/

	/**
	data.xs_interations = 4000;
2402
	data.xs_which_lock = LOCK_RWMUTEX; // LOCK_PTHREAD_RW, LOCK_RWMUTEX, LOCK_SPINXSLOCK, LOCK_XSMUTEX
Paul McCullagh's avatar
Paul McCullagh committed
2403 2404 2405 2406 2407 2408 2409 2410 2411
	data.xs_which_job = JOB_SLEEP;
	data.xs_debug_print = TRUE;
	data.xs_progress = 200;
	lck_reader_writer_test(self, &data, 4, 0);
	lck_reader_writer_test(self, &data, 0, 2);
	lck_reader_writer_test(self, &data, 1, 1);
	lck_reader_writer_test(self, &data, 4, 2);
	**/

2412
	// LOCK_PTHREAD_RW, LOCK_RWMUTEX, LOCK_SPINXSLOCK, LOCK_XSMUTEX, LOCK_ATOMICRWLOCK, LOCK_SKEWRWLOCK
Paul McCullagh's avatar
Paul McCullagh committed
2413
	/**/
2414 2415 2416
	data.xs_interations = 100000;
	data.xs_which_lock = LOCK_XSMUTEX;
	data.xs_which_job = JOB_DOUBLE_INC; // JOB_INCREMENT, JOB_DOUBLE_INC
Paul McCullagh's avatar
Paul McCullagh committed
2417 2418 2419
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
	lck_reader_writer_test(self, &data, 10, 0);
2420 2421 2422 2423 2424
	data.xs_which_lock = LOCK_XSMUTEX;
	lck_reader_writer_test(self, &data, 10, 0);
	//lck_reader_writer_test(self, &data, 0, 5);
	//lck_reader_writer_test(self, &data, 10, 0);
	//lck_reader_writer_test(self, &data, 10, 5);
Paul McCullagh's avatar
Paul McCullagh committed
2425 2426
	/**/

2427
	/**/
Paul McCullagh's avatar
Paul McCullagh committed
2428
	data.xs_interations = 10000;
2429
	data.xs_which_lock = LOCK_XSMUTEX;
Paul McCullagh's avatar
Paul McCullagh committed
2430 2431 2432
	data.xs_which_job = JOB_MEMCPY;
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
2433 2434 2435 2436 2437 2438 2439
	lck_reader_writer_test(self, &data, 10, 0);
	data.xs_which_lock = LOCK_XSMUTEX;
	lck_reader_writer_test(self, &data, 10, 0);
	//lck_reader_writer_test(self, &data, 0, 5);
	//lck_reader_writer_test(self, &data, 10, 0);
	//lck_reader_writer_test(self, &data, 10, 5);
	/**/
Paul McCullagh's avatar
Paul McCullagh committed
2440

2441
	/**/
Paul McCullagh's avatar
Paul McCullagh committed
2442
	data.xs_interations = 1000;
2443 2444
	data.xs_which_lock = LOCK_XSMUTEX;
	data.xs_which_job = JOB_SLEEP; // JOB_SLEEP, JOB_SNOOZE
Paul McCullagh's avatar
Paul McCullagh committed
2445 2446
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
2447 2448 2449 2450
	lck_reader_writer_test(self, &data, 10, 0);
	data.xs_which_lock = LOCK_XSMUTEX;
	lck_reader_writer_test(self, &data, 10, 0);
	/**/
Paul McCullagh's avatar
Paul McCullagh committed
2451 2452 2453

	xt_rwmutex_free(self, &data.xs_lock);
	xt_free_rwlock(&data.xs_plock);
2454 2455 2456 2457
	xt_spinxslock_free(self, &data.xs_spinrwlock);
	xt_xsmutex_free(self, &data.xs_fastrwlock);
	xt_atomicrwlock_free(self, &data.xs_atomicrwlock);
	xt_skewrwlock_free(self, &data.xs_skewrwlock);
Paul McCullagh's avatar
Paul McCullagh committed
2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
}

xtPublic void xt_unit_test_mutex_locks(XTThreadPtr self)
{
	XSLockTestRec	data;

	memset(&data, 0, sizeof(data));

	printf("TEST: xt_unit_test_mutex_locks\n");
	xt_spinlock_init_with_autoname(self, &data.xs_spinlock);
	xt_fastlock_init_with_autoname(self, &data.xs_fastlock);
	xt_init_mutex_with_autoname(self, &data.xs_mutex);

	/**/
	data.xs_interations = 10;
	data.xs_which_lock = LOCK_SPINLOCK; // LOCK_SPINLOCK, LOCK_PTHREAD_MUTEX, LOCK_FASTLOCK
	data.xs_which_job = JOB_PRINT;
	data.xs_debug_print = TRUE;
	data.xs_progress = 0;
	data.xs_inc = 0;
	lck_mutex_lock_test(self, &data, 2);
	/**/

	/**/
	data.xs_interations = 100000;
	data.xs_which_lock = LOCK_SPINLOCK; // LOCK_SPINLOCK, LOCK_PTHREAD_MUTEX, LOCK_FASTLOCK
	data.xs_which_job = JOB_INCREMENT;
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
	data.xs_inc = 0;
	lck_mutex_lock_test(self, &data, 10);
	/**/

	/**/
	data.xs_interations = 10000;
	data.xs_which_lock = LOCK_SPINLOCK; // LOCK_SPINLOCK, LOCK_PTHREAD_MUTEX, LOCK_FASTLOCK
	data.xs_which_job = JOB_MEMCPY;
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
	data.xs_inc = 0;
	lck_mutex_lock_test(self, &data, 10);
	/**/

	/**/
	data.xs_interations = 1000;
	data.xs_which_lock = LOCK_FASTLOCK; // LOCK_SPINLOCK, LOCK_PTHREAD_MUTEX, LOCK_FASTLOCK
	data.xs_which_job = JOB_SLEEP;
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
	data.xs_inc = 0;
	lck_mutex_lock_test(self, &data, 10);
	/**/

	/**/
	data.xs_interations = 100;
	data.xs_which_lock = LOCK_FASTLOCK; // LOCK_SPINLOCK, LOCK_PTHREAD_MUTEX, LOCK_FASTLOCK
	data.xs_which_job = JOB_SNOOZE;
	data.xs_debug_print = FALSE;
	data.xs_progress = 0;
	data.xs_inc = 0;
	lck_mutex_lock_test(self, &data, 10);
	/**/

	xt_spinlock_free(self, &data.xs_spinlock);
	xt_fastlock_free(self, &data.xs_fastlock);
	xt_free_mutex(&data.xs_mutex);
}

xtPublic void xt_unit_test_create_threads(XTThreadPtr self)
{
	XTThreadPtr		threads[10];

	printf("TEST: xt_unit_test_create_threads\n");
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* Create some threads: */
	threads[0] = xt_create_daemon(self, "test0");
	printf("thread = %d\n", threads[0]->t_id);
	threads[1] = xt_create_daemon(self, "test1");
	printf("thread = %d\n", threads[1]->t_id);
	threads[2] = xt_create_daemon(self, "test2");
	printf("thread = %d\n", threads[2]->t_id);
	threads[3] = xt_create_daemon(self, "test3");
	printf("thread = %d\n", threads[3]->t_id);
	threads[4] = xt_create_daemon(self, "test4");
	printf("thread = %d\n", threads[4]->t_id);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* Max stays the same: */
	xt_free_thread(threads[3]);
	xt_free_thread(threads[2]);
	xt_free_thread(threads[1]);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* Fill in the gaps: */
	threads[1] = xt_create_daemon(self, "test1");
	printf("thread = %d\n", threads[1]->t_id);
	threads[2] = xt_create_daemon(self, "test2");
	printf("thread = %d\n", threads[2]->t_id);
	threads[3] = xt_create_daemon(self, "test3");
	printf("thread = %d\n", threads[3]->t_id);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* And add one: */
	threads[5] = xt_create_daemon(self, "test5");
	printf("thread = %d\n", threads[5]->t_id);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* Max stays the same: */
	xt_free_thread(threads[3]);
	xt_free_thread(threads[2]);
	xt_free_thread(threads[1]);
	xt_free_thread(threads[4]);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* Recalculate the max: */
	xt_free_thread(threads[5]);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	/* Fill in the gaps: */
	threads[1] = xt_create_daemon(self, "test1");
	printf("thread = %d\n", threads[1]->t_id);
	threads[2] = xt_create_daemon(self, "test2");
	printf("thread = %d\n", threads[2]->t_id);
	threads[3] = xt_create_daemon(self, "test3");
	printf("thread = %d\n", threads[3]->t_id);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);

	xt_free_thread(threads[3]);
	xt_free_thread(threads[2]);
	xt_free_thread(threads[1]);
	xt_free_thread(threads[0]);
	printf("current max threads = %d, in use = %d\n", xt_thr_current_max_threads, xt_thr_current_thread_count);
}

#ifdef UNUSED_CODE
int XTRowLocks::xt_release_locks(struct XTOpenTable *ot, xtRowID row, XTRowLockListPtr lock_list)
{
	if (ot->ot_temp_row_lock)
		xt_make_lock_permanent(ot, lock_list);

	if (!lock_list->bl_count)
		return XT_NO_LOCK;

	int					group, pgroup;
	XTXactDataPtr		xact;
	xtTableID			tab_id, ptab_id;
	XTPermRowLockPtr	plock;
	XTOpenTablePtr		pot = NULL;
	XTRowLocksPtr		row_locks;

	/* Do I have the lock? */
	group = row % XT_ROW_LOCK_COUNT;
	if (!(xact = tab_row_locks[group]))
		/* There is no lock: */
		return XT_NO_LOCK;

	if (xact != ot->ot_thread->st_xact_data)
		/* There is a lock but it does not belong to me! */
		return XT_NO_LOCK;

	tab_id = ot->ot_table->tab_id;
	plock = (XTPermRowLockPtr) &lock_list->bl_data[lock_list->bl_count * lock_list->bl_item_size];
	lock_list->rll_release_point = lock_list->bl_count;
	for (u_int i=0; i<lock_list->bl_count; i++) {
		plock--;

		pgroup = plock->pr_group;
		ptab_id = plock->pr_tab_id;

		if (ptab_id == tab_id)
			row_locks = this;
		else {
			if (pot) {
				if (pot->ot_table->tab_id == ptab_id)
					goto remove_lock;
				xt_db_return_table_to_pool_ns(pot);
				pot = NULL;
			}

			if (!xt_db_open_pool_table_ns(&pot, ot->ot_table->tab_db, tab_id)) {
				/* Should not happen, but just in case, we just don't
				 * remove the lock. We will probably end up with a deadlock
				 * somewhere.
				 */
				xt_log_and_clear_exception_ns();
				goto skip_remove_lock;
			}
			if (!pot)
				/* Can happen of the table has been dropped: */
				goto skip_remove_lock;

			remove_lock:
			row_locks = &pot->ot_table->tab_locks;
		}

#ifdef XT_TRACE_LOCKS
		xt_ttracef(xt_get_self(), "release lock group=%d\n", pgroup);
#endif
		row_locks->tab_row_locks[pgroup] = NULL;
		row_locks->tab_lock_perm[pgroup] = 0;
		skip_remove_lock:;

		lock_list->rll_release_point--;
		if (tab_id == ptab_id && group == pgroup)
			break;
	}

	if (pot) 
		xt_db_return_table_to_pool_ns(pot);
	return XT_PERM_LOCK;
}

xtBool XTRowLocks::xt_regain_locks(struct XTOpenTable *ot, int *lock_type, xtXactID *xn_id, XTRowLockListPtr lock_list)
{
	int					group;
	XTXactDataPtr		xact, my_xact;
	XTPermRowLockPtr	plock;
	xtTableID			tab_id;
	XTOpenTablePtr		pot = NULL;
	XTRowLocksPtr		row_locks = NULL;
	XTTableHPtr			tab = NULL;

	for (u_int i=lock_list->rll_release_point; i<lock_list->bl_count; i++) {
		plock = (XTPermRowLockPtr) &lock_list->bl_data[i * lock_list->bl_item_size];

		my_xact = ot->ot_thread->st_xact_data;
		group = plock->pr_group;
		tab_id = plock->pr_tab_id;

		if (tab_id == ot->ot_table->tab_id) {
			row_locks = this;
			tab = ot->ot_table;
		}
		else {
			if (pot) {
				if (tab_id == pot->ot_table->tab_id)
					goto gain_lock;
				xt_db_return_table_to_pool_ns(pot);
				pot = NULL;
			}

			if (!xt_db_open_pool_table_ns(&pot, ot->ot_table->tab_db, tab_id))
				return FAILED;
			if (!pot)
				goto no_gain_lock;
			
			gain_lock:
			tab = pot->ot_table;
			row_locks = &tab->tab_locks;
			no_gain_lock:;
		}

#ifdef XT_TRACE_LOCKS
		xt_ttracef(xt_get_self(), "regain lock group=%d\n", group);
#endif
		XT_TAB_ROW_WRITE_LOCK(&tab->tab_row_rwlock[group % XT_ROW_RWLOCKS], ot->ot_thread);
		if ((xact = row_locks->tab_row_locks[group])) {
			if (xact != my_xact) {
				*xn_id = xact->xd_start_xn_id;
				*lock_type = row_locks->tab_lock_perm[group] ? XT_PERM_LOCK : XT_TEMP_LOCK;
				goto done;
			}
		}
		else
			row_locks->tab_row_locks[group] = my_xact;
		row_locks->tab_lock_perm[group] = 1;
		XT_TAB_ROW_UNLOCK(&tab->tab_row_rwlock[group % XT_ROW_RWLOCKS], ot->ot_thread);
		lock_list->rll_release_point++;
	}
	*lock_type = XT_NO_LOCK;
	return OK;

	done:
	XT_TAB_ROW_UNLOCK(&tab->tab_row_rwlock[group % XT_ROW_RWLOCKS], ot->ot_thread);
	return OK;
}

#endif