proc.c 20.3 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * proc.c--
4
 *	  routines to manage per-process shared memory data structure
5 6 7 8 9
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/storage/lmgr/proc.c,v 1.21 1997/09/08 21:47:30 momjian Exp $
11 12 13 14
 *
 *-------------------------------------------------------------------------
 */
/*
15 16
 *	Each postgres backend gets one of these.  We'll use it to
 *	clean up after the process should the process suddenly die.
17 18 19
 *
 *
 * Interface (a):
20 21 22
 *		ProcSleep(), ProcWakeup(), ProcWakeupNext(),
 *		ProcQueueAlloc() -- create a shm queue for sleeping processes
 *		ProcQueueInit() -- create a queue without allocing memory
23 24 25 26 27 28 29 30 31 32
 *
 * Locking and waiting for buffers can cause the backend to be
 * put to sleep.  Whoever releases the lock, etc. wakes the
 * process up again (and gives it an error code so it knows
 * whether it was awoken on an error condition).
 *
 * Interface (b):
 *
 * ProcReleaseLocks -- frees the locks associated with this process,
 * ProcKill -- destroys the shared memory state (and locks)
33
 *		associated with the process.
34 35
 *
 * 5/15/91 -- removed the buffer pool based lock chain in favor
36 37 38 39 40 41
 *		of a shared memory lock chain.	The write-protection is
 *		more expensive if the lock chain is in the buffer pool.
 *		The only reason I kept the lock chain in the buffer pool
 *		in the first place was to allow the lock table to grow larger
 *		than available shared memory and that isn't going to work
 *		without a lot of unimplemented support anyway.
42 43
 *
 * 4/7/95 -- instead of allocating a set of 1 semaphore per process, we
44 45 46 47
 *		allocate a semaphore from a set of PROC_NSEMS_PER_SET semaphores
 *		shared among backends (we keep a few sets of semaphores around).
 *		This is so that we can support more backends. (system-wide semaphore
 *		sets run out pretty fast.)				  -ay 4/95
48
 *
49
 * $Header: /cvsroot/pgsql/src/backend/storage/lmgr/proc.c,v 1.21 1997/09/08 21:47:30 momjian Exp $
50 51 52 53
 */
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
54
#include <signal.h>
55
#include <sys/types.h>
M
Marc G. Fournier 已提交
56

57 58 59 60 61
#if defined(sparc_solaris)
#include <sys/ipc.h>
#include <sys/sem.h>
#endif

M
Marc G. Fournier 已提交
62
#include "postgres.h"
63
#include "miscadmin.h"
64
#include "libpq/pqsignal.h"
65 66 67 68

#include "access/xact.h"
#include "utils/hsearch.h"

69 70 71
#include "storage/ipc.h"
/* In Ultrix, sem.h must be included after ipc.h */
#include <sys/sem.h>
72
#include "storage/buf.h"
73
#include "storage/lock.h"
B
Bruce Momjian 已提交
74
#include "storage/lmgr.h"
75 76 77 78
#include "storage/shmem.h"
#include "storage/spin.h"
#include "storage/proc.h"

79
static void HandleDeadLock(int sig);
80
static PROC *ProcWakeup(PROC *proc, int errType);
81

82 83 84 85
/*
 * timeout (in seconds) for resolving possible deadlock
 */
#ifndef DEADLOCK_TIMEOUT
86
#define DEADLOCK_TIMEOUT		60
87 88 89 90 91 92 93 94 95
#endif

/* --------------------
 * Spin lock for manipulating the shared process data structure:
 * ProcGlobal.... Adding an extra spin lock seemed like the smallest
 * hack to get around reading and updating this structure in shared
 * memory. -mer 17 July 1991
 * --------------------
 */
96
SPINLOCK	ProcStructLock;
97 98 99 100 101

/*
 * For cleanup routines.  Don't cleanup if the initialization
 * has not happened.
 */
102
static bool ProcInitialized = FALSE;
103 104 105

static PROC_HDR *ProcGlobal = NULL;

106
PROC	   *MyProc = NULL;
107

108
static void ProcKill(int exitStatus, int pid);
109
static void ProcGetNewSemKeyAndNum(IPCKey *key, int *semNum);
110
static void ProcFreeSem(IpcSemaphoreKey semKey, int semNum);
111 112 113

/*
 * InitProcGlobal -
114 115 116 117 118
 *	  initializes the global process table. We put it here so that
 *	  the postmaster can do this initialization. (ProcFreeAllSem needs
 *	  to read this table on exiting the postmaster. If we have the first
 *	  backend do this, starting up and killing the postmaster without
 *	  starting any backends will be a problem.)
119 120 121 122
 */
void
InitProcGlobal(IPCKey key)
{
123
	bool		found = false;
124

125 126 127
	/* attach to the free list */
	ProcGlobal = (PROC_HDR *)
		ShmemInitStruct("Proc Header", (unsigned) sizeof(PROC_HDR), &found);
128

129 130 131 132 133
	/* --------------------
	 * We're the first - initialize.
	 * --------------------
	 */
	if (!found)
134
	{
135
		int			i;
136

137 138 139 140 141
		ProcGlobal->numProcs = 0;
		ProcGlobal->freeProcs = INVALID_OFFSET;
		ProcGlobal->currKey = IPCGetProcessSemaphoreInitKey(key);
		for (i = 0; i < MAX_PROC_SEMS / PROC_NSEMS_PER_SET; i++)
			ProcGlobal->freeSemMap[i] = 0;
142 143 144 145 146 147 148 149 150 151 152
	}
}

/* ------------------------
 * InitProc -- create a per-process data structure for this process
 * used by the lock manager on semaphore queues.
 * ------------------------
 */
void
InitProcess(IPCKey key)
{
153 154 155 156 157
	bool		found = false;
	int			pid;
	int			semstat;
	unsigned long location,
				myOffset;
158 159 160 161 162 163 164 165 166 167 168 169 170

	/* ------------------
	 * Routine called if deadlock timer goes off. See ProcSleep()
	 * ------------------
	 */
	pqsignal(SIGALRM, HandleDeadLock);

	SpinAcquire(ProcStructLock);

	/* attach to the free list */
	ProcGlobal = (PROC_HDR *)
		ShmemInitStruct("Proc Header", (unsigned) sizeof(PROC_HDR), &found);
	if (!found)
171
	{
172 173
		/* this should not happen. InitProcGlobal() is called before this. */
		elog(WARN, "InitProcess: Proc Header uninitialized");
174
	}
175 176

	if (MyProc != NULL)
177
	{
178 179 180
		SpinRelease(ProcStructLock);
		elog(WARN, "ProcInit: you already exist");
		return;
181
	}
182 183 184 185 186 187

	/* try to get a proc from the free list first */

	myOffset = ProcGlobal->freeProcs;

	if (myOffset != INVALID_OFFSET)
188
	{
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
		MyProc = (PROC *) MAKE_PTR(myOffset);
		ProcGlobal->freeProcs = MyProc->links.next;
	}
	else
	{

		/*
		 * have to allocate one.  We can't use the normal binding table
		 * mechanism because the proc structure is stored by PID instead
		 * of by a global name (need to look it up by PID when we cleanup
		 * dead processes).
		 */

		MyProc = (PROC *) ShmemAlloc((unsigned) sizeof(PROC));
		if (!MyProc)
204
		{
205 206
			SpinRelease(ProcStructLock);
			elog(FATAL, "cannot create new proc: out of memory");
207
		}
208 209 210 211 212

		/* this cannot be initialized until after the buffer pool */
		SHMQueueInit(&(MyProc->lockQueue));
		MyProc->procId = ProcGlobal->numProcs;
		ProcGlobal->numProcs++;
213
	}
214

215
	/*
216 217 218
	 * zero out the spin lock counts and set the sLocks field for
	 * ProcStructLock to 1 as we have acquired this spinlock above but
	 * didn't record it since we didn't have MyProc until now.
219
	 */
220 221 222 223 224 225
	memset(MyProc->sLocks, 0, sizeof(MyProc->sLocks));
	MyProc->sLocks[ProcStructLock] = 1;


	if (IsUnderPostmaster)
	{
226 227 228 229
		IPCKey		semKey;
		int			semNum;
		int			semId;
		union semun semun;
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

		ProcGetNewSemKeyAndNum(&semKey, &semNum);

		semId = IpcSemaphoreCreate(semKey,
								   PROC_NSEMS_PER_SET,
								   IPCProtection,
								   IpcSemaphoreDefaultStartValue,
								   0,
								   &semstat);

		/*
		 * we might be reusing a semaphore that belongs to a dead backend.
		 * So be careful and reinitialize its value here.
		 */
		semun.val = IpcSemaphoreDefaultStartValue;
		semctl(semId, semNum, SETVAL, semun);

		IpcSemaphoreLock(semId, semNum, IpcExclusiveLock);
		MyProc->sem.semId = semId;
		MyProc->sem.semNum = semNum;
		MyProc->sem.semKey = semKey;
	}
	else
	{
		MyProc->sem.semId = -1;
	}

	/* ----------------------
	 * Release the lock.
	 * ----------------------
	 */
	SpinRelease(ProcStructLock);

	MyProc->pid = 0;
	MyProc->xid = InvalidTransactionId;
265
#if 0
266
	MyProc->pid = MyPid;
267
#endif
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

	/* ----------------
	 * Start keeping spin lock stats from here on.	Any botch before
	 * this initialization is forever botched
	 * ----------------
	 */
	memset(MyProc->sLocks, 0, MAX_SPINS * sizeof(*MyProc->sLocks));

	/* -------------------------
	 * Install ourselves in the binding table.	The name to
	 * use is determined by the OS-assigned process id.  That
	 * allows the cleanup process to find us after any untimely
	 * exit.
	 * -------------------------
	 */
	pid = getpid();
	location = MAKE_OFFSET(MyProc);
	if ((!ShmemPIDLookup(pid, &location)) || (location != MAKE_OFFSET(MyProc)))
286
	{
287
		elog(FATAL, "InitProc: ShmemPID table broken");
288
	}
289 290 291 292 293 294 295

	MyProc->errType = NO_ERROR;
	SHMQueueElemInit(&(MyProc->links));

	on_exitpg(ProcKill, (caddr_t) pid);

	ProcInitialized = TRUE;
296 297 298 299 300 301 302 303 304
}

/*
 * ProcReleaseLocks() -- release all locks associated with this process
 *
 */
void
ProcReleaseLocks()
{
305 306 307
	if (!MyProc)
		return;
	LockReleaseAll(1, &MyProc->lockQueue);
308 309 310 311
}

/*
 * ProcRemove -
312 313 314 315 316
 *	  used by the postmaster to clean up the global tables. This also frees
 *	  up the semaphore used for the lmgr of the process. (We have to do
 *	  this is the postmaster instead of doing a IpcSemaphoreKill on exiting
 *	  the process because the semaphore set is shared among backends and
 *	  we don't want to remove other's semaphores on exit.)
317 318 319 320
 */
bool
ProcRemove(int pid)
{
321 322
	SHMEM_OFFSET location;
	PROC	   *proc;
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

	location = INVALID_OFFSET;

	location = ShmemPIDDestroy(pid);
	if (location == INVALID_OFFSET)
		return (FALSE);
	proc = (PROC *) MAKE_PTR(location);

	SpinAcquire(ProcStructLock);

	ProcFreeSem(proc->sem.semKey, proc->sem.semNum);

	proc->links.next = ProcGlobal->freeProcs;
	ProcGlobal->freeProcs = MAKE_OFFSET(proc);

	SpinRelease(ProcStructLock);

	return (TRUE);
341 342 343 344
}

/*
 * ProcKill() -- Destroy the per-proc data structure for
345
 *		this process. Release any of its held spin locks.
346 347 348 349
 */
static void
ProcKill(int exitStatus, int pid)
{
350 351
	PROC	   *proc;
	SHMEM_OFFSET location;
352 353 354 355 356 357 358 359 360 361 362

	/* --------------------
	 * If this is a FATAL exit the postmaster will have to kill all the
	 * existing backends and reinitialize shared memory.  So all we don't
	 * need to do anything here.
	 * --------------------
	 */
	if (exitStatus != 0)
		return;

	if (!pid)
363
	{
364
		pid = getpid();
365
	}
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

	ShmemPIDLookup(pid, &location);
	if (location == INVALID_OFFSET)
		return;

	proc = (PROC *) MAKE_PTR(location);

	if (proc != MyProc)
	{
		Assert(pid != getpid());
	}
	else
		MyProc = NULL;

	/* ---------------
	 * Assume one lock table.
	 * ---------------
	 */
	ProcReleaseSpins(proc);
	LockReleaseAll(1, &proc->lockQueue);

387
#ifdef USER_LOCKS
388
	LockReleaseAll(0, &proc->lockQueue);
389 390
#endif

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
	/* ----------------
	 * get off the wait queue
	 * ----------------
	 */
	LockLockTable();
	if (proc->links.next != INVALID_OFFSET)
	{
		Assert(proc->waitLock->waitProcs.size > 0);
		SHMQueueDelete(&(proc->links));
		--proc->waitLock->waitProcs.size;
	}
	SHMQueueElemInit(&(proc->links));
	UnlockLockTable();

	return;
406 407 408 409
}

/*
 * ProcQueue package: routines for putting processes to sleep
410
 *		and  waking them up
411 412 413 414 415 416 417 418
 */

/*
 * ProcQueueAlloc -- alloc/attach to a shared memory process queue
 *
 * Returns: a pointer to the queue or NULL
 * Side Effects: Initializes the queue if we allocated one
 */
419
#ifdef NOT_USED
420
PROC_QUEUE *
421 422
ProcQueueAlloc(char *name)
{
423 424
	bool		found;
	PROC_QUEUE *queue = (PROC_QUEUE *)
425 426 427
	ShmemInitStruct(name, (unsigned) sizeof(PROC_QUEUE), &found);

	if (!queue)
428
	{
429
		return (NULL);
430
	}
431
	if (!found)
432
	{
433
		ProcQueueInit(queue);
434
	}
435
	return (queue);
436
}
437

438
#endif
439 440 441 442 443

/*
 * ProcQueueInit -- initialize a shared memory process queue
 */
void
444
ProcQueueInit(PROC_QUEUE *queue)
445
{
446 447
	SHMQueueInit(&(queue->links));
	queue->size = 0;
448 449 450 451 452 453 454 455 456 457 458 459
}



/*
 * ProcSleep -- put a process to sleep
 *
 * P() on the semaphore should put us to sleep.  The process
 * semaphore is cleared by default, so the first time we try
 * to acquire it, we sleep.
 *
 * ASSUME: that no one will fiddle with the queue until after
460
 *		we release the spin lock.
461 462 463 464
 *
 * NOTES: The process queue is now a priority queue for locking.
 */
int
465
ProcSleep(PROC_QUEUE *queue,
466 467 468
		  SPINLOCK spinlock,
		  int token,
		  int prio,
469
		  LOCK *lock)
470
{
471 472
	int			i;
	PROC	   *proc;
473
	struct itimerval timeval,
474
				dummy;
475 476 477

	proc = (PROC *) MAKE_PTR(queue->links.prev);
	for (i = 0; i < queue->size; i++)
478
	{
479 480 481 482
		if (proc->prio < prio)
			proc = (PROC *) MAKE_PTR(proc->links.prev);
		else
			break;
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

	MyProc->prio = prio;
	MyProc->token = token;
	MyProc->waitLock = lock;

	/* -------------------
	 * currently, we only need this for the ProcWakeup routines
	 * -------------------
	 */
	TransactionIdStore((TransactionId) GetCurrentTransactionId(), &MyProc->xid);

	/* -------------------
	 * assume that these two operations are atomic (because
	 * of the spinlock).
	 * -------------------
	 */
	SHMQueueInsertTL(&(proc->links), &(MyProc->links));
	queue->size++;

	SpinRelease(spinlock);

	/* --------------
	 * Postgres does not have any deadlock detection code and for this
	 * reason we must set a timer to wake up the process in the event of
	 * a deadlock.	For now the timer is set for 1 minute and we assume that
	 * any process which sleeps for this amount of time is deadlocked and will
	 * receive a SIGALRM signal.  The handler should release the processes
	 * semaphore and abort the current transaction.
	 *
	 * Need to zero out struct to set the interval and the micro seconds fields
	 * to 0.
	 * --------------
	 */
	memset(&timeval, 0, sizeof(struct itimerval));
	timeval.it_value.tv_sec = DEADLOCK_TIMEOUT;

	if (setitimer(ITIMER_REAL, &timeval, &dummy))
		elog(FATAL, "ProcSleep: Unable to set timer for process wakeup");

	/* --------------
	 * if someone wakes us between SpinRelease and IpcSemaphoreLock,
	 * IpcSemaphoreLock will not block.  The wakeup is "saved" by
	 * the semaphore implementation.
	 * --------------
	 */
	IpcSemaphoreLock(MyProc->sem.semId, MyProc->sem.semNum, IpcExclusiveLock);

	/* ---------------
	 * We were awoken before a timeout - now disable the timer
	 * ---------------
	 */
	timeval.it_value.tv_sec = 0;


	if (setitimer(ITIMER_REAL, &timeval, &dummy))
		elog(FATAL, "ProcSleep: Unable to diable timer for process wakeup");

	/* ----------------
	 * We were assumed to be in a critical section when we went
	 * to sleep.
	 * ----------------
	 */
	SpinAcquire(spinlock);

	return (MyProc->errType);
549 550 551 552 553 554
}


/*
 * ProcWakeup -- wake up a process by releasing its private semaphore.
 *
555 556
 *	 remove the process from the wait queue and set its links invalid.
 *	 RETURN: the next process in the wait queue.
557
 */
558
static PROC *
559
ProcWakeup(PROC *proc, int errType)
560
{
561
	PROC	   *retProc;
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

	/* assume that spinlock has been acquired */

	if (proc->links.prev == INVALID_OFFSET ||
		proc->links.next == INVALID_OFFSET)
		return ((PROC *) NULL);

	retProc = (PROC *) MAKE_PTR(proc->links.prev);

	/* you have to update waitLock->waitProcs.size yourself */
	SHMQueueDelete(&(proc->links));
	SHMQueueElemInit(&(proc->links));

	proc->errType = errType;

	IpcSemaphoreUnlock(proc->sem.semId, proc->sem.semNum, IpcExclusiveLock);

	return retProc;
580 581 582 583 584 585
}


/*
 * ProcGetId --
 */
586
#ifdef NOT_USED
587 588 589
int
ProcGetId()
{
590
	return (MyProc->procId);
591
}
592

593
#endif
594 595 596

/*
 * ProcLockWakeup -- routine for waking up processes when a lock is
597
 *		released.
598 599
 */
int
600
ProcLockWakeup(PROC_QUEUE *queue, char *ltable, char *lock)
601
{
602 603
	PROC	   *proc;
	int			count;
604 605 606 607 608 609 610 611 612 613

	if (!queue->size)
		return (STATUS_NOT_FOUND);

	proc = (PROC *) MAKE_PTR(queue->links.prev);
	count = 0;
	while ((LockResolveConflicts((LOCKTAB *) ltable,
								 (LOCK *) lock,
								 proc->token,
								 proc->xid) == STATUS_OK))
614
	{
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

		/*
		 * there was a waiting process, grant it the lock before waking it
		 * up.	This will prevent another process from seizing the lock
		 * between the time we release the lock master (spinlock) and the
		 * time that the awoken process begins executing again.
		 */
		GrantLock((LOCK *) lock, proc->token);
		queue->size--;

		/*
		 * ProcWakeup removes proc from the lock waiting process queue and
		 * returns the next proc in chain.	If a writer just dropped its
		 * lock and there are several waiting readers, wake them all up.
		 */
		proc = ProcWakeup(proc, NO_ERROR);

		count++;
		if (!proc || queue->size == 0)
			break;
635
	}
636 637 638 639 640 641

	if (count)
		return (STATUS_OK);
	else
		/* Something is still blocking us.	May have deadlocked. */
		return (STATUS_NOT_FOUND);
642 643 644
}

void
645
ProcAddLock(SHM_QUEUE *elem)
646
{
647
	SHMQueueInsertTL(&MyProc->lockQueue, elem);
648 649 650 651 652 653 654
}

/* --------------------
 * We only get to this routine if we got SIGALRM after DEADLOCK_TIMEOUT
 * while waiting for a lock to be released by some other process.  After
 * the one minute deadline we assume we have a deadlock and must abort
 * this transaction.  We must also indicate that I'm no longer waiting
655
 * on a lock so that other processes don't try to wake me up and screw
656 657 658
 * up my semaphore.
 * --------------------
 */
659
static void
M
Fixes:  
Marc G. Fournier 已提交
660
HandleDeadLock(int sig)
661
{
662 663
	LOCK	   *lock;
	int			size;
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

	LockLockTable();

	/* ---------------------
	 * Check to see if we've been awoken by anyone in the interim.
	 *
	 * If we have we can return and resume our transaction -- happy day.
	 * Before we are awoken the process releasing the lock grants it to
	 * us so we know that we don't have to wait anymore.
	 *
	 * Damn these names are LONG! -mer
	 * ---------------------
	 */
	if (IpcSemaphoreGetCount(MyProc->sem.semId, MyProc->sem.semNum) ==
		IpcSemaphoreDefaultStartValue)
	{
		UnlockLockTable();
		return;
	}

	/*
	 * you would think this would be unnecessary, but...
	 *
	 * this also means we've been removed already.  in some ports (e.g.,
	 * sparc and aix) the semop(2) implementation is such that we can
	 * actually end up in this handler after someone has removed us from
	 * the queue and bopped the semaphore *but the test above fails to
	 * detect the semaphore update* (presumably something weird having to
	 * do with the order in which the semaphore wakeup signal and SIGALRM
	 * get handled).
	 */
	if (MyProc->links.prev == INVALID_OFFSET ||
		MyProc->links.next == INVALID_OFFSET)
	{
		UnlockLockTable();
		return;
	}

	lock = MyProc->waitLock;
	size = lock->waitProcs.size;/* so we can look at this in the core */

705
#ifdef DEADLOCK_DEBUG
706
	DumpLocks();
707 708
#endif

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
	/* ------------------------
	 * Get this process off the lock's wait queue
	 * ------------------------
	 */
	Assert(lock->waitProcs.size > 0);
	--lock->waitProcs.size;
	SHMQueueDelete(&(MyProc->links));
	SHMQueueElemInit(&(MyProc->links));

	/* ------------------
	 * Unlock my semaphore so that the count is right for next time.
	 * I was awoken by a signal, not by someone unlocking my semaphore.
	 * ------------------
	 */
	IpcSemaphoreUnlock(MyProc->sem.semId, MyProc->sem.semNum, IpcExclusiveLock);

	/* -------------
	 * Set MyProc->errType to STATUS_ERROR so that we abort after
	 * returning from this handler.
	 * -------------
	 */
	MyProc->errType = STATUS_ERROR;

	/*
	 * if this doesn't follow the IpcSemaphoreUnlock then we get lock
	 * table corruption ("LockReplace: xid table corrupted") due to race
	 * conditions.	i don't claim to understand this...
	 */
	UnlockLockTable();

	elog(NOTICE, "Timeout -- possible deadlock");
	return;
741 742 743
}

void
744
ProcReleaseSpins(PROC *proc)
745
{
746
	int			i;
747 748 749 750 751 752 753

	if (!proc)
		proc = MyProc;

	if (!proc)
		return;
	for (i = 0; i < (int) MAX_SPINS; i++)
754
	{
755
		if (proc->sLocks[i])
756
		{
757 758
			Assert(proc->sLocks[i] == 1);
			SpinRelease(i);
759 760 761 762 763
		}
	}
}

/*****************************************************************************
764
 *
765 766 767 768
 *****************************************************************************/

/*
 * ProcGetNewSemKeyAndNum -
769 770 771 772
 *	  scan the free semaphore bitmap and allocate a single semaphore from
 *	  a semaphore set. (If the semaphore set doesn't exist yet,
 *	  IpcSemaphoreCreate will create it. Otherwise, we use the existing
 *	  semaphore set.)
773 774
 */
static void
775
ProcGetNewSemKeyAndNum(IPCKey *key, int *semNum)
776
{
777 778 779
	int			i;
	int32	   *freeSemMap = ProcGlobal->freeSemMap;
	unsigned int fullmask;
780

781 782 783 784 785 786 787
	/*
	 * we hold ProcStructLock when entering this routine. We scan through
	 * the bitmap to look for a free semaphore.
	 */
	fullmask = ~0 >> (32 - PROC_NSEMS_PER_SET);
	for (i = 0; i < MAX_PROC_SEMS / PROC_NSEMS_PER_SET; i++)
	{
788 789
		int			mask = 1;
		int			j;
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

		if (freeSemMap[i] == fullmask)
			continue;			/* none free for this set */

		for (j = 0; j < PROC_NSEMS_PER_SET; j++)
		{
			if ((freeSemMap[i] & mask) == 0)
			{

				/*
				 * a free semaphore found. Mark it as allocated.
				 */
				freeSemMap[i] |= mask;

				*key = ProcGlobal->currKey + i;
				*semNum = j;
				return;
			}
			mask <<= 1;
		}
810 811
	}

812 813
	/* if we reach here, all the semaphores are in use. */
	elog(WARN, "InitProc: cannot allocate a free semaphore");
814 815 816 817
}

/*
 * ProcFreeSem -
818 819
 *	  free up our semaphore in the semaphore set. If we're the last one
 *	  in the set, also remove the semaphore set.
820 821 822 823
 */
static void
ProcFreeSem(IpcSemaphoreKey semKey, int semNum)
{
824 825 826
	int			mask;
	int			i;
	int32	   *freeSemMap = ProcGlobal->freeSemMap;
827

828 829 830
	i = semKey - ProcGlobal->currKey;
	mask = ~(1 << semNum);
	freeSemMap[i] &= mask;
831

832 833
	if (freeSemMap[i] == 0)
		IpcSemaphoreKill(semKey);
834 835 836 837
}

/*
 * ProcFreeAllSemaphores -
838 839
 *	  on exiting the postmaster, we free up all the semaphores allocated
 *	  to the lmgrs of the backends.
840 841 842 843
 */
void
ProcFreeAllSemaphores()
{
844 845
	int			i;
	int32	   *freeSemMap = ProcGlobal->freeSemMap;
846

847 848 849 850 851
	for (i = 0; i < MAX_PROC_SEMS / PROC_NSEMS_PER_SET; i++)
	{
		if (freeSemMap[i] != 0)
			IpcSemaphoreKill(ProcGlobal->currKey + i);
	}
852
}