1
/*-------------------------------------------------------------------------
4
* Implement PGSemaphores using POSIX semaphore facilities
6
* We prefer the unnamed style of POSIX semaphore (the kind made with
7
* sem_init). We can cope with the kind made with sem_open, however.
10
* Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
11
* Portions Copyright (c) 1994, Regents of the University of California
14
* $PostgreSQL: pgsql/src/backend/port/posix_sema.c,v 1.13 2004-12-31 22:00:29 pgsql Exp $
16
*-------------------------------------------------------------------------
25
#include "miscadmin.h"
26
#include "storage/ipc.h"
27
#include "storage/pg_sema.h"
30
#ifdef USE_NAMED_POSIX_SEMAPHORES
31
/* PGSemaphore is pointer to pointer to sem_t */
32
#define PG_SEM_REF(x) (*(x))
34
/* PGSemaphore is pointer to sem_t */
35
#define PG_SEM_REF(x) (x)
39
#define IPCProtection (0600) /* access/modify by user only */
41
static sem_t **mySemPointers; /* keep track of created semaphores */
42
static int numSems; /* number of semas acquired so far */
43
static int maxSems; /* allocated size of mySemaPointers array */
44
static int nextSemKey; /* next name to try */
47
static void ReleaseSemaphores(int status, Datum arg);
50
#ifdef USE_NAMED_POSIX_SEMAPHORES
53
* PosixSemaphoreCreate
55
* Attempt to create a new named semaphore.
57
* If we fail with a failure code other than collision-with-existing-sema,
58
* print out an error and abort. Other types of errors suggest nonrecoverable
62
PosixSemaphoreCreate(void)
70
semKey = nextSemKey++;
72
snprintf(semname, sizeof(semname), "/pgsql-%d", semKey);
74
mySem = sem_open(semname, O_CREAT | O_EXCL,
75
(mode_t) IPCProtection, (unsigned) 1);
78
if (mySem != (sem_t *) SEM_FAILED)
81
if (mySem != (sem_t *) (-1))
85
/* Loop if error indicates a collision */
86
if (errno == EEXIST || errno == EACCES || errno == EINTR)
90
* Else complain and abort
92
elog(FATAL, "sem_open(\"%s\") failed: %m", semname);
96
* Unlink the semaphore immediately, so it can't be accessed
97
* externally. This also ensures that it will go away if we crash.
104
#else /* !USE_NAMED_POSIX_SEMAPHORES */
107
* PosixSemaphoreCreate
109
* Attempt to create a new unnamed semaphore.
112
PosixSemaphoreCreate(sem_t * sem)
114
if (sem_init(sem, 1, 1) < 0)
115
elog(FATAL, "sem_init failed: %m");
117
#endif /* USE_NAMED_POSIX_SEMAPHORES */
121
* PosixSemaphoreKill - removes a semaphore
124
PosixSemaphoreKill(sem_t * sem)
126
#ifdef USE_NAMED_POSIX_SEMAPHORES
127
/* Got to use sem_close for named semaphores */
128
if (sem_close(sem) < 0)
129
elog(LOG, "sem_close failed: %m");
131
/* Got to use sem_destroy for unnamed semaphores */
132
if (sem_destroy(sem) < 0)
133
elog(LOG, "sem_destroy failed: %m");
139
* PGReserveSemaphores --- initialize semaphore support
141
* This is called during postmaster start or shared memory reinitialization.
142
* It should do whatever is needed to be able to support up to maxSemas
143
* subsequent PGSemaphoreCreate calls. Also, if any system resources
144
* are acquired here or in PGSemaphoreCreate, register an on_shmem_exit
145
* callback to release them.
147
* The port number is passed for possible use as a key (for Posix, we use
148
* it to generate the starting semaphore name). In a standalone backend,
149
* zero will be passed.
151
* In the Posix implementation, we acquire semaphores on-demand; the
152
* maxSemas parameter is just used to size the array that keeps track of
153
* acquired semas for subsequent releasing.
156
PGReserveSemaphores(int maxSemas, int port)
158
mySemPointers = (sem_t **) malloc(maxSemas * sizeof(sem_t *));
159
if (mySemPointers == NULL)
160
elog(PANIC, "out of memory");
163
nextSemKey = port * 1000;
165
on_shmem_exit(ReleaseSemaphores, 0);
169
* Release semaphores at shutdown or shmem reinitialization
171
* (called as an on_shmem_exit callback, hence funny argument list)
174
ReleaseSemaphores(int status, Datum arg)
178
for (i = 0; i < numSems; i++)
179
PosixSemaphoreKill(mySemPointers[i]);
186
* Initialize a PGSemaphore structure to represent a sema with count 1
189
PGSemaphoreCreate(PGSemaphore sema)
193
/* Can't do this in a backend, because static state is postmaster's */
194
Assert(!IsUnderPostmaster);
196
if (numSems >= maxSems)
197
elog(PANIC, "too many semaphores created");
199
#ifdef USE_NAMED_POSIX_SEMAPHORES
200
*sema = newsem = PosixSemaphoreCreate();
202
PosixSemaphoreCreate(sema);
206
/* Remember new sema for ReleaseSemaphores */
207
mySemPointers[numSems++] = newsem;
213
* Reset a previously-initialized PGSemaphore to have count 0
216
PGSemaphoreReset(PGSemaphore sema)
219
* There's no direct API for this in POSIX, so we have to ratchet the
220
* semaphore down to 0 with repeated trywait's.
224
if (sem_trywait(PG_SEM_REF(sema)) < 0)
226
if (errno == EAGAIN || errno == EDEADLK)
227
break; /* got it down to 0 */
229
continue; /* can this happen? */
230
elog(FATAL, "sem_trywait failed: %m");
238
* Lock a semaphore (decrement count), blocking if count would be < 0
241
PGSemaphoreLock(PGSemaphore sema, bool interruptOK)
246
* Note: if errStatus is -1 and errno == EINTR then it means we
247
* returned from the operation prematurely because we were sent a
248
* signal. So we try and lock the semaphore again.
250
* Each time around the loop, we check for a cancel/die interrupt. We
251
* assume that if such an interrupt comes in while we are waiting, it
252
* will cause the sem_wait() call to exit with errno == EINTR, so that
253
* we will be able to service the interrupt (if not in a critical
256
* Once we acquire the lock, we do NOT check for an interrupt before
257
* returning. The caller needs to be able to record ownership of the
258
* lock before any interrupt can be accepted.
260
* There is a window of a few instructions between CHECK_FOR_INTERRUPTS
261
* and entering the sem_wait() call. If a cancel/die interrupt occurs
262
* in that window, we would fail to notice it until after we acquire
263
* the lock (or get another interrupt to escape the sem_wait()). We
264
* can avoid this problem by temporarily setting ImmediateInterruptOK
265
* to true before we do CHECK_FOR_INTERRUPTS; then, a die() interrupt
266
* in this interval will execute directly. However, there is a huge
267
* pitfall: there is another window of a few instructions after the
268
* sem_wait() before we are able to reset ImmediateInterruptOK. If an
269
* interrupt occurs then, we'll lose control, which means that the
270
* lock has been acquired but our caller did not get a chance to
271
* record the fact. Therefore, we only set ImmediateInterruptOK if the
272
* caller tells us it's OK to do so, ie, the caller does not need to
273
* record acquiring the lock. (This is currently true for lockmanager
274
* locks, since the process that granted us the lock did all the
275
* necessary state updates. It's not true for Posix semaphores used to
276
* implement LW locks or emulate spinlocks --- but the wait time for
277
* such locks should not be very long, anyway.)
281
ImmediateInterruptOK = interruptOK;
282
CHECK_FOR_INTERRUPTS();
283
errStatus = sem_wait(PG_SEM_REF(sema));
284
ImmediateInterruptOK = false;
285
} while (errStatus < 0 && errno == EINTR);
288
elog(FATAL, "sem_wait failed: %m");
294
* Unlock a semaphore (increment count)
297
PGSemaphoreUnlock(PGSemaphore sema)
302
* Note: if errStatus is -1 and errno == EINTR then it means we
303
* returned from the operation prematurely because we were sent a
304
* signal. So we try and unlock the semaphore again. Not clear this
305
* can really happen, but might as well cope.
309
errStatus = sem_post(PG_SEM_REF(sema));
310
} while (errStatus < 0 && errno == EINTR);
313
elog(FATAL, "sem_post failed: %m");
319
* Lock a semaphore only if able to do so without blocking
322
PGSemaphoreTryLock(PGSemaphore sema)
327
* Note: if errStatus is -1 and errno == EINTR then it means we
328
* returned from the operation prematurely because we were sent a
329
* signal. So we try and lock the semaphore again.
333
errStatus = sem_trywait(PG_SEM_REF(sema));
334
} while (errStatus < 0 && errno == EINTR);
338
if (errno == EAGAIN || errno == EDEADLK)
339
return false; /* failed to lock it */
340
/* Otherwise we got trouble */
341
elog(FATAL, "sem_trywait failed: %m");