proc.c 37.1 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * proc.c
4
 *	  routines to manage per-process shared memory data structure
5
 *
6
 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/storage/lmgr/proc.c,v 1.181 2006/11/21 20:59:52 tgl Exp $
12 13 14 15 16
 *
 *-------------------------------------------------------------------------
 */
/*
 * Interface (a):
17
 *		ProcSleep(), ProcWakeup(),
18 19
 *		ProcQueueAlloc() -- create a shm queue for sleeping processes
 *		ProcQueueInit() -- create a queue without allocing memory
20
 *
21 22
 * Waiting for a lock causes the backend to be put to sleep.  Whoever releases
 * the lock wakes the process up again (and gives it an error code so it knows
23 24 25 26
 * whether it was awoken on an error condition).
 *
 * Interface (b):
 *
27 28
 * ProcReleaseLocks -- frees the locks associated with current transaction
 *
29
 * ProcKill -- destroys the shared memory state (and locks)
30
 * associated with the process.
31
 */
32 33
#include "postgres.h"

34
#include <signal.h>
35 36
#include <unistd.h>
#include <sys/time.h>
M
Marc G. Fournier 已提交
37

38
#include "access/transam.h"
39
#include "access/xact.h"
40
#include "miscadmin.h"
41
#include "storage/ipc.h"
42
#include "storage/proc.h"
43
#include "storage/procarray.h"
44
#include "storage/spin.h"
45

46

47
/* GUC variables */
B
Bruce Momjian 已提交
48
int			DeadlockTimeout = 1000;
49
int			StatementTimeout = 0;
M
 
Marc G. Fournier 已提交
50

51
/* Pointer to this process's PGPROC struct, if any */
J
Jan Wieck 已提交
52
PGPROC	   *MyProc = NULL;
53 54

/*
J
Jan Wieck 已提交
55
 * This spinlock protects the freelist of recycled PGPROC structures.
56
 * We cannot use an LWLock because the LWLock manager depends on already
J
Jan Wieck 已提交
57
 * having a PGPROC and a wait semaphore!  But these structures are touched
58 59
 * relatively infrequently (only at backend startup or shutdown) and not for
 * very long, so a spinlock is okay.
60
 */
61
NON_EXEC_STATIC slock_t *ProcStructLock = NULL;
62

63
/* Pointers to shared-memory structures */
64 65
NON_EXEC_STATIC PROC_HDR *ProcGlobal = NULL;
NON_EXEC_STATIC PGPROC *DummyProcs = NULL;
66

67 68
/* If we are waiting for a lock, this points to the associated LOCALLOCK */
static LOCALLOCK *lockAwaited = NULL;
69

70 71 72
/* Mark these volatile because they can be changed by signal handler */
static volatile bool statement_timeout_active = false;
static volatile bool deadlock_timeout_active = false;
73
volatile bool cancel_from_timeout = false;
B
Bruce Momjian 已提交
74

75
/* statement_fin_time is valid only if statement_timeout_active is true */
76
static TimestampTz statement_fin_time;
77 78


79
static void RemoveProcFromArray(int code, Datum arg);
80 81
static void ProcKill(int code, Datum arg);
static void DummyProcKill(int code, Datum arg);
82
static bool CheckStatementTimeout(void);
83

V
Vadim B. Mikheev 已提交
84

85 86 87
/*
 * Report shared-memory space needed by InitProcGlobal.
 */
88
Size
89
ProcGlobalShmemSize(void)
90
{
91 92 93 94 95 96 97 98 99 100
	Size		size = 0;

	/* ProcGlobal */
	size = add_size(size, sizeof(PROC_HDR));
	/* DummyProcs */
	size = add_size(size, mul_size(NUM_DUMMY_PROCS, sizeof(PGPROC)));
	/* MyProcs */
	size = add_size(size, mul_size(MaxBackends, sizeof(PGPROC)));
	/* ProcStructLock */
	size = add_size(size, sizeof(slock_t));
101 102 103 104

	return size;
}

105 106 107 108
/*
 * Report number of semaphores needed by InitProcGlobal.
 */
int
109
ProcGlobalSemas(void)
110
{
111
	/* We need a sema per backend, plus one for each dummy process. */
112
	return MaxBackends + NUM_DUMMY_PROCS;
113 114
}

115 116
/*
 * InitProcGlobal -
117 118
 *	  Initialize the global process table during postmaster or standalone
 *	  backend startup.
119
 *
120
 *	  We also create all the per-process semaphores we will need to support
121 122 123 124 125 126 127 128 129
 *	  the requested number of backends.  We used to allocate semaphores
 *	  only when backends were actually started up, but that is bad because
 *	  it lets Postgres fail under load --- a lot of Unix systems are
 *	  (mis)configured with small limits on the number of semaphores, and
 *	  running out when trying to start another backend is a common failure.
 *	  So, now we grab enough semaphores to support the desired max number
 *	  of backends immediately at initialization --- if the sysadmin has set
 *	  MaxBackends higher than his kernel will support, he'll find out sooner
 *	  rather than later.
130 131 132 133
 *
 *	  Another reason for creating semaphores here is that the semaphore
 *	  implementation typically requires us to create semaphores in the
 *	  postmaster, not in backends.
134 135 136 137
 *
 * Note: this is NOT called by individual backends under a postmaster,
 * not even in the EXEC_BACKEND case.  The ProcGlobal and DummyProcs
 * pointers must be propagated specially for EXEC_BACKEND operation.
138 139
 */
void
140
InitProcGlobal(void)
141
{
142 143 144
	PGPROC	   *procs;
	int			i;
	bool		found;
145

146
	/* Create the ProcGlobal shared structure */
147
	ProcGlobal = (PROC_HDR *)
148 149
		ShmemInitStruct("Proc Header", sizeof(PROC_HDR), &found);
	Assert(!found);
150

151
	/*
B
Bruce Momjian 已提交
152 153
	 * Create the PGPROC structures for dummy (bgwriter) processes, too. These
	 * do not get linked into the freeProcs list.
154
	 */
155
	DummyProcs = (PGPROC *)
156
		ShmemInitStruct("DummyProcs", NUM_DUMMY_PROCS * sizeof(PGPROC),
157 158
						&found);
	Assert(!found);
159

160 161 162 163
	/*
	 * Initialize the data structures.
	 */
	ProcGlobal->freeProcs = INVALID_OFFSET;
164

165
	ProcGlobal->spins_per_delay = DEFAULT_SPINS_PER_DELAY;
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
	/*
	 * Pre-create the PGPROC structures and create a semaphore for each.
	 */
	procs = (PGPROC *) ShmemAlloc(MaxBackends * sizeof(PGPROC));
	if (!procs)
		ereport(FATAL,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("out of shared memory")));
	MemSet(procs, 0, MaxBackends * sizeof(PGPROC));
	for (i = 0; i < MaxBackends; i++)
	{
		PGSemaphoreCreate(&(procs[i].sem));
		procs[i].links.next = ProcGlobal->freeProcs;
		ProcGlobal->freeProcs = MAKE_OFFSET(&procs[i]);
	}
182

183 184 185
	MemSet(DummyProcs, 0, NUM_DUMMY_PROCS * sizeof(PGPROC));
	for (i = 0; i < NUM_DUMMY_PROCS; i++)
	{
B
Bruce Momjian 已提交
186
		DummyProcs[i].pid = 0;	/* marks dummy proc as not in use */
187
		PGSemaphoreCreate(&(DummyProcs[i].sem));
188
	}
189 190 191 192

	/* Create ProcStructLock spinlock, too */
	ProcStructLock = (slock_t *) ShmemAlloc(sizeof(slock_t));
	SpinLockInit(ProcStructLock);
193 194
}

195
/*
196
 * InitProcess -- initialize a per-process data structure for this backend
197 198
 */
void
199
InitProcess(void)
200
{
201 202
	/* use volatile pointer to prevent code rearrangement */
	volatile PROC_HDR *procglobal = ProcGlobal;
203 204
	SHMEM_OFFSET myOffset;
	int			i;
205 206

	/*
207 208
	 * ProcGlobal should be set up already (if we are a backend, we inherit
	 * this by fork() or EXEC_BACKEND mechanism from the postmaster).
209
	 */
210
	if (procglobal == NULL)
211
		elog(PANIC, "proc header uninitialized");
212 213

	if (MyProc != NULL)
214
		elog(ERROR, "you already exist");
215

216
	/*
B
Bruce Momjian 已提交
217 218
	 * Try to get a proc struct from the free list.  If this fails, we must be
	 * out of PGPROC structures (not to mention semaphores).
219
	 *
B
Bruce Momjian 已提交
220 221
	 * While we are holding the ProcStructLock, also copy the current shared
	 * estimate of spins_per_delay to local storage.
222
	 */
223
	SpinLockAcquire(ProcStructLock);
224

225 226
	set_spins_per_delay(procglobal->spins_per_delay);

227
	myOffset = procglobal->freeProcs;
228 229

	if (myOffset != INVALID_OFFSET)
230
	{
J
Jan Wieck 已提交
231
		MyProc = (PGPROC *) MAKE_PTR(myOffset);
232
		procglobal->freeProcs = MyProc->links.next;
233
		SpinLockRelease(ProcStructLock);
234 235 236 237
	}
	else
	{
		/*
B
Bruce Momjian 已提交
238 239 240
		 * If we reach here, all the PGPROCs are in use.  This is one of the
		 * possible places to detect "too many backends", so give the standard
		 * error message.
241
		 */
242
		SpinLockRelease(ProcStructLock);
243 244 245
		ereport(FATAL,
				(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
				 errmsg("sorry, too many clients already")));
246
	}
247

248
	/*
B
Bruce Momjian 已提交
249 250
	 * Initialize all fields of MyProc, except for the semaphore which was
	 * prepared for us by InitProcGlobal.
251
	 */
252
	SHMQueueElemInit(&(MyProc->links));
253
	MyProc->waitStatus = STATUS_OK;
254
	MyProc->xid = InvalidTransactionId;
255
	MyProc->xmin = InvalidTransactionId;
256
	MyProc->pid = MyProcPid;
257 258
	/* databaseId and roleId will be filled in later */
	MyProc->databaseId = InvalidOid;
259
	MyProc->roleId = InvalidOid;
260
	MyProc->inVacuum = false;
261 262 263
	MyProc->lwWaiting = false;
	MyProc->lwExclusive = false;
	MyProc->lwWaitLink = NULL;
264
	MyProc->waitLock = NULL;
265
	MyProc->waitProcLock = NULL;
266 267
	for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
		SHMQueueInit(&(MyProc->myProcLocks[i]));
268

269
	/*
270
	 * We might be reusing a semaphore that belonged to a failed process. So
B
Bruce Momjian 已提交
271
	 * be careful and reinitialize its value here.	(This is not strictly
272
	 * necessary anymore, but seems like a good idea for cleanliness.)
273
	 */
274
	PGSemaphoreReset(&MyProc->sem);
275

276
	/*
277
	 * Arrange to clean up at backend exit.
278
	 */
279
	on_shmem_exit(ProcKill, 0);
280 281

	/*
B
Bruce Momjian 已提交
282 283
	 * Now that we have a PGPROC, we could try to acquire locks, so initialize
	 * the deadlock checker.
284 285
	 */
	InitDeadLockChecking();
286 287
}

288 289 290 291 292 293 294 295 296 297 298 299 300
/*
 * InitProcessPhase2 -- make MyProc visible in the shared ProcArray.
 *
 * This is separate from InitProcess because we can't acquire LWLocks until
 * we've created a PGPROC, but in the EXEC_BACKEND case there is a good deal
 * of stuff to be done before this step that will require LWLock access.
 */
void
InitProcessPhase2(void)
{
	Assert(MyProc != NULL);

	/*
B
Bruce Momjian 已提交
301 302 303
	 * We should now know what database we're in, so advertise that.  (We need
	 * not do any locking here, since no other backend can yet see our
	 * PGPROC.)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
	 */
	Assert(OidIsValid(MyDatabaseId));
	MyProc->databaseId = MyDatabaseId;

	/*
	 * Add our PGPROC to the PGPROC array in shared memory.
	 */
	ProcArrayAdd(MyProc);

	/*
	 * Arrange to clean that up at backend exit.
	 */
	on_shmem_exit(RemoveProcFromArray, 0);
}

319 320 321
/*
 * InitDummyProcess -- create a dummy per-process data structure
 *
322 323
 * This is called by bgwriter and similar processes so that they will have a
 * MyProc value that's real enough to let them wait for LWLocks.  The PGPROC
324
 * and sema that are assigned are one of the extra ones created during
325
 * InitProcGlobal.
326 327
 *
 * Dummy processes are presently not expected to wait for real (lockmgr)
328 329
 * locks, so we need not set up the deadlock checker.  They are never added
 * to the ProcArray or the sinval messaging mechanism, either.
330 331
 */
void
332
InitDummyProcess(void)
333
{
B
Bruce Momjian 已提交
334
	PGPROC	   *dummyproc;
335
	int			proctype;
336
	int			i;
J
Jan Wieck 已提交
337

338
	/*
339 340
	 * ProcGlobal should be set up already (if we are a backend, we inherit
	 * this by fork() or EXEC_BACKEND mechanism from the postmaster).
341
	 */
342
	if (ProcGlobal == NULL || DummyProcs == NULL)
343
		elog(PANIC, "proc header uninitialized");
344 345

	if (MyProc != NULL)
346
		elog(ERROR, "you already exist");
347

348
	/*
349 350
	 * We use the ProcStructLock to protect assignment and releasing of
	 * DummyProcs entries.
351
	 *
B
Bruce Momjian 已提交
352 353
	 * While we are holding the ProcStructLock, also copy the current shared
	 * estimate of spins_per_delay to local storage.
354 355 356 357 358
	 */
	SpinLockAcquire(ProcStructLock);

	set_spins_per_delay(ProcGlobal->spins_per_delay);

359
	/*
360
	 * Find a free dummyproc ... *big* trouble if there isn't one ...
361
	 */
362 363 364 365 366 367 368
	for (proctype = 0; proctype < NUM_DUMMY_PROCS; proctype++)
	{
		dummyproc = &DummyProcs[proctype];
		if (dummyproc->pid == 0)
			break;
	}
	if (proctype >= NUM_DUMMY_PROCS)
369 370
	{
		SpinLockRelease(ProcStructLock);
371
		elog(FATAL, "all DummyProcs are in use");
372
	}
373

374 375 376 377 378
	/* Mark dummy proc as in use by me */
	/* use volatile pointer to prevent code rearrangement */
	((volatile PGPROC *) dummyproc)->pid = MyProcPid;

	MyProc = dummyproc;
379 380 381

	SpinLockRelease(ProcStructLock);

382
	/*
383 384
	 * Initialize all fields of MyProc, except for the semaphore which was
	 * prepared for us by InitProcGlobal.
385 386
	 */
	SHMQueueElemInit(&(MyProc->links));
387
	MyProc->waitStatus = STATUS_OK;
388 389
	MyProc->xid = InvalidTransactionId;
	MyProc->xmin = InvalidTransactionId;
390
	MyProc->databaseId = InvalidOid;
391
	MyProc->roleId = InvalidOid;
392
	MyProc->inVacuum = false;
393 394 395 396
	MyProc->lwWaiting = false;
	MyProc->lwExclusive = false;
	MyProc->lwWaitLink = NULL;
	MyProc->waitLock = NULL;
397
	MyProc->waitProcLock = NULL;
398 399
	for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
		SHMQueueInit(&(MyProc->myProcLocks[i]));
400 401

	/*
B
Bruce Momjian 已提交
402
	 * We might be reusing a semaphore that belonged to a failed process. So
B
Bruce Momjian 已提交
403
	 * be careful and reinitialize its value here.	(This is not strictly
404
	 * necessary anymore, but seems like a good idea for cleanliness.)
405
	 */
406
	PGSemaphoreReset(&MyProc->sem);
407 408 409 410 411

	/*
	 * Arrange to clean up at process exit.
	 */
	on_shmem_exit(DummyProcKill, Int32GetDatum(proctype));
412 413
}

414 415 416 417 418 419 420 421 422 423
/*
 * Check whether there are at least N free PGPROC objects.
 *
 * Note: this is designed on the assumption that N will generally be small.
 */
bool
HaveNFreeProcs(int n)
{
	SHMEM_OFFSET offset;
	PGPROC	   *proc;
B
Bruce Momjian 已提交
424

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
	/* use volatile pointer to prevent code rearrangement */
	volatile PROC_HDR *procglobal = ProcGlobal;

	SpinLockAcquire(ProcStructLock);

	offset = procglobal->freeProcs;

	while (n > 0 && offset != INVALID_OFFSET)
	{
		proc = (PGPROC *) MAKE_PTR(offset);
		offset = proc->links.next;
		n--;
	}

	SpinLockRelease(ProcStructLock);

	return (n <= 0);
}

444 445 446
/*
 * Cancel any pending wait for lock, when aborting a transaction.
 *
447 448
 * Returns true if we had been waiting for a lock, else false.
 *
449
 * (Normally, this would only happen if we accept a cancel/die
450
 * interrupt while waiting; but an ereport(ERROR) while waiting is
451 452
 * within the realm of possibility, too.)
 */
453
bool
454 455
LockWaitCancel(void)
{
456 457
	LWLockId	partitionLock;

458
	/* Nothing to do if we weren't waiting for a lock */
459
	if (lockAwaited == NULL)
460 461
		return false;

462
	/* Turn off the deadlock timer, if it's still running (see ProcSleep) */
463
	disable_sig_alarm(false);
464 465

	/* Unlink myself from the wait queue, if on it (might not be anymore!) */
466
	partitionLock = LockHashPartitionLock(lockAwaited->hashcode);
467
	LWLockAcquire(partitionLock, LW_EXCLUSIVE);
468

469
	if (MyProc->links.next != INVALID_OFFSET)
470 471
	{
		/* We could not have been granted the lock yet */
472
		RemoveFromWaitQueue(MyProc, lockAwaited->hashcode);
473 474 475 476 477
	}
	else
	{
		/*
		 * Somebody kicked us off the lock queue already.  Perhaps they
B
Bruce Momjian 已提交
478 479 480
		 * granted us the lock, or perhaps they detected a deadlock. If they
		 * did grant us the lock, we'd better remember it in our local lock
		 * table.
481
		 */
482 483
		if (MyProc->waitStatus == STATUS_OK)
			GrantAwaitedLock();
484 485
	}

486
	lockAwaited = NULL;
487

488
	LWLockRelease(partitionLock);
H
Hiroshi Inoue 已提交
489

490
	/*
491
	 * We used to do PGSemaphoreReset() here to ensure that our proc's wait
B
Bruce Momjian 已提交
492 493 494 495 496 497
	 * semaphore is reset to zero.	This prevented a leftover wakeup signal
	 * from remaining in the semaphore if someone else had granted us the lock
	 * we wanted before we were able to remove ourselves from the wait-list.
	 * However, now that ProcSleep loops until waitStatus changes, a leftover
	 * wakeup signal isn't harmful, and it seems not worth expending cycles to
	 * get rid of a signal that most likely isn't there.
498
	 */
499 500

	/*
B
Bruce Momjian 已提交
501 502
	 * Return true even if we were kicked off the lock before we were able to
	 * remove ourselves.
503 504
	 */
	return true;
H
Hiroshi Inoue 已提交
505
}
506

507

508
/*
509
 * ProcReleaseLocks() -- release locks associated with current transaction
510
 *			at main transaction commit or abort
511 512 513 514 515 516
 *
 * At main transaction commit, we release all locks except session locks.
 * At main transaction abort, we release all locks including session locks;
 * this lets us clean up after a VACUUM FULL failure.
 *
 * At subtransaction commit, we don't release any locks (so this func is not
517
 * needed at all); we will defer the releasing to the parent transaction.
518
 * At subtransaction abort, we release all locks held by the subtransaction;
519 520
 * this is implemented by retail releasing of the locks under control of
 * the ResourceOwner mechanism.
521 522
 *
 * Note that user locks are not released in any case.
523 524
 */
void
525
ProcReleaseLocks(bool isCommit)
526
{
527 528
	if (!MyProc)
		return;
529 530 531
	/* If waiting, get off wait queue (should only be needed after error) */
	LockWaitCancel();
	/* Release locks */
532
	LockReleaseAll(DEFAULT_LOCKMETHOD, !isCommit);
533 534 535
}


536 537 538 539 540 541 542 543 544 545
/*
 * RemoveProcFromArray() -- Remove this process from the shared ProcArray.
 */
static void
RemoveProcFromArray(int code, Datum arg)
{
	Assert(MyProc != NULL);
	ProcArrayRemove(MyProc);
}

546 547
/*
 * ProcKill() -- Destroy the per-proc data structure for
548
 *		this process. Release any of its held LW locks.
549 550
 */
static void
551
ProcKill(int code, Datum arg)
552
{
553 554 555
	/* use volatile pointer to prevent code rearrangement */
	volatile PROC_HDR *procglobal = ProcGlobal;

556
	Assert(MyProc != NULL);
557

558
	/*
B
Bruce Momjian 已提交
559 560
	 * Release any LW locks I am holding.  There really shouldn't be any, but
	 * it's cheap to check again before we cut the knees off the LWLock
561
	 * facility by releasing our PGPROC ...
562
	 */
563
	LWLockReleaseAll();
564

565
	SpinLockAcquire(ProcStructLock);
566

J
Jan Wieck 已提交
567
	/* Return PGPROC structure (and semaphore) to freelist */
568 569
	MyProc->links.next = procglobal->freeProcs;
	procglobal->freeProcs = MAKE_OFFSET(MyProc);
570

J
Jan Wieck 已提交
571
	/* PGPROC struct isn't mine anymore */
572
	MyProc = NULL;
573

574 575 576
	/* Update shared estimate of spins_per_delay */
	procglobal->spins_per_delay = update_spins_per_delay(procglobal->spins_per_delay);

577 578 579 580
	SpinLockRelease(ProcStructLock);
}

/*
581
 * DummyProcKill() -- Cut-down version of ProcKill for dummy (bgwriter)
J
Jan Wieck 已提交
582
 *		processes.	The PGPROC and sema are not released, only marked
583 584 585
 *		as not-in-use.
 */
static void
586
DummyProcKill(int code, Datum arg)
587
{
B
Bruce Momjian 已提交
588 589
	int			proctype = DatumGetInt32(arg);
	PGPROC	   *dummyproc;
J
Jan Wieck 已提交
590

591
	Assert(proctype >= 0 && proctype < NUM_DUMMY_PROCS);
J
Jan Wieck 已提交
592

593
	dummyproc = &DummyProcs[proctype];
J
Jan Wieck 已提交
594

595
	Assert(MyProc == dummyproc);
596

597
	/* Release any LW locks I am holding (see notes above) */
598 599
	LWLockReleaseAll();

600 601
	SpinLockAcquire(ProcStructLock);

602
	/* Mark dummy proc no longer in use */
603 604
	MyProc->pid = 0;

J
Jan Wieck 已提交
605
	/* PGPROC struct isn't mine anymore */
606
	MyProc = NULL;
607 608 609 610 611

	/* Update shared estimate of spins_per_delay */
	ProcGlobal->spins_per_delay = update_spins_per_delay(ProcGlobal->spins_per_delay);

	SpinLockRelease(ProcStructLock);
612 613
}

614

615 616
/*
 * ProcQueue package: routines for putting processes to sleep
617
 *		and  waking them up
618 619 620 621 622 623 624 625
 */

/*
 * 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
 */
626
#ifdef NOT_USED
627
PROC_QUEUE *
628 629
ProcQueueAlloc(char *name)
{
630 631
	bool		found;
	PROC_QUEUE *queue = (PROC_QUEUE *)
B
Bruce Momjian 已提交
632
	ShmemInitStruct(name, sizeof(PROC_QUEUE), &found);
633 634

	if (!queue)
635
		return NULL;
636 637
	if (!found)
		ProcQueueInit(queue);
638
	return queue;
639
}
640
#endif
641 642 643 644 645

/*
 * ProcQueueInit -- initialize a shared memory process queue
 */
void
646
ProcQueueInit(PROC_QUEUE *queue)
647
{
648 649
	SHMQueueInit(&(queue->links));
	queue->size = 0;
650 651 652 653
}


/*
654
 * ProcSleep -- put a process to sleep on the specified lock
655
 *
656 657
 * Caller must have set MyProc->heldLocks to reflect locks already held
 * on the lockable object by this process (under all XIDs).
658
 *
659
 * The lock table's partition lock must be held at entry, and will be held
660
 * at exit.
661
 *
662
 * Result: STATUS_OK if we acquired the lock, STATUS_ERROR if not (deadlock).
663
 *
664
 * ASSUME: that no one will fiddle with the queue until after
665
 *		we release the partition lock.
666 667
 *
 * NOTES: The process queue is now a priority queue for locking.
668 669 670
 *
 * P() on the semaphore should put us to sleep.  The process
 * semaphore is normally zero, so when we try to acquire it, we sleep.
671 672
 */
int
673
ProcSleep(LOCALLOCK *locallock, LockMethod lockMethodTable)
674
{
675 676 677
	LOCKMODE	lockmode = locallock->tag.mode;
	LOCK	   *lock = locallock->lock;
	PROCLOCK   *proclock = locallock->proclock;
678 679
	uint32		hashcode = locallock->hashcode;
	LWLockId	partitionLock = LockHashPartitionLock(hashcode);
680
	PROC_QUEUE *waitQueue = &(lock->waitProcs);
681
	LOCKMASK	myHeldLocks = MyProc->heldLocks;
682
	bool		early_deadlock = false;
J
Jan Wieck 已提交
683
	PGPROC	   *proc;
684
	int			i;
685

686
	/*
687 688
	 * Determine where to add myself in the wait queue.
	 *
689 690 691 692
	 * Normally I should go at the end of the queue.  However, if I already
	 * hold locks that conflict with the request of any previous waiter, put
	 * myself in the queue just in front of the first such waiter. This is not
	 * a necessary step, since deadlock detection would move me to before that
B
Bruce Momjian 已提交
693 694
	 * waiter anyway; but it's relatively cheap to detect such a conflict
	 * immediately, and avoid delaying till deadlock timeout.
695
	 *
696 697
	 * Special case: if I find I should go in front of some waiter, check to
	 * see if I conflict with already-held locks or the requests before that
B
Bruce Momjian 已提交
698 699 700 701
	 * waiter.	If not, then just grant myself the requested lock immediately.
	 * This is the same as the test for immediate grant in LockAcquire, except
	 * we are only considering the part of the wait queue before my insertion
	 * point.
702 703
	 */
	if (myHeldLocks != 0)
V
Vadim B. Mikheev 已提交
704
	{
705
		LOCKMASK	aheadRequests = 0;
706

J
Jan Wieck 已提交
707
		proc = (PGPROC *) MAKE_PTR(waitQueue->links.next);
708
		for (i = 0; i < waitQueue->size; i++)
V
Vadim B. Mikheev 已提交
709
		{
710
			/* Must he wait for me? */
B
Bruce Momjian 已提交
711
			if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
V
Vadim B. Mikheev 已提交
712
			{
713
				/* Must I wait for him ? */
B
Bruce Momjian 已提交
714
				if (lockMethodTable->conflictTab[lockmode] & proc->heldLocks)
715
				{
716
					/*
B
Bruce Momjian 已提交
717 718 719 720 721
					 * Yes, so we have a deadlock.	Easiest way to clean up
					 * correctly is to call RemoveFromWaitQueue(), but we
					 * can't do that until we are *on* the wait queue. So, set
					 * a flag to check below, and break out of loop.  Also,
					 * record deadlock info for later message.
722
					 */
723
					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
724 725
					early_deadlock = true;
					break;
726
				}
727
				/* I must go before this waiter.  Check special case. */
B
Bruce Momjian 已提交
728
				if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
729 730 731
					LockCheckConflicts(lockMethodTable,
									   lockmode,
									   lock,
732
									   proclock,
733
									   MyProc) == STATUS_OK)
734
				{
735
					/* Skip the wait and just grant myself the lock. */
736
					GrantLock(lock, proclock, lockmode);
737
					GrantAwaitedLock();
738
					return STATUS_OK;
739 740
				}
				/* Break out of loop to put myself before him */
V
Vadim B. Mikheev 已提交
741
				break;
742
			}
743
			/* Nope, so advance to next waiter */
744
			aheadRequests |= LOCKBIT_ON(proc->waitLockMode);
J
Jan Wieck 已提交
745
			proc = (PGPROC *) MAKE_PTR(proc->links.next);
V
Vadim B. Mikheev 已提交
746
		}
B
Bruce Momjian 已提交
747

748
		/*
B
Bruce Momjian 已提交
749 750
		 * If we fall out of loop normally, proc points to waitQueue head, so
		 * we will insert at tail of queue as desired.
751
		 */
752 753 754 755
	}
	else
	{
		/* I hold no locks, so I can't push in front of anyone. */
J
Jan Wieck 已提交
756
		proc = (PGPROC *) &(waitQueue->links);
V
Vadim B. Mikheev 已提交
757
	}
758

759
	/*
B
Bruce Momjian 已提交
760
	 * Insert self into queue, ahead of the given proc (or at tail of queue).
761
	 */
762
	SHMQueueInsertBefore(&(proc->links), &(MyProc->links));
B
Bruce Momjian 已提交
763
	waitQueue->size++;
764

765
	lock->waitMask |= LOCKBIT_ON(lockmode);
766

J
Jan Wieck 已提交
767
	/* Set up wait information in PGPROC object, too */
768
	MyProc->waitLock = lock;
769
	MyProc->waitProcLock = proclock;
770 771
	MyProc->waitLockMode = lockmode;

772
	MyProc->waitStatus = STATUS_WAITING;
773 774

	/*
B
Bruce Momjian 已提交
775 776 777
	 * If we detected deadlock, give up without waiting.  This must agree with
	 * CheckDeadLock's recovery code, except that we shouldn't release the
	 * semaphore since we haven't tried to lock it yet.
778 779 780
	 */
	if (early_deadlock)
	{
781
		RemoveFromWaitQueue(MyProc, hashcode);
782 783
		return STATUS_ERROR;
	}
784

785
	/* mark that we are waiting for a lock */
786
	lockAwaited = locallock;
787

788
	/*
789
	 * Release the lock table's partition lock.
790
	 *
791
	 * NOTE: this may also cause us to exit critical-section state, possibly
B
Bruce Momjian 已提交
792 793
	 * allowing a cancel/die interrupt to be accepted. This is OK because we
	 * have recorded the fact that we are waiting for a lock, and so
794
	 * LockWaitCancel will clean up if cancel/die happens.
795
	 */
796
	LWLockRelease(partitionLock);
797

798
	/*
B
Bruce Momjian 已提交
799 800 801 802
	 * Set timer so we can wake up after awhile and check for a deadlock. If a
	 * deadlock is detected, the handler releases the process's semaphore and
	 * sets MyProc->waitStatus = STATUS_ERROR, allowing us to know that we
	 * must report failure rather than success.
803
	 *
804 805
	 * By delaying the check until we've waited for a bit, we can avoid
	 * running the rather expensive deadlock-check code in most cases.
806
	 */
807
	if (!enable_sig_alarm(DeadlockTimeout, false))
808
		elog(FATAL, "could not set timer for process wakeup");
809

810
	/*
811
	 * If someone wakes us between LWLockRelease and PGSemaphoreLock,
B
Bruce Momjian 已提交
812
	 * PGSemaphoreLock will not block.	The wakeup is "saved" by the semaphore
B
Bruce Momjian 已提交
813 814 815 816 817
	 * implementation.	While this is normally good, there are cases where a
	 * saved wakeup might be leftover from a previous operation (for example,
	 * we aborted ProcWaitForSignal just before someone did ProcSendSignal).
	 * So, loop to wait again if the waitStatus shows we haven't been granted
	 * nor denied the lock yet.
818
	 *
819 820 821 822 823 824 825
	 * We pass interruptOK = true, which eliminates a window in which
	 * cancel/die interrupts would be held off undesirably.  This is a promise
	 * that we don't mind losing control to a cancel/die interrupt here.  We
	 * don't, because we have no shared-state-change work to do after being
	 * granted the lock (the grantor did it all).  We do have to worry about
	 * updating the locallock table, but if we lose control to an error,
	 * LockWaitCancel will fix that up.
826
	 */
B
Bruce Momjian 已提交
827 828
	do
	{
829 830
		PGSemaphoreLock(&MyProc->sem, true);
	} while (MyProc->waitStatus == STATUS_WAITING);
831

832
	/*
833
	 * Disable the timer, if it's still running
B
Bruce Momjian 已提交
834
	 */
835
	if (!disable_sig_alarm(false))
836
		elog(FATAL, "could not disable timer for process wakeup");
B
Bruce Momjian 已提交
837

838
	/*
B
Bruce Momjian 已提交
839 840 841
	 * Re-acquire the lock table's partition lock.  We have to do this to hold
	 * off cancel/die interrupts before we can mess with lockAwaited (else we
	 * might have a missed or duplicated locallock update).
842
	 */
843
	LWLockAcquire(partitionLock, LW_EXCLUSIVE);
844 845 846

	/*
	 * We no longer want LockWaitCancel to do anything.
847
	 */
848
	lockAwaited = NULL;
849

850
	/*
851
	 * If we got the lock, be sure to remember it in the locallock table.
852
	 */
853
	if (MyProc->waitStatus == STATUS_OK)
854
		GrantAwaitedLock();
855

856 857 858 859
	/*
	 * We don't have to do anything else, because the awaker did all the
	 * necessary update of the lock table and MyProc.
	 */
860
	return MyProc->waitStatus;
861 862 863 864 865 866
}


/*
 * ProcWakeup -- wake up a process by releasing its private semaphore.
 *
867
 *	 Also remove the process from the wait queue and set its links invalid.
868
 *	 RETURN: the next process in the wait queue.
869
 *
870 871
 * The appropriate lock partition lock must be held by caller.
 *
872 873 874
 * XXX: presently, this code is only used for the "success" case, and only
 * works correctly for that case.  To clean up in failure case, would need
 * to twiddle the lock's request counts too --- see RemoveFromWaitQueue.
875
 * Hence, in practice the waitStatus parameter must be STATUS_OK.
876
 */
J
Jan Wieck 已提交
877
PGPROC *
878
ProcWakeup(PGPROC *proc, int waitStatus)
879
{
J
Jan Wieck 已提交
880
	PGPROC	   *retProc;
881

882
	/* Proc should be sleeping ... */
883 884
	if (proc->links.prev == INVALID_OFFSET ||
		proc->links.next == INVALID_OFFSET)
885
		return NULL;
886
	Assert(proc->waitStatus == STATUS_WAITING);
887

888
	/* Save next process before we zap the list link */
J
Jan Wieck 已提交
889
	retProc = (PGPROC *) MAKE_PTR(proc->links.next);
890

891
	/* Remove process from wait queue */
892
	SHMQueueDelete(&(proc->links));
893
	(proc->waitLock->waitProcs.size)--;
894

895 896
	/* Clean up process' state and pass it the ok/fail signal */
	proc->waitLock = NULL;
897
	proc->waitProcLock = NULL;
898
	proc->waitStatus = waitStatus;
899

900
	/* And awaken it */
901
	PGSemaphoreUnlock(&proc->sem);
902 903

	return retProc;
904 905 906 907
}

/*
 * ProcLockWakeup -- routine for waking up processes when a lock is
908 909
 *		released (or a prior waiter is aborted).  Scan all waiters
 *		for lock, waken any that are no longer blocked.
910 911
 *
 * The appropriate lock partition lock must be held by caller.
912
 */
913
void
914
ProcLockWakeup(LockMethod lockMethodTable, LOCK *lock)
915
{
916 917
	PROC_QUEUE *waitQueue = &(lock->waitProcs);
	int			queue_size = waitQueue->size;
J
Jan Wieck 已提交
918
	PGPROC	   *proc;
919
	LOCKMASK	aheadRequests = 0;
M
 
Marc G. Fournier 已提交
920

921
	Assert(queue_size >= 0);
922

923 924
	if (queue_size == 0)
		return;
925

J
Jan Wieck 已提交
926
	proc = (PGPROC *) MAKE_PTR(waitQueue->links.next);
927

928 929
	while (queue_size-- > 0)
	{
B
Bruce Momjian 已提交
930
		LOCKMODE	lockmode = proc->waitLockMode;
M
 
Marc G. Fournier 已提交
931 932

		/*
B
Bruce Momjian 已提交
933 934
		 * Waken if (a) doesn't conflict with requests of earlier waiters, and
		 * (b) doesn't conflict with already-held locks.
M
 
Marc G. Fournier 已提交
935
		 */
B
Bruce Momjian 已提交
936
		if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
937 938 939
			LockCheckConflicts(lockMethodTable,
							   lockmode,
							   lock,
940
							   proc->waitProcLock,
941
							   proc) == STATUS_OK)
M
 
Marc G. Fournier 已提交
942
		{
943
			/* OK to waken */
944
			GrantLock(lock, proc->waitProcLock, lockmode);
945
			proc = ProcWakeup(proc, STATUS_OK);
B
Bruce Momjian 已提交
946

947
			/*
B
Bruce Momjian 已提交
948 949 950
			 * ProcWakeup removes proc from the lock's waiting process queue
			 * and returns the next proc in chain; don't use proc's next-link,
			 * because it's been cleared.
951
			 */
M
 
Marc G. Fournier 已提交
952
		}
953
		else
954
		{
B
Bruce Momjian 已提交
955
			/*
B
Bruce Momjian 已提交
956
			 * Cannot wake this guy. Remember his request for later checks.
B
Bruce Momjian 已提交
957
			 */
958
			aheadRequests |= LOCKBIT_ON(lockmode);
J
Jan Wieck 已提交
959
			proc = (PGPROC *) MAKE_PTR(proc->links.next);
960
		}
M
 
Marc G. Fournier 已提交
961
	}
962 963

	Assert(waitQueue->size >= 0);
964 965
}

966 967 968
/*
 * CheckDeadLock
 *
969
 * We only get to this routine if we got SIGALRM after DeadlockTimeout
970 971 972 973
 * while waiting for a lock to be released by some other process.  Look
 * to see if there's a deadlock; if not, just return and continue waiting.
 * If we have a real deadlock, remove ourselves from the lock's wait queue
 * and signal an error to ProcSleep.
974
 */
975
static void
976
CheckDeadLock(void)
977
{
978 979
	int			i;

980
	/*
B
Bruce Momjian 已提交
981 982
	 * Acquire exclusive lock on the entire shared lock data structures. Must
	 * grab LWLocks in partition-number order to avoid LWLock deadlock.
983 984 985 986 987 988
	 *
	 * Note that the deadlock check interrupt had better not be enabled
	 * anywhere that this process itself holds lock partition locks, else this
	 * will wait forever.  Also note that LWLockAcquire creates a critical
	 * section, so that this routine cannot be interrupted by cancel/die
	 * interrupts.
989
	 */
990 991
	for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
		LWLockAcquire(FirstLockMgrLock + i, LW_EXCLUSIVE);
992

993
	/*
994 995
	 * Check to see if we've been awoken by anyone in the interim.
	 *
996 997 998
	 * 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.
999
	 *
1000
	 * We check by looking to see if we've been unlinked from the wait queue.
B
Bruce Momjian 已提交
1001
	 * This is quicker than checking our semaphore's state, since no kernel
1002
	 * call is needed, and it is safe because we hold the lock partition lock.
1003 1004 1005
	 */
	if (MyProc->links.prev == INVALID_OFFSET ||
		MyProc->links.next == INVALID_OFFSET)
1006
		goto check_done;
1007

1008
#ifdef LOCK_DEBUG
B
Bruce Momjian 已提交
1009 1010
	if (Debug_deadlocks)
		DumpAllLocks();
1011 1012
#endif

1013
	if (!DeadLockCheck(MyProc))
B
Bruce Momjian 已提交
1014
	{
1015
		/* No deadlock, so keep waiting */
1016
		goto check_done;
B
Bruce Momjian 已提交
1017 1018
	}

1019
	/*
1020 1021
	 * Oops.  We have a deadlock.
	 *
B
Bruce Momjian 已提交
1022
	 * Get this process out of wait state.	(Note: we could do this more
1023 1024 1025
	 * efficiently by relying on lockAwaited, but use this coding to preserve
	 * the flexibility to kill some other transaction than the one detecting
	 * the deadlock.)
1026 1027 1028
	 *
	 * RemoveFromWaitQueue sets MyProc->waitStatus to STATUS_ERROR, so
	 * ProcSleep will report an error after we return from the signal handler.
1029
	 */
1030
	Assert(MyProc->waitLock != NULL);
1031
	RemoveFromWaitQueue(MyProc, LockTagHashCode(&(MyProc->waitLock->tag)));
1032

1033 1034 1035
	/*
	 * Unlock my semaphore so that the interrupted ProcSleep() call can
	 * finish.
1036
	 */
1037
	PGSemaphoreUnlock(&MyProc->sem);
1038

1039
	/*
B
Bruce Momjian 已提交
1040 1041 1042 1043 1044 1045 1046 1047
	 * We're done here.  Transaction abort caused by the error that ProcSleep
	 * will raise will cause any other locks we hold to be released, thus
	 * allowing other processes to wake up; we don't need to do that here.
	 * NOTE: an exception is that releasing locks we hold doesn't consider the
	 * possibility of waiters that were blocked behind us on the lock we just
	 * failed to get, and might now be wakable because we're not in front of
	 * them anymore.  However, RemoveFromWaitQueue took care of waking up any
	 * such processes.
1048
	 */
1049 1050

	/*
B
Bruce Momjian 已提交
1051 1052
	 * Release locks acquired at head of routine.  Order is not critical, so
	 * do it back-to-front to avoid waking another CheckDeadLock instance
1053 1054 1055
	 * before it can get all the locks.
	 */
check_done:
B
Bruce Momjian 已提交
1056
	for (i = NUM_LOCK_PARTITIONS; --i >= 0;)
1057
		LWLockRelease(FirstLockMgrLock + i);
1058 1059 1060
}


1061 1062 1063 1064 1065 1066
/*
 * ProcWaitForSignal - wait for a signal from another backend.
 *
 * This can share the semaphore normally used for waiting for locks,
 * since a backend could never be waiting for a lock and a signal at
 * the same time.  As with locks, it's OK if the signal arrives just
B
Bruce Momjian 已提交
1067
 * before we actually reach the waiting state.	Also as with locks,
1068 1069
 * it's necessary that the caller be robust against bogus wakeups:
 * always check that the desired state has occurred, and wait again
B
Bruce Momjian 已提交
1070
 * if not.	This copes with possible "leftover" wakeups.
1071 1072 1073 1074
 */
void
ProcWaitForSignal(void)
{
1075
	PGSemaphoreLock(&MyProc->sem, true);
1076 1077 1078
}

/*
1079
 * ProcSendSignal - send a signal to a backend identified by PID
1080 1081
 */
void
1082
ProcSendSignal(int pid)
1083
{
1084
	PGPROC	   *proc = BackendPidGetProc(pid);
1085 1086

	if (proc != NULL)
1087
		PGSemaphoreUnlock(&proc->sem);
1088 1089 1090
}


1091 1092 1093 1094 1095 1096 1097 1098 1099
/*****************************************************************************
 * SIGALRM interrupt support
 *
 * Maybe these should be in pqsignal.c?
 *****************************************************************************/

/*
 * Enable the SIGALRM interrupt to fire after the specified delay
 *
1100
 * Delay is given in milliseconds.	Caller should be sure a SIGALRM
1101 1102
 * signal handler is installed before this is called.
 *
1103 1104
 * This code properly handles nesting of deadlock timeout alarms within
 * statement timeout alarms.
1105
 *
1106 1107 1108
 * Returns TRUE if okay, FALSE on failure.
 */
bool
1109
enable_sig_alarm(int delayms, bool is_statement_timeout)
1110
{
1111
	TimestampTz fin_time;
1112
	struct itimerval timeval;
1113

1114 1115
	if (is_statement_timeout)
	{
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
		/*
		 * Begin statement-level timeout
		 *
		 * Note that we compute statement_fin_time with reference to the
		 * statement_timestamp, but apply the specified delay without any
		 * correction; that is, we ignore whatever time has elapsed since
		 * statement_timestamp was set.  In the normal case only a small
		 * interval will have elapsed and so this doesn't matter, but there
		 * are corner cases (involving multi-statement query strings with
		 * embedded COMMIT or ROLLBACK) where we might re-initialize the
B
Bruce Momjian 已提交
1126 1127 1128 1129
		 * statement timeout long after initial receipt of the message. In
		 * such cases the enforcement of the statement timeout will be a bit
		 * inconsistent.  This annoyance is judged not worth the cost of
		 * performing an additional gettimeofday() here.
1130
		 */
1131
		Assert(!deadlock_timeout_active);
1132 1133
		fin_time = GetCurrentStatementStartTimestamp();
		fin_time = TimestampTzPlusMilliseconds(fin_time, delayms);
1134
		statement_fin_time = fin_time;
1135
		cancel_from_timeout = false;
1136
		statement_timeout_active = true;
1137 1138 1139 1140 1141 1142
	}
	else if (statement_timeout_active)
	{
		/*
		 * Begin deadlock timeout with statement-level timeout active
		 *
1143 1144 1145 1146
		 * Here, we want to interrupt at the closer of the two timeout times.
		 * If fin_time >= statement_fin_time then we need not touch the
		 * existing timer setting; else set up to interrupt at the deadlock
		 * timeout time.
1147 1148 1149
		 *
		 * NOTE: in this case it is possible that this routine will be
		 * interrupted by the previously-set timer alarm.  This is okay
B
Bruce Momjian 已提交
1150 1151 1152
		 * because the signal handler will do only what it should do according
		 * to the state variables.	The deadlock checker may get run earlier
		 * than normal, but that does no harm.
1153
		 */
1154 1155
		fin_time = GetCurrentTimestamp();
		fin_time = TimestampTzPlusMilliseconds(fin_time, delayms);
1156
		deadlock_timeout_active = true;
1157
		if (fin_time >= statement_fin_time)
1158 1159 1160 1161 1162 1163 1164
			return true;
	}
	else
	{
		/* Begin deadlock timeout with no statement-level timeout */
		deadlock_timeout_active = true;
	}
1165

1166
	/* If we reach here, okay to set the timer interrupt */
1167
	MemSet(&timeval, 0, sizeof(struct itimerval));
1168 1169
	timeval.it_value.tv_sec = delayms / 1000;
	timeval.it_value.tv_usec = (delayms % 1000) * 1000;
1170
	if (setitimer(ITIMER_REAL, &timeval, NULL))
1171
		return false;
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
	return true;
}

/*
 * Cancel the SIGALRM timer, either for a deadlock timeout or a statement
 * timeout.  If a deadlock timeout is canceled, any active statement timeout
 * remains in force.
 *
 * Returns TRUE if okay, FALSE on failure.
 */
bool
disable_sig_alarm(bool is_statement_timeout)
{
	/*
	 * Always disable the interrupt if it is active; this avoids being
	 * interrupted by the signal handler and thereby possibly getting
	 * confused.
	 *
	 * We will re-enable the interrupt if necessary in CheckStatementTimeout.
	 */
	if (statement_timeout_active || deadlock_timeout_active)
1193
	{
1194
		struct itimerval timeval;
1195

1196
		MemSet(&timeval, 0, sizeof(struct itimerval));
1197
		if (setitimer(ITIMER_REAL, &timeval, NULL))
1198
		{
1199 1200 1201
			statement_timeout_active = false;
			cancel_from_timeout = false;
			deadlock_timeout_active = false;
1202 1203
			return false;
		}
1204 1205
	}

1206 1207 1208 1209
	/* Always cancel deadlock timeout, in case this is error cleanup */
	deadlock_timeout_active = false;

	/* Cancel or reschedule statement timeout */
1210
	if (is_statement_timeout)
1211
	{
1212
		statement_timeout_active = false;
1213 1214
		cancel_from_timeout = false;
	}
1215 1216 1217 1218 1219
	else if (statement_timeout_active)
	{
		if (!CheckStatementTimeout())
			return false;
	}
1220 1221 1222
	return true;
}

1223

1224
/*
1225 1226 1227
 * Check for statement timeout.  If the timeout time has come,
 * trigger a query-cancel interrupt; if not, reschedule the SIGALRM
 * interrupt to occur at the right time.
1228
 *
1229
 * Returns true if okay, false if failed to set the interrupt.
1230
 */
1231 1232
static bool
CheckStatementTimeout(void)
1233
{
1234
	TimestampTz now;
B
Bruce Momjian 已提交
1235

1236 1237 1238
	if (!statement_timeout_active)
		return true;			/* do nothing if not active */

1239
	now = GetCurrentTimestamp();
1240

1241
	if (now >= statement_fin_time)
1242
	{
1243 1244
		/* Time to die */
		statement_timeout_active = false;
1245
		cancel_from_timeout = true;
1246 1247 1248 1249
#ifdef HAVE_SETSID
		/* try to signal whole process group */
		kill(-MyProcPid, SIGINT);
#endif
1250
		kill(MyProcPid, SIGINT);
1251 1252 1253 1254
	}
	else
	{
		/* Not time yet, so (re)schedule the interrupt */
1255 1256
		long		secs;
		int			usecs;
1257 1258
		struct itimerval timeval;

1259 1260
		TimestampDifference(now, statement_fin_time,
							&secs, &usecs);
B
Bruce Momjian 已提交
1261

1262 1263 1264 1265 1266 1267
		/*
		 * It's possible that the difference is less than a microsecond;
		 * ensure we don't cancel, rather than set, the interrupt.
		 */
		if (secs == 0 && usecs == 0)
			usecs = 1;
1268
		MemSet(&timeval, 0, sizeof(struct itimerval));
1269 1270
		timeval.it_value.tv_sec = secs;
		timeval.it_value.tv_usec = usecs;
1271
		if (setitimer(ITIMER_REAL, &timeval, NULL))
1272 1273 1274
			return false;
	}

1275 1276
	return true;
}
1277 1278 1279


/*
1280 1281 1282 1283 1284 1285
 * Signal handler for SIGALRM
 *
 * Process deadlock check and/or statement timeout check, as needed.
 * To avoid various edge cases, we must be careful to do nothing
 * when there is nothing to be done.  We also need to be able to
 * reschedule the timer interrupt if called before end of statement.
1286 1287 1288 1289
 */
void
handle_sig_alarm(SIGNAL_ARGS)
{
1290 1291 1292
	int			save_errno = errno;

	if (deadlock_timeout_active)
1293
	{
1294
		deadlock_timeout_active = false;
1295 1296
		CheckDeadLock();
	}
1297 1298 1299 1300 1301

	if (statement_timeout_active)
		(void) CheckStatementTimeout();

	errno = save_errno;
1302
}