proc.c 37.2 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * proc.c
4
 *	  routines to manage per-process shared memory data structure
5
 *
6
 * Portions Copyright (c) 1996-2007, 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.183 2007/01/16 13:28:56 alvherre 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 "postmaster/autovacuum.h"
42
#include "storage/ipc.h"
43
#include "storage/proc.h"
44
#include "storage/procarray.h"
45
#include "storage/spin.h"
46

47

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

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

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

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

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

71 72 73
/* 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;
74
volatile bool cancel_from_timeout = false;
B
Bruce Momjian 已提交
75

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


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

V
Vadim B. Mikheev 已提交
85

86 87 88
/*
 * Report shared-memory space needed by InitProcGlobal.
 */
89
Size
90
ProcGlobalShmemSize(void)
91
{
92 93 94 95 96 97 98 99 100 101
	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));
102 103 104 105

	return size;
}

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

116 117
/*
 * InitProcGlobal -
118 119
 *	  Initialize the global process table during postmaster or standalone
 *	  backend startup.
120
 *
121
 *	  We also create all the per-process semaphores we will need to support
122 123 124 125 126 127 128 129 130
 *	  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.
131 132 133 134
 *
 *	  Another reason for creating semaphores here is that the semaphore
 *	  implementation typically requires us to create semaphores in the
 *	  postmaster, not in backends.
135 136 137 138
 *
 * 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.
139 140
 */
void
141
InitProcGlobal(void)
142
{
143 144 145
	PGPROC	   *procs;
	int			i;
	bool		found;
146

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

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

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

166
	ProcGlobal->spins_per_delay = DEFAULT_SPINS_PER_DELAY;
167

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
	/*
	 * 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]);
	}
183

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

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

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

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

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

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

226 227
	set_spins_per_delay(procglobal->spins_per_delay);

228
	myOffset = procglobal->freeProcs;
229 230

	if (myOffset != INVALID_OFFSET)
231
	{
J
Jan Wieck 已提交
232
		MyProc = (PGPROC *) MAKE_PTR(myOffset);
233
		procglobal->freeProcs = MyProc->links.next;
234
		SpinLockRelease(ProcStructLock);
235 236 237 238
	}
	else
	{
		/*
B
Bruce Momjian 已提交
239 240 241
		 * 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.
242
		 */
243
		SpinLockRelease(ProcStructLock);
244 245 246
		ereport(FATAL,
				(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
				 errmsg("sorry, too many clients already")));
247
	}
248

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

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

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

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

290 291 292 293 294 295 296 297 298 299 300 301 302
/*
 * 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 已提交
303 304 305
	 * 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.)
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
	 */
	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);
}

321 322 323
/*
 * InitDummyProcess -- create a dummy per-process data structure
 *
324 325
 * 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
326
 * and sema that are assigned are one of the extra ones created during
327
 * InitProcGlobal.
328 329
 *
 * Dummy processes are presently not expected to wait for real (lockmgr)
330 331
 * locks, so we need not set up the deadlock checker.  They are never added
 * to the ProcArray or the sinval messaging mechanism, either.
332 333
 */
void
334
InitDummyProcess(void)
335
{
B
Bruce Momjian 已提交
336
	PGPROC	   *dummyproc;
337
	int			proctype;
338
	int			i;
J
Jan Wieck 已提交
339

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

	if (MyProc != NULL)
348
		elog(ERROR, "you already exist");
349

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

	set_spins_per_delay(ProcGlobal->spins_per_delay);

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

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

	MyProc = dummyproc;
381 382 383

	SpinLockRelease(ProcStructLock);

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

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

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

417 418 419 420 421 422 423 424 425 426
/*
 * 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 已提交
427

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
	/* 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);
}

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

461
	/* Nothing to do if we weren't waiting for a lock */
462
	if (lockAwaited == NULL)
463 464
		return false;

465
	/* Turn off the deadlock timer, if it's still running (see ProcSleep) */
466
	disable_sig_alarm(false);
467 468

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

472
	if (MyProc->links.next != INVALID_OFFSET)
473 474
	{
		/* We could not have been granted the lock yet */
475
		RemoveFromWaitQueue(MyProc, lockAwaited->hashcode);
476 477 478 479 480
	}
	else
	{
		/*
		 * Somebody kicked us off the lock queue already.  Perhaps they
B
Bruce Momjian 已提交
481 482 483
		 * 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.
484
		 */
485 486
		if (MyProc->waitStatus == STATUS_OK)
			GrantAwaitedLock();
487 488
	}

489
	lockAwaited = NULL;
490

491
	LWLockRelease(partitionLock);
H
Hiroshi Inoue 已提交
492

493
	/*
494
	 * We used to do PGSemaphoreReset() here to ensure that our proc's wait
B
Bruce Momjian 已提交
495 496 497 498 499 500
	 * 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.
501
	 */
502 503

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

510

511
/*
512
 * ProcReleaseLocks() -- release locks associated with current transaction
513
 *			at main transaction commit or abort
514 515 516 517 518 519
 *
 * 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
520
 * needed at all); we will defer the releasing to the parent transaction.
521
 * At subtransaction abort, we release all locks held by the subtransaction;
522 523
 * this is implemented by retail releasing of the locks under control of
 * the ResourceOwner mechanism.
524 525
 *
 * Note that user locks are not released in any case.
526 527
 */
void
528
ProcReleaseLocks(bool isCommit)
529
{
530 531
	if (!MyProc)
		return;
532 533 534
	/* If waiting, get off wait queue (should only be needed after error) */
	LockWaitCancel();
	/* Release locks */
535
	LockReleaseAll(DEFAULT_LOCKMETHOD, !isCommit);
536 537 538
}


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

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

559
	Assert(MyProc != NULL);
560

561
	/*
B
Bruce Momjian 已提交
562 563
	 * 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
564
	 * facility by releasing our PGPROC ...
565
	 */
566
	LWLockReleaseAll();
567

568
	SpinLockAcquire(ProcStructLock);
569

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

J
Jan Wieck 已提交
574
	/* PGPROC struct isn't mine anymore */
575
	MyProc = NULL;
576

577 578 579
	/* Update shared estimate of spins_per_delay */
	procglobal->spins_per_delay = update_spins_per_delay(procglobal->spins_per_delay);

580 581 582 583
	SpinLockRelease(ProcStructLock);
}

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

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

596
	dummyproc = &DummyProcs[proctype];
J
Jan Wieck 已提交
597

598
	Assert(MyProc == dummyproc);
599

600
	/* Release any LW locks I am holding (see notes above) */
601 602
	LWLockReleaseAll();

603 604
	SpinLockAcquire(ProcStructLock);

605
	/* Mark dummy proc no longer in use */
606 607
	MyProc->pid = 0;

J
Jan Wieck 已提交
608
	/* PGPROC struct isn't mine anymore */
609
	MyProc = NULL;
610 611 612 613 614

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

	SpinLockRelease(ProcStructLock);
615 616
}

617

618 619
/*
 * ProcQueue package: routines for putting processes to sleep
620
 *		and  waking them up
621 622 623 624 625 626 627 628
 */

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

	if (!queue)
638
		return NULL;
639 640
	if (!found)
		ProcQueueInit(queue);
641
	return queue;
642
}
643
#endif
644 645 646 647 648

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


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

689
	/*
690 691
	 * Determine where to add myself in the wait queue.
	 *
692 693 694 695
	 * 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 已提交
696 697
	 * waiter anyway; but it's relatively cheap to detect such a conflict
	 * immediately, and avoid delaying till deadlock timeout.
698
	 *
699 700
	 * 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 已提交
701 702 703 704
	 * 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.
705 706
	 */
	if (myHeldLocks != 0)
V
Vadim B. Mikheev 已提交
707
	{
708
		LOCKMASK	aheadRequests = 0;
709

J
Jan Wieck 已提交
710
		proc = (PGPROC *) MAKE_PTR(waitQueue->links.next);
711
		for (i = 0; i < waitQueue->size; i++)
V
Vadim B. Mikheev 已提交
712
		{
713
			/* Must he wait for me? */
B
Bruce Momjian 已提交
714
			if (lockMethodTable->conflictTab[proc->waitLockMode] & myHeldLocks)
V
Vadim B. Mikheev 已提交
715
			{
716
				/* Must I wait for him ? */
B
Bruce Momjian 已提交
717
				if (lockMethodTable->conflictTab[lockmode] & proc->heldLocks)
718
				{
719
					/*
B
Bruce Momjian 已提交
720 721 722 723 724
					 * 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.
725
					 */
726
					RememberSimpleDeadLock(MyProc, lockmode, lock, proc);
727 728
					early_deadlock = true;
					break;
729
				}
730
				/* I must go before this waiter.  Check special case. */
B
Bruce Momjian 已提交
731
				if ((lockMethodTable->conflictTab[lockmode] & aheadRequests) == 0 &&
732 733 734
					LockCheckConflicts(lockMethodTable,
									   lockmode,
									   lock,
735
									   proclock,
736
									   MyProc) == STATUS_OK)
737
				{
738
					/* Skip the wait and just grant myself the lock. */
739
					GrantLock(lock, proclock, lockmode);
740
					GrantAwaitedLock();
741
					return STATUS_OK;
742 743
				}
				/* Break out of loop to put myself before him */
V
Vadim B. Mikheev 已提交
744
				break;
745
			}
746
			/* Nope, so advance to next waiter */
747
			aheadRequests |= LOCKBIT_ON(proc->waitLockMode);
J
Jan Wieck 已提交
748
			proc = (PGPROC *) MAKE_PTR(proc->links.next);
V
Vadim B. Mikheev 已提交
749
		}
B
Bruce Momjian 已提交
750

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

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

768
	lock->waitMask |= LOCKBIT_ON(lockmode);
769

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

775
	MyProc->waitStatus = STATUS_WAITING;
776 777

	/*
B
Bruce Momjian 已提交
778 779 780
	 * 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.
781 782 783
	 */
	if (early_deadlock)
	{
784
		RemoveFromWaitQueue(MyProc, hashcode);
785 786
		return STATUS_ERROR;
	}
787

788
	/* mark that we are waiting for a lock */
789
	lockAwaited = locallock;
790

791
	/*
792
	 * Release the lock table's partition lock.
793
	 *
794
	 * NOTE: this may also cause us to exit critical-section state, possibly
B
Bruce Momjian 已提交
795 796
	 * 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
797
	 * LockWaitCancel will clean up if cancel/die happens.
798
	 */
799
	LWLockRelease(partitionLock);
800

801
	/*
B
Bruce Momjian 已提交
802 803 804 805
	 * 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.
806
	 *
807 808
	 * By delaying the check until we've waited for a bit, we can avoid
	 * running the rather expensive deadlock-check code in most cases.
809
	 */
810
	if (!enable_sig_alarm(DeadlockTimeout, false))
811
		elog(FATAL, "could not set timer for process wakeup");
812

813
	/*
814
	 * If someone wakes us between LWLockRelease and PGSemaphoreLock,
B
Bruce Momjian 已提交
815
	 * PGSemaphoreLock will not block.	The wakeup is "saved" by the semaphore
B
Bruce Momjian 已提交
816 817 818 819 820
	 * 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.
821
	 *
822 823 824 825 826 827 828
	 * 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.
829
	 */
B
Bruce Momjian 已提交
830 831
	do
	{
832 833
		PGSemaphoreLock(&MyProc->sem, true);
	} while (MyProc->waitStatus == STATUS_WAITING);
834

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

841
	/*
B
Bruce Momjian 已提交
842 843 844
	 * 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).
845
	 */
846
	LWLockAcquire(partitionLock, LW_EXCLUSIVE);
847 848 849

	/*
	 * We no longer want LockWaitCancel to do anything.
850
	 */
851
	lockAwaited = NULL;
852

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

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


/*
 * ProcWakeup -- wake up a process by releasing its private semaphore.
 *
870
 *	 Also remove the process from the wait queue and set its links invalid.
871
 *	 RETURN: the next process in the wait queue.
872
 *
873 874
 * The appropriate lock partition lock must be held by caller.
 *
875 876 877
 * 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.
878
 * Hence, in practice the waitStatus parameter must be STATUS_OK.
879
 */
J
Jan Wieck 已提交
880
PGPROC *
881
ProcWakeup(PGPROC *proc, int waitStatus)
882
{
J
Jan Wieck 已提交
883
	PGPROC	   *retProc;
884

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

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

894
	/* Remove process from wait queue */
895
	SHMQueueDelete(&(proc->links));
896
	(proc->waitLock->waitProcs.size)--;
897

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

903
	/* And awaken it */
904
	PGSemaphoreUnlock(&proc->sem);
905 906

	return retProc;
907 908 909 910
}

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

924
	Assert(queue_size >= 0);
925

926 927
	if (queue_size == 0)
		return;
928

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

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

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

950
			/*
B
Bruce Momjian 已提交
951 952 953
			 * 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.
954
			 */
M
 
Marc G. Fournier 已提交
955
		}
956
		else
957
		{
B
Bruce Momjian 已提交
958
			/*
B
Bruce Momjian 已提交
959
			 * Cannot wake this guy. Remember his request for later checks.
B
Bruce Momjian 已提交
960
			 */
961
			aheadRequests |= LOCKBIT_ON(lockmode);
J
Jan Wieck 已提交
962
			proc = (PGPROC *) MAKE_PTR(proc->links.next);
963
		}
M
 
Marc G. Fournier 已提交
964
	}
965 966

	Assert(waitQueue->size >= 0);
967 968
}

969 970 971
/*
 * CheckDeadLock
 *
972
 * We only get to this routine if we got SIGALRM after DeadlockTimeout
973 974 975 976
 * 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.
977
 */
978
static void
979
CheckDeadLock(void)
980
{
981 982
	int			i;

983
	/*
B
Bruce Momjian 已提交
984 985
	 * Acquire exclusive lock on the entire shared lock data structures. Must
	 * grab LWLocks in partition-number order to avoid LWLock deadlock.
986 987 988 989 990 991
	 *
	 * 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.
992
	 */
993 994
	for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
		LWLockAcquire(FirstLockMgrLock + i, LW_EXCLUSIVE);
995

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

1011
#ifdef LOCK_DEBUG
B
Bruce Momjian 已提交
1012 1013
	if (Debug_deadlocks)
		DumpAllLocks();
1014 1015
#endif

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

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

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

1042
	/*
B
Bruce Momjian 已提交
1043 1044 1045 1046 1047 1048 1049 1050
	 * 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.
1051
	 */
1052 1053

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


1064 1065 1066 1067 1068 1069
/*
 * 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 已提交
1070
 * before we actually reach the waiting state.	Also as with locks,
1071 1072
 * 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 已提交
1073
 * if not.	This copes with possible "leftover" wakeups.
1074 1075 1076 1077
 */
void
ProcWaitForSignal(void)
{
1078
	PGSemaphoreLock(&MyProc->sem, true);
1079 1080 1081
}

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

	if (proc != NULL)
1090
		PGSemaphoreUnlock(&proc->sem);
1091 1092 1093
}


1094 1095 1096 1097 1098 1099 1100 1101 1102
/*****************************************************************************
 * SIGALRM interrupt support
 *
 * Maybe these should be in pqsignal.c?
 *****************************************************************************/

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

1117 1118
	if (is_statement_timeout)
	{
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
		/*
		 * 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 已提交
1129 1130 1131 1132
		 * 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.
1133
		 */
1134
		Assert(!deadlock_timeout_active);
1135 1136
		fin_time = GetCurrentStatementStartTimestamp();
		fin_time = TimestampTzPlusMilliseconds(fin_time, delayms);
1137
		statement_fin_time = fin_time;
1138
		cancel_from_timeout = false;
1139
		statement_timeout_active = true;
1140 1141 1142 1143 1144 1145
	}
	else if (statement_timeout_active)
	{
		/*
		 * Begin deadlock timeout with statement-level timeout active
		 *
1146 1147 1148 1149
		 * 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.
1150 1151 1152
		 *
		 * 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 已提交
1153 1154 1155
		 * 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.
1156
		 */
1157 1158
		fin_time = GetCurrentTimestamp();
		fin_time = TimestampTzPlusMilliseconds(fin_time, delayms);
1159
		deadlock_timeout_active = true;
1160
		if (fin_time >= statement_fin_time)
1161 1162 1163 1164 1165 1166 1167
			return true;
	}
	else
	{
		/* Begin deadlock timeout with no statement-level timeout */
		deadlock_timeout_active = true;
	}
1168

1169
	/* If we reach here, okay to set the timer interrupt */
1170
	MemSet(&timeval, 0, sizeof(struct itimerval));
1171 1172
	timeval.it_value.tv_sec = delayms / 1000;
	timeval.it_value.tv_usec = (delayms % 1000) * 1000;
1173
	if (setitimer(ITIMER_REAL, &timeval, NULL))
1174
		return false;
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
	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)
1196
	{
1197
		struct itimerval timeval;
1198

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

1209 1210 1211 1212
	/* Always cancel deadlock timeout, in case this is error cleanup */
	deadlock_timeout_active = false;

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

1226

1227
/*
1228 1229 1230
 * 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.
1231
 *
1232
 * Returns true if okay, false if failed to set the interrupt.
1233
 */
1234 1235
static bool
CheckStatementTimeout(void)
1236
{
1237
	TimestampTz now;
B
Bruce Momjian 已提交
1238

1239 1240 1241
	if (!statement_timeout_active)
		return true;			/* do nothing if not active */

1242
	now = GetCurrentTimestamp();
1243

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

1262 1263
		TimestampDifference(now, statement_fin_time,
							&secs, &usecs);
B
Bruce Momjian 已提交
1264

1265 1266 1267 1268 1269 1270
		/*
		 * 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;
1271
		MemSet(&timeval, 0, sizeof(struct itimerval));
1272 1273
		timeval.it_value.tv_sec = secs;
		timeval.it_value.tv_usec = usecs;
1274
		if (setitimer(ITIMER_REAL, &timeval, NULL))
1275 1276 1277
			return false;
	}

1278 1279
	return true;
}
1280 1281 1282


/*
1283 1284 1285 1286 1287 1288
 * 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.
1289 1290 1291 1292
 */
void
handle_sig_alarm(SIGNAL_ARGS)
{
1293 1294 1295
	int			save_errno = errno;

	if (deadlock_timeout_active)
1296
	{
1297
		deadlock_timeout_active = false;
1298 1299
		CheckDeadLock();
	}
1300 1301 1302 1303 1304

	if (statement_timeout_active)
		(void) CheckStatementTimeout();

	errno = save_errno;
1305
}