⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 proc.c

📁 PostgreSQL 8.1.4的源码 适用于Linux下的开源数据库系统
💻 C
📖 第 1 页 / 共 3 页
字号:
/*------------------------------------------------------------------------- * * proc.c *	  routines to manage per-process shared memory data structure * * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION *	  $PostgreSQL: pgsql/src/backend/storage/lmgr/proc.c,v 1.167.2.1 2005/11/22 18:23:19 momjian Exp $ * *------------------------------------------------------------------------- *//* * Interface (a): *		ProcSleep(), ProcWakeup(), *		ProcQueueAlloc() -- create a shm queue for sleeping processes *		ProcQueueInit() -- create a queue without allocing memory * * 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 current transaction * * ProcKill -- destroys the shared memory state (and locks) *		associated with the process. */#include "postgres.h"#include <signal.h>#include <unistd.h>#include <sys/time.h>#include "miscadmin.h"#include "access/xact.h"#include "storage/bufmgr.h"#include "storage/ipc.h"#include "storage/proc.h"#include "storage/procarray.h"#include "storage/spin.h"/* GUC variables */int			DeadlockTimeout = 1000;int			StatementTimeout = 0;/* Pointer to this process's PGPROC struct, if any */PGPROC	   *MyProc = NULL;/* * This spinlock protects the freelist of recycled PGPROC structures. * We cannot use an LWLock because the LWLock manager depends on already * having a PGPROC and a wait semaphore!  But these structures are touched * relatively infrequently (only at backend startup or shutdown) and not for * very long, so a spinlock is okay. */NON_EXEC_STATIC slock_t *ProcStructLock = NULL;/* Pointers to shared-memory structures */static PROC_HDR *ProcGlobal = NULL;static PGPROC *DummyProcs = NULL;static bool waitingForLock = false;/* 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;volatile bool cancel_from_timeout = false;/* statement_fin_time is valid only if statement_timeout_active is true */static struct timeval statement_fin_time;static void ProcKill(int code, Datum arg);static void DummyProcKill(int code, Datum arg);static bool CheckStatementTimeout(void);/* * Report shared-memory space needed by InitProcGlobal. */SizeProcGlobalShmemSize(void){	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));	return size;}/* * Report number of semaphores needed by InitProcGlobal. */intProcGlobalSemas(void){	/* We need a sema per backend, plus one for each dummy process. */	return MaxBackends + NUM_DUMMY_PROCS;}/* * InitProcGlobal - *	  Initialize the global process table during postmaster startup. * *	  We also create all the per-process semaphores we will need to support *	  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. * *	  Another reason for creating semaphores here is that the semaphore *	  implementation typically requires us to create semaphores in the *	  postmaster, not in backends. */voidInitProcGlobal(void){	bool		foundProcGlobal,				foundDummy;	/* Create or attach to the ProcGlobal shared structure */	ProcGlobal = (PROC_HDR *)		ShmemInitStruct("Proc Header", sizeof(PROC_HDR), &foundProcGlobal);	/*	 * Create or attach to the PGPROC structures for dummy (bgwriter)	 * processes, too.	These do not get linked into the freeProcs list.	 */	DummyProcs = (PGPROC *)		ShmemInitStruct("DummyProcs", NUM_DUMMY_PROCS * sizeof(PGPROC),						&foundDummy);	if (foundProcGlobal || foundDummy)	{		/* both should be present or neither */		Assert(foundProcGlobal && foundDummy);	}	else	{		/*		 * We're the first - initialize.		 */		PGPROC	   *procs;		int			i;		ProcGlobal->freeProcs = INVALID_OFFSET;		ProcGlobal->spins_per_delay = DEFAULT_SPINS_PER_DELAY;		/*		 * 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]);		}		MemSet(DummyProcs, 0, NUM_DUMMY_PROCS * sizeof(PGPROC));		for (i = 0; i < NUM_DUMMY_PROCS; i++)		{			DummyProcs[i].pid = 0;		/* marks dummy proc as not in use */			PGSemaphoreCreate(&(DummyProcs[i].sem));		}		/* Create ProcStructLock spinlock, too */		ProcStructLock = (slock_t *) ShmemAlloc(sizeof(slock_t));		SpinLockInit(ProcStructLock);	}}/* * InitProcess -- initialize a per-process data structure for this backend */voidInitProcess(void){	SHMEM_OFFSET myOffset;	/* use volatile pointer to prevent code rearrangement */	volatile PROC_HDR *procglobal = ProcGlobal;	/*	 * ProcGlobal should be set by a previous call to InitProcGlobal (if we	 * are a backend, we inherit this by fork() from the postmaster).	 */	if (procglobal == NULL)		elog(PANIC, "proc header uninitialized");	if (MyProc != NULL)		elog(ERROR, "you already exist");	/*	 * Try to get a proc struct from the free list.  If this fails, we must be	 * out of PGPROC structures (not to mention semaphores).	 *	 * While we are holding the ProcStructLock, also copy the current shared	 * estimate of spins_per_delay to local storage.	 */	SpinLockAcquire(ProcStructLock);	set_spins_per_delay(procglobal->spins_per_delay);	myOffset = procglobal->freeProcs;	if (myOffset != INVALID_OFFSET)	{		MyProc = (PGPROC *) MAKE_PTR(myOffset);		procglobal->freeProcs = MyProc->links.next;		SpinLockRelease(ProcStructLock);	}	else	{		/*		 * 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.		 */		SpinLockRelease(ProcStructLock);		ereport(FATAL,				(errcode(ERRCODE_TOO_MANY_CONNECTIONS),				 errmsg("sorry, too many clients already")));	}	/*	 * Initialize all fields of MyProc, except for the semaphore which was	 * prepared for us by InitProcGlobal.	 */	SHMQueueElemInit(&(MyProc->links));	MyProc->waitStatus = STATUS_OK;	MyProc->xid = InvalidTransactionId;	MyProc->xmin = InvalidTransactionId;	MyProc->pid = MyProcPid;	MyProc->databaseId = MyDatabaseId;	/* Will be set properly after the session role id is determined */	MyProc->roleId = InvalidOid;	MyProc->lwWaiting = false;	MyProc->lwExclusive = false;	MyProc->lwWaitLink = NULL;	MyProc->waitLock = NULL;	MyProc->waitProcLock = NULL;	SHMQueueInit(&(MyProc->procLocks));	/*	 * Add our PGPROC to the PGPROC array in shared memory.	 */	ProcArrayAdd(MyProc);	/*	 * Arrange to clean up at backend exit.	 */	on_shmem_exit(ProcKill, 0);	/*	 * We might be reusing a semaphore that belonged to a failed process. So	 * be careful and reinitialize its value here.	 */	PGSemaphoreReset(&MyProc->sem);	/*	 * Now that we have a PGPROC, we could try to acquire locks, so initialize	 * the deadlock checker.	 */	InitDeadLockChecking();}/* * InitDummyProcess -- create a dummy per-process data structure * * 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 * and sema that are assigned are the extra ones created during * InitProcGlobal. * * Dummy processes are presently not expected to wait for real (lockmgr) * locks, nor to participate in sinval messaging. */voidInitDummyProcess(int proctype){	PGPROC	   *dummyproc;	/*	 * ProcGlobal should be set by a previous call to InitProcGlobal (we	 * inherit this by fork() from the postmaster).	 */	if (ProcGlobal == NULL || DummyProcs == NULL)		elog(PANIC, "proc header uninitialized");	if (MyProc != NULL)		elog(ERROR, "you already exist");	Assert(proctype >= 0 && proctype < NUM_DUMMY_PROCS);	/*	 * Just for paranoia's sake, we use the ProcStructLock to protect	 * assignment and releasing of DummyProcs entries.	 *	 * While we are holding the ProcStructLock, also copy the current shared	 * estimate of spins_per_delay to local storage.	 */	SpinLockAcquire(ProcStructLock);	set_spins_per_delay(ProcGlobal->spins_per_delay);	dummyproc = &DummyProcs[proctype];	/*	 * dummyproc should not presently be in use by anyone else	 */	if (dummyproc->pid != 0)	{		SpinLockRelease(ProcStructLock);		elog(FATAL, "DummyProc[%d] is in use by PID %d",			 proctype, dummyproc->pid);	}	MyProc = dummyproc;	MyProc->pid = MyProcPid;	/* marks dummy proc as in use by me */	SpinLockRelease(ProcStructLock);	/*	 * Initialize all fields of MyProc, except MyProc->sem which was set up by	 * InitProcGlobal.	 */	SHMQueueElemInit(&(MyProc->links));	MyProc->waitStatus = STATUS_OK;	MyProc->xid = InvalidTransactionId;	MyProc->xmin = InvalidTransactionId;	MyProc->databaseId = MyDatabaseId;	MyProc->roleId = InvalidOid;	MyProc->lwWaiting = false;	MyProc->lwExclusive = false;	MyProc->lwWaitLink = NULL;	MyProc->waitLock = NULL;	MyProc->waitProcLock = NULL;	SHMQueueInit(&(MyProc->procLocks));	/*	 * Arrange to clean up at process exit.	 */	on_shmem_exit(DummyProcKill, Int32GetDatum(proctype));	/*	 * We might be reusing a semaphore that belonged to a failed process. So	 * be careful and reinitialize its value here.	 */	PGSemaphoreReset(&MyProc->sem);}/* * Check whether there are at least N free PGPROC objects. * * Note: this is designed on the assumption that N will generally be small. */boolHaveNFreeProcs(int n){	SHMEM_OFFSET offset;	PGPROC	   *proc;	/* 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);}/* * Cancel any pending wait for lock, when aborting a transaction. * * Returns true if we had been waiting for a lock, else false. * * (Normally, this would only happen if we accept a cancel/die * interrupt while waiting; but an ereport(ERROR) while waiting is * within the realm of possibility, too.) */boolLockWaitCancel(void){	/* Nothing to do if we weren't waiting for a lock */	if (!waitingForLock)		return false;	/* Turn off the deadlock timer, if it's still running (see ProcSleep) */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -