]> granicus.if.org Git - postgresql/blob - src/backend/port/sysv_sema.c
Fix confusion between "size" and "AnonymousShmemSize".
[postgresql] / src / backend / port / sysv_sema.c
1 /*-------------------------------------------------------------------------
2  *
3  * sysv_sema.c
4  *        Implement PGSemaphores using SysV semaphore facilities
5  *
6  *
7  * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  * IDENTIFICATION
11  *        src/backend/port/sysv_sema.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include <signal.h>
18 #include <unistd.h>
19 #include <sys/file.h>
20 #ifdef HAVE_SYS_IPC_H
21 #include <sys/ipc.h>
22 #endif
23 #ifdef HAVE_SYS_SEM_H
24 #include <sys/sem.h>
25 #endif
26
27 #include "miscadmin.h"
28 #include "storage/ipc.h"
29 #include "storage/pg_sema.h"
30
31
32 #ifndef HAVE_UNION_SEMUN
33 union semun
34 {
35         int                     val;
36         struct semid_ds *buf;
37         unsigned short *array;
38 };
39 #endif
40
41 typedef key_t IpcSemaphoreKey;  /* semaphore key passed to semget(2) */
42 typedef int IpcSemaphoreId;             /* semaphore ID returned by semget(2) */
43
44 /*
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.)
49  */
50 #define SEMAS_PER_SET   16
51
52 #define IPCProtection   (0600)  /* access/modify by user only */
53
54 #define PGSemaMagic             537             /* must be less than SEMVMX */
55
56
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 */
62
63
64 static IpcSemaphoreId InternalIpcSemaphoreCreate(IpcSemaphoreKey semKey,
65                                                    int numSems);
66 static void IpcSemaphoreInitialize(IpcSemaphoreId semId, int semNum,
67                                            int value);
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);
73
74
75 /*
76  * InternalIpcSemaphoreCreate
77  *
78  * Attempt to create a new semaphore set with the specified key.
79  * Will fail (return -1) if such a set already exists.
80  *
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
83  * problems.
84  */
85 static IpcSemaphoreId
86 InternalIpcSemaphoreCreate(IpcSemaphoreKey semKey, int numSems)
87 {
88         int                     semId;
89
90         semId = semget(semKey, numSems, IPC_CREAT | IPC_EXCL | IPCProtection);
91
92         if (semId < 0)
93         {
94                 /*
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.
99                  */
100                 if (errno == EEXIST || errno == EACCES
101 #ifdef EIDRM
102                         || errno == EIDRM
103 #endif
104                         )
105                         return -1;
106
107                 /*
108                  * Else complain and abort
109                  */
110                 ereport(FATAL,
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),
115                                  (errno == ENOSPC) ?
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));
124         }
125
126         return semId;
127 }
128
129 /*
130  * Initialize a semaphore to the specified value.
131  */
132 static void
133 IpcSemaphoreInitialize(IpcSemaphoreId semId, int semNum, int value)
134 {
135         union semun semun;
136
137         semun.val = value;
138         if (semctl(semId, semNum, SETVAL, semun) < 0)
139                 ereport(FATAL,
140                                 (errmsg_internal("semctl(%d, %d, SETVAL, %d) failed: %m",
141                                                                  semId, semNum, value),
142                                  (errno == ERANGE) ?
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.",
145                                                  value) : 0));
146 }
147
148 /*
149  * IpcSemaphoreKill(semId)      - removes a semaphore set
150  */
151 static void
152 IpcSemaphoreKill(IpcSemaphoreId semId)
153 {
154         union semun semun;
155
156         semun.val = 0;                          /* unused, but keep compiler quiet */
157
158         if (semctl(semId, 0, IPC_RMID, semun) < 0)
159                 elog(LOG, "semctl(%d, 0, IPC_RMID, ...) failed: %m", semId);
160 }
161
162 /* Get the current value (semval) of the semaphore */
163 static int
164 IpcSemaphoreGetValue(IpcSemaphoreId semId, int semNum)
165 {
166         union semun dummy;                      /* for Solaris */
167
168         dummy.val = 0;                          /* unused */
169
170         return semctl(semId, semNum, GETVAL, dummy);
171 }
172
173 /* Get the PID of the last process to do semop() on the semaphore */
174 static pid_t
175 IpcSemaphoreGetLastPID(IpcSemaphoreId semId, int semNum)
176 {
177         union semun dummy;                      /* for Solaris */
178
179         dummy.val = 0;                          /* unused */
180
181         return semctl(semId, semNum, GETPID, dummy);
182 }
183
184
185 /*
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.
190  *
191  * The idea here is to detect and re-use keys that may have been assigned
192  * by a crashed postmaster or backend.
193  */
194 static IpcSemaphoreId
195 IpcSemaphoreCreate(int numSems)
196 {
197         IpcSemaphoreId semId;
198         union semun semun;
199         PGSemaphoreData mysema;
200
201         /* Loop till we find a free IPC key */
202         for (nextSemaKey++;; nextSemaKey++)
203         {
204                 pid_t           creatorPID;
205
206                 /* Try to create new semaphore set */
207                 semId = InternalIpcSemaphoreCreate(nextSemaKey, numSems + 1);
208                 if (semId >= 0)
209                         break;                          /* successful create */
210
211                 /* See if it looks to be leftover from a dead Postgres process */
212                 semId = semget(nextSemaKey, numSems + 1, 0);
213                 if (semId < 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 */
217
218                 /*
219                  * If the creator PID is my own PID or does not belong to any extant
220                  * process, it's safe to zap it.
221                  */
222                 creatorPID = IpcSemaphoreGetLastPID(semId, numSems);
223                 if (creatorPID <= 0)
224                         continue;                       /* oops, GETPID failed */
225                 if (creatorPID != getpid())
226                 {
227                         if (kill(creatorPID, 0) == 0 || errno != ESRCH)
228                                 continue;               /* sema belongs to a live process */
229                 }
230
231                 /*
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.
236                  */
237                 semun.val = 0;                  /* unused, but keep compiler quiet */
238                 if (semctl(semId, 0, IPC_RMID, semun) < 0)
239                         continue;
240
241                 /*
242                  * Now try again to create the sema set.
243                  */
244                 semId = InternalIpcSemaphoreCreate(nextSemaKey, numSems + 1);
245                 if (semId >= 0)
246                         break;                          /* successful create */
247
248                 /*
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
251                  * next key.
252                  */
253         }
254
255         /*
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.
260          */
261         IpcSemaphoreInitialize(semId, numSems, PGSemaMagic - 1);
262         mysema.semId = semId;
263         mysema.semNum = numSems;
264         PGSemaphoreUnlock(&mysema);
265
266         return semId;
267 }
268
269
270 /*
271  * PGReserveSemaphores --- initialize semaphore support
272  *
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.
278  *
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.
282  *
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.
286  */
287 void
288 PGReserveSemaphores(int maxSemas, int port)
289 {
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");
295         numSemaSets = 0;
296         nextSemaKey = port * 1000;
297         nextSemaNumber = SEMAS_PER_SET;         /* force sema set alloc on 1st call */
298
299         on_shmem_exit(ReleaseSemaphores, 0);
300 }
301
302 /*
303  * Release semaphores at shutdown or shmem reinitialization
304  *
305  * (called as an on_shmem_exit callback, hence funny argument list)
306  */
307 static void
308 ReleaseSemaphores(int status, Datum arg)
309 {
310         int                     i;
311
312         for (i = 0; i < numSemaSets; i++)
313                 IpcSemaphoreKill(mySemaSets[i]);
314         free(mySemaSets);
315 }
316
317 /*
318  * PGSemaphoreCreate
319  *
320  * Initialize a PGSemaphore structure to represent a sema with count 1
321  */
322 void
323 PGSemaphoreCreate(PGSemaphore sema)
324 {
325         /* Can't do this in a backend, because static state is postmaster's */
326         Assert(!IsUnderPostmaster);
327
328         if (nextSemaNumber >= SEMAS_PER_SET)
329         {
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);
334                 numSemaSets++;
335                 nextSemaNumber = 0;
336         }
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);
342 }
343
344 /*
345  * PGSemaphoreReset
346  *
347  * Reset a previously-initialized PGSemaphore to have count 0
348  */
349 void
350 PGSemaphoreReset(PGSemaphore sema)
351 {
352         IpcSemaphoreInitialize(sema->semId, sema->semNum, 0);
353 }
354
355 /*
356  * PGSemaphoreLock
357  *
358  * Lock a semaphore (decrement count), blocking if count would be < 0
359  */
360 void
361 PGSemaphoreLock(PGSemaphore sema, bool interruptOK)
362 {
363         int                     errStatus;
364         struct sembuf sops;
365
366         sops.sem_op = -1;                       /* decrement */
367         sops.sem_flg = 0;
368         sops.sem_num = sema->semNum;
369
370         /*
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.
374          *
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.
380          *
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.
384          *
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.)
402          *
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
409          * of interrupts.
410          */
411         do
412         {
413                 ImmediateInterruptOK = interruptOK;
414                 CHECK_FOR_INTERRUPTS();
415                 errStatus = semop(sema->semId, &sops, 1);
416                 ImmediateInterruptOK = false;
417         } while (errStatus < 0 && errno == EINTR);
418
419         if (errStatus < 0)
420                 elog(FATAL, "semop(id=%d) failed: %m", sema->semId);
421 }
422
423 /*
424  * PGSemaphoreUnlock
425  *
426  * Unlock a semaphore (increment count)
427  */
428 void
429 PGSemaphoreUnlock(PGSemaphore sema)
430 {
431         int                     errStatus;
432         struct sembuf sops;
433
434         sops.sem_op = 1;                        /* increment */
435         sops.sem_flg = 0;
436         sops.sem_num = sema->semNum;
437
438         /*
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.
443          */
444         do
445         {
446                 errStatus = semop(sema->semId, &sops, 1);
447         } while (errStatus < 0 && errno == EINTR);
448
449         if (errStatus < 0)
450                 elog(FATAL, "semop(id=%d) failed: %m", sema->semId);
451 }
452
453 /*
454  * PGSemaphoreTryLock
455  *
456  * Lock a semaphore only if able to do so without blocking
457  */
458 bool
459 PGSemaphoreTryLock(PGSemaphore sema)
460 {
461         int                     errStatus;
462         struct sembuf sops;
463
464         sops.sem_op = -1;                       /* decrement */
465         sops.sem_flg = IPC_NOWAIT;      /* but don't block */
466         sops.sem_num = sema->semNum;
467
468         /*
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.
472          */
473         do
474         {
475                 errStatus = semop(sema->semId, &sops, 1);
476         } while (errStatus < 0 && errno == EINTR);
477
478         if (errStatus < 0)
479         {
480                 /* Expect EAGAIN or EWOULDBLOCK (platform-dependent) */
481 #ifdef EAGAIN
482                 if (errno == EAGAIN)
483                         return false;           /* failed to lock it */
484 #endif
485 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
486                 if (errno == EWOULDBLOCK)
487                         return false;           /* failed to lock it */
488 #endif
489                 /* Otherwise we got trouble */
490                 elog(FATAL, "semop(id=%d) failed: %m", sema->semId);
491         }
492
493         return true;
494 }