1 /*-------------------------------------------------------------------------
4 * Implement PGSemaphores using SysV semaphore facilities
7 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/port/sysv_sema.c
13 *-------------------------------------------------------------------------
27 #include "miscadmin.h"
28 #include "storage/ipc.h"
29 #include "storage/pg_sema.h"
32 #ifndef HAVE_UNION_SEMUN
37 unsigned short *array;
41 typedef key_t IpcSemaphoreKey; /* semaphore key passed to semget(2) */
42 typedef int IpcSemaphoreId; /* semaphore ID returned by semget(2) */
45 * SEMAS_PER_SET is the number of useful semaphores in each semaphore set
46 * we allocate. It must be *less than* your kernel's SEMMSL (max semaphores
47 * per set) parameter, which is often around 25. (Less than, because we
48 * allocate one extra sema in each set for identification purposes.)
50 #define SEMAS_PER_SET 16
52 #define IPCProtection (0600) /* access/modify by user only */
54 #define PGSemaMagic 537 /* must be less than SEMVMX */
57 static IpcSemaphoreId *mySemaSets; /* IDs of sema sets acquired so far */
58 static int numSemaSets; /* number of sema sets acquired so far */
59 static int maxSemaSets; /* allocated size of mySemaSets array */
60 static IpcSemaphoreKey nextSemaKey; /* next key to try using */
61 static int nextSemaNumber; /* next free sem num in last sema set */
64 static IpcSemaphoreId InternalIpcSemaphoreCreate(IpcSemaphoreKey semKey,
66 static void IpcSemaphoreInitialize(IpcSemaphoreId semId, int semNum,
68 static void IpcSemaphoreKill(IpcSemaphoreId semId);
69 static int IpcSemaphoreGetValue(IpcSemaphoreId semId, int semNum);
70 static pid_t IpcSemaphoreGetLastPID(IpcSemaphoreId semId, int semNum);
71 static IpcSemaphoreId IpcSemaphoreCreate(int numSems);
72 static void ReleaseSemaphores(int status, Datum arg);
76 * InternalIpcSemaphoreCreate
78 * Attempt to create a new semaphore set with the specified key.
79 * Will fail (return -1) if such a set already exists.
81 * If we fail with a failure code other than collision-with-existing-set,
82 * print out an error and abort. Other types of errors suggest nonrecoverable
86 InternalIpcSemaphoreCreate(IpcSemaphoreKey semKey, int numSems)
90 semId = semget(semKey, numSems, IPC_CREAT | IPC_EXCL | IPCProtection);
95 * Fail quietly if error indicates a collision with existing set. One
96 * would expect EEXIST, given that we said IPC_EXCL, but perhaps we
97 * could get a permission violation instead? Also, EIDRM might occur
98 * if an old set is slated for destruction but not gone yet.
100 if (errno == EEXIST || errno == EACCES
108 * Else complain and abort
111 (errmsg("could not create semaphores: %m"),
112 errdetail("Failed system call was semget(%lu, %d, 0%o).",
113 (unsigned long) semKey, numSems,
114 IPC_CREAT | IPC_EXCL | IPCProtection),
116 errhint("This error does *not* mean that you have run out of disk space. "
117 "It occurs when either the system limit for the maximum number of "
118 "semaphore sets (SEMMNI), or the system wide maximum number of "
119 "semaphores (SEMMNS), would be exceeded. You need to raise the "
120 "respective kernel parameter. Alternatively, reduce PostgreSQL's "
121 "consumption of semaphores by reducing its max_connections parameter.\n"
122 "The PostgreSQL documentation contains more information about "
123 "configuring your system for PostgreSQL.") : 0));
130 * Initialize a semaphore to the specified value.
133 IpcSemaphoreInitialize(IpcSemaphoreId semId, int semNum, int value)
138 if (semctl(semId, semNum, SETVAL, semun) < 0)
140 (errmsg_internal("semctl(%d, %d, SETVAL, %d) failed: %m",
141 semId, semNum, value),
143 errhint("You possibly need to raise your kernel's SEMVMX value to be at least "
144 "%d. Look into the PostgreSQL documentation for details.",
149 * IpcSemaphoreKill(semId) - removes a semaphore set
152 IpcSemaphoreKill(IpcSemaphoreId semId)
156 semun.val = 0; /* unused, but keep compiler quiet */
158 if (semctl(semId, 0, IPC_RMID, semun) < 0)
159 elog(LOG, "semctl(%d, 0, IPC_RMID, ...) failed: %m", semId);
162 /* Get the current value (semval) of the semaphore */
164 IpcSemaphoreGetValue(IpcSemaphoreId semId, int semNum)
166 union semun dummy; /* for Solaris */
168 dummy.val = 0; /* unused */
170 return semctl(semId, semNum, GETVAL, dummy);
173 /* Get the PID of the last process to do semop() on the semaphore */
175 IpcSemaphoreGetLastPID(IpcSemaphoreId semId, int semNum)
177 union semun dummy; /* for Solaris */
179 dummy.val = 0; /* unused */
181 return semctl(semId, semNum, GETPID, dummy);
186 * Create a semaphore set with the given number of useful semaphores
187 * (an additional sema is actually allocated to serve as identifier).
188 * Dead Postgres sema sets are recycled if found, but we do not fail
189 * upon collision with non-Postgres sema sets.
191 * The idea here is to detect and re-use keys that may have been assigned
192 * by a crashed postmaster or backend.
194 static IpcSemaphoreId
195 IpcSemaphoreCreate(int numSems)
197 IpcSemaphoreId semId;
199 PGSemaphoreData mysema;
201 /* Loop till we find a free IPC key */
202 for (nextSemaKey++;; nextSemaKey++)
206 /* Try to create new semaphore set */
207 semId = InternalIpcSemaphoreCreate(nextSemaKey, numSems + 1);
209 break; /* successful create */
211 /* See if it looks to be leftover from a dead Postgres process */
212 semId = semget(nextSemaKey, numSems + 1, 0);
214 continue; /* failed: must be some other app's */
215 if (IpcSemaphoreGetValue(semId, numSems) != PGSemaMagic)
216 continue; /* sema belongs to a non-Postgres app */
219 * If the creator PID is my own PID or does not belong to any extant
220 * process, it's safe to zap it.
222 creatorPID = IpcSemaphoreGetLastPID(semId, numSems);
224 continue; /* oops, GETPID failed */
225 if (creatorPID != getpid())
227 if (kill(creatorPID, 0) == 0 || errno != ESRCH)
228 continue; /* sema belongs to a live process */
232 * The sema set appears to be from a dead Postgres process, or from a
233 * previous cycle of life in this same process. Zap it, if possible.
234 * This probably shouldn't fail, but if it does, assume the sema set
235 * belongs to someone else after all, and continue quietly.
237 semun.val = 0; /* unused, but keep compiler quiet */
238 if (semctl(semId, 0, IPC_RMID, semun) < 0)
242 * Now try again to create the sema set.
244 semId = InternalIpcSemaphoreCreate(nextSemaKey, numSems + 1);
246 break; /* successful create */
249 * Can only get here if some other process managed to create the same
250 * sema key before we did. Let him have that one, loop around to try
256 * OK, we created a new sema set. Mark it as created by this process. We
257 * do this by setting the spare semaphore to PGSemaMagic-1 and then
258 * incrementing it with semop(). That leaves it with value PGSemaMagic
259 * and sempid referencing this process.
261 IpcSemaphoreInitialize(semId, numSems, PGSemaMagic - 1);
262 mysema.semId = semId;
263 mysema.semNum = numSems;
264 PGSemaphoreUnlock(&mysema);
271 * PGReserveSemaphores --- initialize semaphore support
273 * This is called during postmaster start or shared memory reinitialization.
274 * It should do whatever is needed to be able to support up to maxSemas
275 * subsequent PGSemaphoreCreate calls. Also, if any system resources
276 * are acquired here or in PGSemaphoreCreate, register an on_shmem_exit
277 * callback to release them.
279 * The port number is passed for possible use as a key (for SysV, we use
280 * it to generate the starting semaphore key). In a standalone backend,
281 * zero will be passed.
283 * In the SysV implementation, we acquire semaphore sets on-demand; the
284 * maxSemas parameter is just used to size the array that keeps track of
285 * acquired sets for subsequent releasing.
288 PGReserveSemaphores(int maxSemas, int port)
290 maxSemaSets = (maxSemas + SEMAS_PER_SET - 1) / SEMAS_PER_SET;
291 mySemaSets = (IpcSemaphoreId *)
292 malloc(maxSemaSets * sizeof(IpcSemaphoreId));
293 if (mySemaSets == NULL)
294 elog(PANIC, "out of memory");
296 nextSemaKey = port * 1000;
297 nextSemaNumber = SEMAS_PER_SET; /* force sema set alloc on 1st call */
299 on_shmem_exit(ReleaseSemaphores, 0);
303 * Release semaphores at shutdown or shmem reinitialization
305 * (called as an on_shmem_exit callback, hence funny argument list)
308 ReleaseSemaphores(int status, Datum arg)
312 for (i = 0; i < numSemaSets; i++)
313 IpcSemaphoreKill(mySemaSets[i]);
320 * Initialize a PGSemaphore structure to represent a sema with count 1
323 PGSemaphoreCreate(PGSemaphore sema)
325 /* Can't do this in a backend, because static state is postmaster's */
326 Assert(!IsUnderPostmaster);
328 if (nextSemaNumber >= SEMAS_PER_SET)
330 /* Time to allocate another semaphore set */
331 if (numSemaSets >= maxSemaSets)
332 elog(PANIC, "too many semaphores created");
333 mySemaSets[numSemaSets] = IpcSemaphoreCreate(SEMAS_PER_SET);
337 /* Assign the next free semaphore in the current set */
338 sema->semId = mySemaSets[numSemaSets - 1];
339 sema->semNum = nextSemaNumber++;
340 /* Initialize it to count 1 */
341 IpcSemaphoreInitialize(sema->semId, sema->semNum, 1);
347 * Reset a previously-initialized PGSemaphore to have count 0
350 PGSemaphoreReset(PGSemaphore sema)
352 IpcSemaphoreInitialize(sema->semId, sema->semNum, 0);
358 * Lock a semaphore (decrement count), blocking if count would be < 0
361 PGSemaphoreLock(PGSemaphore sema, bool interruptOK)
366 sops.sem_op = -1; /* decrement */
368 sops.sem_num = sema->semNum;
371 * Note: if errStatus is -1 and errno == EINTR then it means we returned
372 * from the operation prematurely because we were sent a signal. So we
373 * try and lock the semaphore again.
375 * Each time around the loop, we check for a cancel/die interrupt. On
376 * some platforms, if such an interrupt comes in while we are waiting, it
377 * will cause the semop() call to exit with errno == EINTR, allowing us to
378 * service the interrupt (if not in a critical section already) during the
379 * next loop iteration.
381 * Once we acquire the lock, we do NOT check for an interrupt before
382 * returning. The caller needs to be able to record ownership of the lock
383 * before any interrupt can be accepted.
385 * There is a window of a few instructions between CHECK_FOR_INTERRUPTS
386 * and entering the semop() call. If a cancel/die interrupt occurs in
387 * that window, we would fail to notice it until after we acquire the lock
388 * (or get another interrupt to escape the semop()). We can avoid this
389 * problem by temporarily setting ImmediateInterruptOK to true before we
390 * do CHECK_FOR_INTERRUPTS; then, a die() interrupt in this interval will
391 * execute directly. However, there is a huge pitfall: there is another
392 * window of a few instructions after the semop() before we are able to
393 * reset ImmediateInterruptOK. If an interrupt occurs then, we'll lose
394 * control, which means that the lock has been acquired but our caller did
395 * not get a chance to record the fact. Therefore, we only set
396 * ImmediateInterruptOK if the caller tells us it's OK to do so, ie, the
397 * caller does not need to record acquiring the lock. (This is currently
398 * true for lockmanager locks, since the process that granted us the lock
399 * did all the necessary state updates. It's not true for SysV semaphores
400 * used to implement LW locks or emulate spinlocks --- but the wait time
401 * for such locks should not be very long, anyway.)
403 * On some platforms, signals marked SA_RESTART (which is most, for us)
404 * will not interrupt the semop(); it will just keep waiting. Therefore
405 * it's necessary for cancel/die interrupts to be serviced directly by the
406 * signal handler. On these platforms the behavior is really the same
407 * whether the signal arrives just before the semop() begins, or while it
408 * is waiting. The loop on EINTR is thus important only for other types
413 ImmediateInterruptOK = interruptOK;
414 CHECK_FOR_INTERRUPTS();
415 errStatus = semop(sema->semId, &sops, 1);
416 ImmediateInterruptOK = false;
417 } while (errStatus < 0 && errno == EINTR);
420 elog(FATAL, "semop(id=%d) failed: %m", sema->semId);
426 * Unlock a semaphore (increment count)
429 PGSemaphoreUnlock(PGSemaphore sema)
434 sops.sem_op = 1; /* increment */
436 sops.sem_num = sema->semNum;
439 * Note: if errStatus is -1 and errno == EINTR then it means we returned
440 * from the operation prematurely because we were sent a signal. So we
441 * try and unlock the semaphore again. Not clear this can really happen,
442 * but might as well cope.
446 errStatus = semop(sema->semId, &sops, 1);
447 } while (errStatus < 0 && errno == EINTR);
450 elog(FATAL, "semop(id=%d) failed: %m", sema->semId);
456 * Lock a semaphore only if able to do so without blocking
459 PGSemaphoreTryLock(PGSemaphore sema)
464 sops.sem_op = -1; /* decrement */
465 sops.sem_flg = IPC_NOWAIT; /* but don't block */
466 sops.sem_num = sema->semNum;
469 * Note: if errStatus is -1 and errno == EINTR then it means we returned
470 * from the operation prematurely because we were sent a signal. So we
471 * try and lock the semaphore again.
475 errStatus = semop(sema->semId, &sops, 1);
476 } while (errStatus < 0 && errno == EINTR);
480 /* Expect EAGAIN or EWOULDBLOCK (platform-dependent) */
483 return false; /* failed to lock it */
485 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
486 if (errno == EWOULDBLOCK)
487 return false; /* failed to lock it */
489 /* Otherwise we got trouble */
490 elog(FATAL, "semop(id=%d) failed: %m", sema->semId);