PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
sysv_shmem.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * sysv_shmem.c
4  * Implement shared memory using SysV facilities
5  *
6  * These routines used to be a fairly thin layer on top of SysV shared
7  * memory functionality. With the addition of anonymous-shmem logic,
8  * they're a bit fatter now. We still require a SysV shmem block to
9  * exist, though, because mmap'd shmem provides no way to find out how
10  * many processes are attached, which we need for interlocking purposes.
11  *
12  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  * IDENTIFICATION
16  * src/backend/port/sysv_shmem.c
17  *
18  *-------------------------------------------------------------------------
19  */
20 #include "postgres.h"
21 
22 #include <signal.h>
23 #include <unistd.h>
24 #include <sys/file.h>
25 #include <sys/mman.h>
26 #include <sys/stat.h>
27 #ifdef HAVE_SYS_IPC_H
28 #include <sys/ipc.h>
29 #endif
30 #ifdef HAVE_SYS_SHM_H
31 #include <sys/shm.h>
32 #endif
33 
34 #include "miscadmin.h"
35 #include "portability/mem.h"
36 #include "storage/dsm.h"
37 #include "storage/fd.h"
38 #include "storage/ipc.h"
39 #include "storage/pg_shmem.h"
40 #include "utils/guc.h"
41 
42 
43 /*
44  * As of PostgreSQL 9.3, we normally allocate only a very small amount of
45  * System V shared memory, and only for the purposes of providing an
46  * interlock to protect the data directory. The real shared memory block
47  * is allocated using mmap(). This works around the problem that many
48  * systems have very low limits on the amount of System V shared memory
49  * that can be allocated. Even a limit of a few megabytes will be enough
50  * to run many copies of PostgreSQL without needing to adjust system settings.
51  *
52  * We assume that no one will attempt to run PostgreSQL 9.3 or later on
53  * systems that are ancient enough that anonymous shared memory is not
54  * supported, such as pre-2.4 versions of Linux. If that turns out to be
55  * false, we might need to add compile and/or run-time tests here and do this
56  * only if the running kernel supports it.
57  *
58  * However, we must always disable this logic in the EXEC_BACKEND case, and
59  * fall back to the old method of allocating the entire segment using System V
60  * shared memory, because there's no way to attach an anonymous mmap'd segment
61  * to a process after exec(). Since EXEC_BACKEND is intended only for
62  * developer use, this shouldn't be a big problem. Because of this, we do
63  * not worry about supporting anonymous shmem in the EXEC_BACKEND cases below.
64  */
65 #ifndef EXEC_BACKEND
66 #define USE_ANONYMOUS_SHMEM
67 #endif
68 
69 
70 typedef key_t IpcMemoryKey; /* shared memory key passed to shmget(2) */
71 typedef int IpcMemoryId; /* shared memory ID returned by shmget(2) */
72 
73 
74 unsigned long UsedShmemSegID = 0;
76 
77 #ifdef USE_ANONYMOUS_SHMEM
79 static void *AnonymousShmem = NULL;
80 #endif
81 
82 static void *InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size);
83 static void IpcMemoryDetach(int status, Datum shmaddr);
84 static void IpcMemoryDelete(int status, Datum shmId);
86  IpcMemoryId *shmid);
87 
88 
89 /*
90  * InternalIpcMemoryCreate(memKey, size)
91  *
92  * Attempt to create a new shared memory segment with the specified key.
93  * Will fail (return NULL) if such a segment already exists. If successful,
94  * attach the segment to the current process and return its attached address.
95  * On success, callbacks are registered with on_shmem_exit to detach and
96  * delete the segment when on_shmem_exit is called.
97  *
98  * If we fail with a failure code other than collision-with-existing-segment,
99  * print out an error and abort. Other types of errors are not recoverable.
100  */
101 static void *
103 {
104  IpcMemoryId shmid;
105  void *memAddress;
106 
107  shmid = shmget(memKey, size, IPC_CREAT | IPC_EXCL | IPCProtection);
108 
109  if (shmid < 0)
110  {
111  int shmget_errno = errno;
112 
113  /*
114  * Fail quietly if error indicates a collision with existing segment.
115  * One would expect EEXIST, given that we said IPC_EXCL, but perhaps
116  * we could get a permission violation instead? Also, EIDRM might
117  * occur if an old seg is slated for destruction but not gone yet.
118  */
119  if (shmget_errno == EEXIST || shmget_errno == EACCES
120 #ifdef EIDRM
121  || shmget_errno == EIDRM
122 #endif
123  )
124  return NULL;
125 
126  /*
127  * Some BSD-derived kernels are known to return EINVAL, not EEXIST, if
128  * there is an existing segment but it's smaller than "size" (this is
129  * a result of poorly-thought-out ordering of error tests). To
130  * distinguish between collision and invalid size in such cases, we
131  * make a second try with size = 0. These kernels do not test size
132  * against SHMMIN in the preexisting-segment case, so we will not get
133  * EINVAL a second time if there is such a segment.
134  */
135  if (shmget_errno == EINVAL)
136  {
137  shmid = shmget(memKey, 0, IPC_CREAT | IPC_EXCL | IPCProtection);
138 
139  if (shmid < 0)
140  {
141  /* As above, fail quietly if we verify a collision */
142  if (errno == EEXIST || errno == EACCES
143 #ifdef EIDRM
144  || errno == EIDRM
145 #endif
146  )
147  return NULL;
148  /* Otherwise, fall through to report the original error */
149  }
150  else
151  {
152  /*
153  * On most platforms we cannot get here because SHMMIN is
154  * greater than zero. However, if we do succeed in creating a
155  * zero-size segment, free it and then fall through to report
156  * the original error.
157  */
158  if (shmctl(shmid, IPC_RMID, NULL) < 0)
159  elog(LOG, "shmctl(%d, %d, 0) failed: %m",
160  (int) shmid, IPC_RMID);
161  }
162  }
163 
164  /*
165  * Else complain and abort.
166  *
167  * Note: at this point EINVAL should mean that either SHMMIN or SHMMAX
168  * is violated. SHMALL violation might be reported as either ENOMEM
169  * (BSDen) or ENOSPC (Linux); the Single Unix Spec fails to say which
170  * it should be. SHMMNI violation is ENOSPC, per spec. Just plain
171  * not-enough-RAM is ENOMEM.
172  */
173  errno = shmget_errno;
174  ereport(FATAL,
175  (errmsg("could not create shared memory segment: %m"),
176  errdetail("Failed system call was shmget(key=%lu, size=%zu, 0%o).",
177  (unsigned long) memKey, size,
179  (shmget_errno == EINVAL) ?
180  errhint("This error usually means that PostgreSQL's request for a shared memory "
181  "segment exceeded your kernel's SHMMAX parameter, or possibly that "
182  "it is less than "
183  "your kernel's SHMMIN parameter.\n"
184  "The PostgreSQL documentation contains more information about shared "
185  "memory configuration.") : 0,
186  (shmget_errno == ENOMEM) ?
187  errhint("This error usually means that PostgreSQL's request for a shared "
188  "memory segment exceeded your kernel's SHMALL parameter. You might need "
189  "to reconfigure the kernel with larger SHMALL.\n"
190  "The PostgreSQL documentation contains more information about shared "
191  "memory configuration.") : 0,
192  (shmget_errno == ENOSPC) ?
193  errhint("This error does *not* mean that you have run out of disk space. "
194  "It occurs either if all available shared memory IDs have been taken, "
195  "in which case you need to raise the SHMMNI parameter in your kernel, "
196  "or because the system's overall limit for shared memory has been "
197  "reached.\n"
198  "The PostgreSQL documentation contains more information about shared "
199  "memory configuration.") : 0));
200  }
201 
202  /* Register on-exit routine to delete the new segment */
204 
205  /* OK, should be able to attach to the segment */
206  memAddress = shmat(shmid, NULL, PG_SHMAT_FLAGS);
207 
208  if (memAddress == (void *) -1)
209  elog(FATAL, "shmat(id=%d) failed: %m", shmid);
210 
211  /* Register on-exit routine to detach new segment before deleting */
213 
214  /*
215  * Store shmem key and ID in data directory lockfile. Format to try to
216  * keep it the same length always (trailing junk in the lockfile won't
217  * hurt, but might confuse humans).
218  */
219  {
220  char line[64];
221 
222  sprintf(line, "%9lu %9lu",
223  (unsigned long) memKey, (unsigned long) shmid);
225  }
226 
227  return memAddress;
228 }
229 
230 /****************************************************************************/
231 /* IpcMemoryDetach(status, shmaddr) removes a shared memory segment */
232 /* from process' address space */
233 /* (called as an on_shmem_exit callback, hence funny argument list) */
234 /****************************************************************************/
235 static void
237 {
238  /* Detach System V shared memory block. */
239  if (shmdt(DatumGetPointer(shmaddr)) < 0)
240  elog(LOG, "shmdt(%p) failed: %m", DatumGetPointer(shmaddr));
241 }
242 
243 /****************************************************************************/
244 /* IpcMemoryDelete(status, shmId) deletes a shared memory segment */
245 /* (called as an on_shmem_exit callback, hence funny argument list) */
246 /****************************************************************************/
247 static void
249 {
250  if (shmctl(DatumGetInt32(shmId), IPC_RMID, NULL) < 0)
251  elog(LOG, "shmctl(%d, %d, 0) failed: %m",
252  DatumGetInt32(shmId), IPC_RMID);
253 }
254 
255 /*
256  * PGSharedMemoryIsInUse
257  *
258  * Is a previously-existing shmem segment still existing and in use?
259  *
260  * The point of this exercise is to detect the case where a prior postmaster
261  * crashed, but it left child backends that are still running. Therefore
262  * we only care about shmem segments that are associated with the intended
263  * DataDir. This is an important consideration since accidental matches of
264  * shmem segment IDs are reasonably common.
265  */
266 bool
267 PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
268 {
269  IpcMemoryId shmId = (IpcMemoryId) id2;
270  struct shmid_ds shmStat;
271  struct stat statbuf;
272  PGShmemHeader *hdr;
273 
274  /*
275  * We detect whether a shared memory segment is in use by seeing whether
276  * it (a) exists and (b) has any processes attached to it.
277  */
278  if (shmctl(shmId, IPC_STAT, &shmStat) < 0)
279  {
280  /*
281  * EINVAL actually has multiple possible causes documented in the
282  * shmctl man page, but we assume it must mean the segment no longer
283  * exists.
284  */
285  if (errno == EINVAL)
286  return false;
287 
288  /*
289  * EACCES implies that the segment belongs to some other userid, which
290  * means it is not a Postgres shmem segment (or at least, not one that
291  * is relevant to our data directory).
292  */
293  if (errno == EACCES)
294  return false;
295 
296  /*
297  * Some Linux kernel versions (in fact, all of them as of July 2007)
298  * sometimes return EIDRM when EINVAL is correct. The Linux kernel
299  * actually does not have any internal state that would justify
300  * returning EIDRM, so we can get away with assuming that EIDRM is
301  * equivalent to EINVAL on that platform.
302  */
303 #ifdef HAVE_LINUX_EIDRM_BUG
304  if (errno == EIDRM)
305  return false;
306 #endif
307 
308  /*
309  * Otherwise, we had better assume that the segment is in use. The
310  * only likely case is EIDRM, which implies that the segment has been
311  * IPC_RMID'd but there are still processes attached to it.
312  */
313  return true;
314  }
315 
316  /* If it has no attached processes, it's not in use */
317  if (shmStat.shm_nattch == 0)
318  return false;
319 
320  /*
321  * Try to attach to the segment and see if it matches our data directory.
322  * This avoids shmid-conflict problems on machines that are running
323  * several postmasters under the same userid.
324  */
325  if (stat(DataDir, &statbuf) < 0)
326  return true; /* if can't stat, be conservative */
327 
328  hdr = (PGShmemHeader *) shmat(shmId, NULL, PG_SHMAT_FLAGS);
329 
330  if (hdr == (PGShmemHeader *) -1)
331  return true; /* if can't attach, be conservative */
332 
333  if (hdr->magic != PGShmemMagic ||
334  hdr->device != statbuf.st_dev ||
335  hdr->inode != statbuf.st_ino)
336  {
337  /*
338  * It's either not a Postgres segment, or not one for my data
339  * directory. In either case it poses no threat.
340  */
341  shmdt((void *) hdr);
342  return false;
343  }
344 
345  /* Trouble --- looks a lot like there's still live backends */
346  shmdt((void *) hdr);
347 
348  return true;
349 }
350 
351 #ifdef USE_ANONYMOUS_SHMEM
352 
353 #ifdef MAP_HUGETLB
354 
355 /*
356  * Identify the huge page size to use.
357  *
358  * Some Linux kernel versions have a bug causing mmap() to fail on requests
359  * that are not a multiple of the hugepage size. Versions without that bug
360  * instead silently round the request up to the next hugepage multiple ---
361  * and then munmap() fails when we give it a size different from that.
362  * So we have to round our request up to a multiple of the actual hugepage
363  * size to avoid trouble.
364  *
365  * Doing the round-up ourselves also lets us make use of the extra memory,
366  * rather than just wasting it. Currently, we just increase the available
367  * space recorded in the shmem header, which will make the extra usable for
368  * purposes such as additional locktable entries. Someday, for very large
369  * hugepage sizes, we might want to think about more invasive strategies,
370  * such as increasing shared_buffers to absorb the extra space.
371  *
372  * Returns the (real or assumed) page size into *hugepagesize,
373  * and the hugepage-related mmap flags to use into *mmap_flags.
374  *
375  * Currently *mmap_flags is always just MAP_HUGETLB. Someday, on systems
376  * that support it, we might OR in additional bits to specify a particular
377  * non-default huge page size.
378  */
379 static void
380 GetHugePageSize(Size *hugepagesize, int *mmap_flags)
381 {
382  /*
383  * If we fail to find out the system's default huge page size, assume it
384  * is 2MB. This will work fine when the actual size is less. If it's
385  * more, we might get mmap() or munmap() failures due to unaligned
386  * requests; but at this writing, there are no reports of any non-Linux
387  * systems being picky about that.
388  */
389  *hugepagesize = 2 * 1024 * 1024;
390  *mmap_flags = MAP_HUGETLB;
391 
392  /*
393  * System-dependent code to find out the default huge page size.
394  *
395  * On Linux, read /proc/meminfo looking for a line like "Hugepagesize:
396  * nnnn kB". Ignore any failures, falling back to the preset default.
397  */
398 #ifdef __linux__
399  {
400  FILE *fp = AllocateFile("/proc/meminfo", "r");
401  char buf[128];
402  unsigned int sz;
403  char ch;
404 
405  if (fp)
406  {
407  while (fgets(buf, sizeof(buf), fp))
408  {
409  if (sscanf(buf, "Hugepagesize: %u %c", &sz, &ch) == 2)
410  {
411  if (ch == 'k')
412  {
413  *hugepagesize = sz * (Size) 1024;
414  break;
415  }
416  /* We could accept other units besides kB, if needed */
417  }
418  }
419  FreeFile(fp);
420  }
421  }
422 #endif /* __linux__ */
423 }
424 
425 #endif /* MAP_HUGETLB */
426 
427 /*
428  * Creates an anonymous mmap()ed shared memory segment.
429  *
430  * Pass the requested size in *size. This function will modify *size to the
431  * actual size of the allocation, if it ends up allocating a segment that is
432  * larger than requested.
433  */
434 static void *
436 {
437  Size allocsize = *size;
438  void *ptr = MAP_FAILED;
439  int mmap_errno = 0;
440 
441 #ifndef MAP_HUGETLB
442  /* PGSharedMemoryCreate should have dealt with this case */
444 #else
446  {
447  /*
448  * Round up the request size to a suitable large value.
449  */
450  Size hugepagesize;
451  int mmap_flags;
452 
453  GetHugePageSize(&hugepagesize, &mmap_flags);
454 
455  if (allocsize % hugepagesize != 0)
456  allocsize += hugepagesize - (allocsize % hugepagesize);
457 
458  ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
459  PG_MMAP_FLAGS | mmap_flags, -1, 0);
460  mmap_errno = errno;
461  if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
462  elog(DEBUG1, "mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
463  allocsize);
464  }
465 #endif
466 
467  if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
468  {
469  /*
470  * Use the original size, not the rounded-up value, when falling back
471  * to non-huge pages.
472  */
473  allocsize = *size;
474  ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
475  PG_MMAP_FLAGS, -1, 0);
476  mmap_errno = errno;
477  }
478 
479  if (ptr == MAP_FAILED)
480  {
481  errno = mmap_errno;
482  ereport(FATAL,
483  (errmsg("could not map anonymous shared memory: %m"),
484  (mmap_errno == ENOMEM) ?
485  errhint("This error usually means that PostgreSQL's request "
486  "for a shared memory segment exceeded available memory, "
487  "swap space, or huge pages. To reduce the request size "
488  "(currently %zu bytes), reduce PostgreSQL's shared "
489  "memory usage, perhaps by reducing shared_buffers or "
490  "max_connections.",
491  *size) : 0));
492  }
493 
494  *size = allocsize;
495  return ptr;
496 }
497 
498 /*
499  * AnonymousShmemDetach --- detach from an anonymous mmap'd block
500  * (called as an on_shmem_exit callback, hence funny argument list)
501  */
502 static void
504 {
505  /* Release anonymous shared memory block, if any. */
506  if (AnonymousShmem != NULL)
507  {
508  if (munmap(AnonymousShmem, AnonymousShmemSize) < 0)
509  elog(LOG, "munmap(%p, %zu) failed: %m",
512  }
513 }
514 
515 #endif /* USE_ANONYMOUS_SHMEM */
516 
517 /*
518  * PGSharedMemoryCreate
519  *
520  * Create a shared memory segment of the given size and initialize its
521  * standard header. Also, register an on_shmem_exit callback to release
522  * the storage.
523  *
524  * Dead Postgres segments are recycled if found, but we do not fail upon
525  * collision with non-Postgres shmem segments. The idea here is to detect and
526  * re-use keys that may have been assigned by a crashed postmaster or backend.
527  *
528  * makePrivate means to always create a new segment, rather than attach to
529  * or recycle any existing segment.
530  *
531  * The port number is passed for possible use as a key (for SysV, we use
532  * it to generate the starting shmem key). In a standalone backend,
533  * zero will be passed.
534  */
536 PGSharedMemoryCreate(Size size, bool makePrivate, int port,
537  PGShmemHeader **shim)
538 {
539  IpcMemoryKey NextShmemSegID;
540  void *memAddress;
541  PGShmemHeader *hdr;
542  IpcMemoryId shmid;
543  struct stat statbuf;
544  Size sysvsize;
545 
546  /* Complain if hugepages demanded but we can't possibly support them */
547 #if !defined(USE_ANONYMOUS_SHMEM) || !defined(MAP_HUGETLB)
548  if (huge_pages == HUGE_PAGES_ON)
549  ereport(ERROR,
550  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
551  errmsg("huge pages not supported on this platform")));
552 #endif
553 
554  /* Room for a header? */
555  Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
556 
557 #ifdef USE_ANONYMOUS_SHMEM
559  AnonymousShmemSize = size;
560 
561  /* Register on-exit routine to unmap the anonymous segment */
563 
564  /* Now we need only allocate a minimal-sized SysV shmem block. */
565  sysvsize = sizeof(PGShmemHeader);
566 #else
567  sysvsize = size;
568 #endif
569 
570  /* Make sure PGSharedMemoryAttach doesn't fail without need */
572 
573  /* Loop till we find a free IPC key */
574  NextShmemSegID = port * 1000;
575 
576  for (NextShmemSegID++;; NextShmemSegID++)
577  {
578  /* Try to create new segment */
579  memAddress = InternalIpcMemoryCreate(NextShmemSegID, sysvsize);
580  if (memAddress)
581  break; /* successful create and attach */
582 
583  /* Check shared memory and possibly remove and recreate */
584 
585  if (makePrivate) /* a standalone backend shouldn't do this */
586  continue;
587 
588  if ((memAddress = PGSharedMemoryAttach(NextShmemSegID, &shmid)) == NULL)
589  continue; /* can't attach, not one of mine */
590 
591  /*
592  * If I am not the creator and it belongs to an extant process,
593  * continue.
594  */
595  hdr = (PGShmemHeader *) memAddress;
596  if (hdr->creatorPID != getpid())
597  {
598  if (kill(hdr->creatorPID, 0) == 0 || errno != ESRCH)
599  {
600  shmdt(memAddress);
601  continue; /* segment belongs to a live process */
602  }
603  }
604 
605  /*
606  * The segment appears to be from a dead Postgres process, or from a
607  * previous cycle of life in this same process. Zap it, if possible,
608  * and any associated dynamic shared memory segments, as well. This
609  * probably shouldn't fail, but if it does, assume the segment belongs
610  * to someone else after all, and continue quietly.
611  */
612  if (hdr->dsm_control != 0)
614  shmdt(memAddress);
615  if (shmctl(shmid, IPC_RMID, NULL) < 0)
616  continue;
617 
618  /*
619  * Now try again to create the segment.
620  */
621  memAddress = InternalIpcMemoryCreate(NextShmemSegID, sysvsize);
622  if (memAddress)
623  break; /* successful create and attach */
624 
625  /*
626  * Can only get here if some other process managed to create the same
627  * shmem key before we did. Let him have that one, loop around to try
628  * next key.
629  */
630  }
631 
632  /*
633  * OK, we created a new segment. Mark it as created by this process. The
634  * order of assignments here is critical so that another Postgres process
635  * can't see the header as valid but belonging to an invalid PID!
636  */
637  hdr = (PGShmemHeader *) memAddress;
638  hdr->creatorPID = getpid();
639  hdr->magic = PGShmemMagic;
640  hdr->dsm_control = 0;
641 
642  /* Fill in the data directory ID info, too */
643  if (stat(DataDir, &statbuf) < 0)
644  ereport(FATAL,
646  errmsg("could not stat data directory \"%s\": %m",
647  DataDir)));
648  hdr->device = statbuf.st_dev;
649  hdr->inode = statbuf.st_ino;
650 
651  /*
652  * Initialize space allocation status for segment.
653  */
654  hdr->totalsize = size;
655  hdr->freeoffset = MAXALIGN(sizeof(PGShmemHeader));
656  *shim = hdr;
657 
658  /* Save info for possible future use */
659  UsedShmemSegAddr = memAddress;
660  UsedShmemSegID = (unsigned long) NextShmemSegID;
661 
662  /*
663  * If AnonymousShmem is NULL here, then we're not using anonymous shared
664  * memory, and should return a pointer to the System V shared memory
665  * block. Otherwise, the System V shared memory block is only a shim, and
666  * we must return a pointer to the real block.
667  */
668 #ifdef USE_ANONYMOUS_SHMEM
669  if (AnonymousShmem == NULL)
670  return hdr;
671  memcpy(AnonymousShmem, hdr, sizeof(PGShmemHeader));
672  return (PGShmemHeader *) AnonymousShmem;
673 #else
674  return hdr;
675 #endif
676 }
677 
678 #ifdef EXEC_BACKEND
679 
680 /*
681  * PGSharedMemoryReAttach
682  *
683  * This is called during startup of a postmaster child process to re-attach to
684  * an already existing shared memory segment. This is needed only in the
685  * EXEC_BACKEND case; otherwise postmaster children inherit the shared memory
686  * segment attachment via fork().
687  *
688  * UsedShmemSegID and UsedShmemSegAddr are implicit parameters to this
689  * routine. The caller must have already restored them to the postmaster's
690  * values.
691  */
692 void
694 {
695  IpcMemoryId shmid;
696  void *hdr;
697  void *origUsedShmemSegAddr = UsedShmemSegAddr;
698 
701 
702 #ifdef __CYGWIN__
703  /* cygipc (currently) appears to not detach on exec. */
705  UsedShmemSegAddr = origUsedShmemSegAddr;
706 #endif
707 
708  elog(DEBUG3, "attaching to %p", UsedShmemSegAddr);
709  hdr = (void *) PGSharedMemoryAttach((IpcMemoryKey) UsedShmemSegID, &shmid);
710  if (hdr == NULL)
711  elog(FATAL, "could not reattach to shared memory (key=%d, addr=%p): %m",
713  if (hdr != origUsedShmemSegAddr)
714  elog(FATAL, "reattaching to shared memory returned unexpected address (got %p, expected %p)",
715  hdr, origUsedShmemSegAddr);
716  dsm_set_control_handle(((PGShmemHeader *) hdr)->dsm_control);
717 
718  UsedShmemSegAddr = hdr; /* probably redundant */
719 }
720 
721 /*
722  * PGSharedMemoryNoReAttach
723  *
724  * This is called during startup of a postmaster child process when we choose
725  * *not* to re-attach to the existing shared memory segment. We must clean up
726  * to leave things in the appropriate state. This is not used in the non
727  * EXEC_BACKEND case, either.
728  *
729  * The child process startup logic might or might not call PGSharedMemoryDetach
730  * after this; make sure that it will be a no-op if called.
731  *
732  * UsedShmemSegID and UsedShmemSegAddr are implicit parameters to this
733  * routine. The caller must have already restored them to the postmaster's
734  * values.
735  */
736 void
738 {
741 
742 #ifdef __CYGWIN__
743  /* cygipc (currently) appears to not detach on exec. */
745 #endif
746 
747  /* For cleanliness, reset UsedShmemSegAddr to show we're not attached. */
749  /* And the same for UsedShmemSegID. */
750  UsedShmemSegID = 0;
751 }
752 
753 #endif /* EXEC_BACKEND */
754 
755 /*
756  * PGSharedMemoryDetach
757  *
758  * Detach from the shared memory segment, if still attached. This is not
759  * intended to be called explicitly by the process that originally created the
760  * segment (it will have on_shmem_exit callback(s) registered to do that).
761  * Rather, this is for subprocesses that have inherited an attachment and want
762  * to get rid of it.
763  *
764  * UsedShmemSegID and UsedShmemSegAddr are implicit parameters to this
765  * routine, also AnonymousShmem and AnonymousShmemSize.
766  */
767 void
769 {
770  if (UsedShmemSegAddr != NULL)
771  {
772  if ((shmdt(UsedShmemSegAddr) < 0)
773 #if defined(EXEC_BACKEND) && defined(__CYGWIN__)
774  /* Work-around for cygipc exec bug */
775  && shmdt(NULL) < 0
776 #endif
777  )
778  elog(LOG, "shmdt(%p) failed: %m", UsedShmemSegAddr);
780  }
781 
782 #ifdef USE_ANONYMOUS_SHMEM
783  if (AnonymousShmem != NULL)
784  {
785  if (munmap(AnonymousShmem, AnonymousShmemSize) < 0)
786  elog(LOG, "munmap(%p, %zu) failed: %m",
789  }
790 #endif
791 }
792 
793 
794 /*
795  * Attach to shared memory and make sure it has a Postgres header
796  *
797  * Returns attach address if OK, else NULL
798  */
799 static PGShmemHeader *
801 {
802  PGShmemHeader *hdr;
803 
804  if ((*shmid = shmget(key, sizeof(PGShmemHeader), 0)) < 0)
805  return NULL;
806 
807  hdr = (PGShmemHeader *) shmat(*shmid, UsedShmemSegAddr, PG_SHMAT_FLAGS);
808 
809  if (hdr == (PGShmemHeader *) -1)
810  return NULL; /* failed: must be some other app's */
811 
812  if (hdr->magic != PGShmemMagic)
813  {
814  shmdt((void *) hdr);
815  return NULL; /* segment belongs to a non-Postgres app */
816  }
817 
818  return hdr;
819 }
#define IPC_CREAT
Definition: win32.h:115
#define IPC_EXCL
Definition: win32.h:116
pid_t creatorPID
Definition: pg_shmem.h:33
#define MAP_FAILED
Definition: mem.h:45
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
static void IpcMemoryDetach(int status, Datum shmaddr)
Definition: sysv_shmem.c:236
#define DatumGetInt32(X)
Definition: postgres.h:480
#define DEBUG3
Definition: elog.h:23
void dsm_cleanup_using_control_segment(dsm_handle old_control_handle)
Definition: dsm.c:210
static PGShmemHeader * PGSharedMemoryAttach(IpcMemoryKey key, IpcMemoryId *shmid)
Definition: sysv_shmem.c:800
dsm_handle dsm_control
Definition: pg_shmem.h:36
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1148
#define PointerGetDatum(X)
Definition: postgres.h:564
#define IPCProtection
Definition: posix_sema.c:52
#define PG_SHMAT_FLAGS
Definition: mem.h:20
#define IPC_STAT
Definition: win32.h:119
struct PGShmemHeader PGShmemHeader
static Size AnonymousShmemSize
Definition: sysv_shmem.c:78
void PGSharedMemoryNoReAttach(void)
Definition: win32_shmem.c:315
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
void PGSharedMemoryDetach(void)
Definition: sysv_shmem.c:768
long key_t
Definition: win32.h:263
static void * InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size)
Definition: sysv_shmem.c:102
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:348
static char * buf
Definition: pg_test_fsync.c:65
#define PG_MMAP_FLAGS
Definition: mem.h:41
key_t IpcMemoryKey
Definition: sysv_shmem.c:70
bool IsUnderPostmaster
Definition: globals.c:100
int errdetail(const char *fmt,...)
Definition: elog.c:873
void PGSharedMemoryReAttach(void)
Definition: win32_shmem.c:271
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2043
void * UsedShmemSegAddr
Definition: sysv_shmem.c:75
static void AnonymousShmemDetach(int status, Datum arg)
Definition: sysv_shmem.c:503
#define ereport(elevel, rest)
Definition: elog.h:122
static void IpcMemoryDelete(int status, Datum shmId)
Definition: sysv_shmem.c:248
static int port
Definition: pg_regress.c:87
int32 magic
Definition: pg_shmem.h:31
static void * CreateAnonymousSegment(Size *size)
Definition: sysv_shmem.c:435
Size totalsize
Definition: pg_shmem.h:34
uintptr_t Datum
Definition: postgres.h:374
unsigned long UsedShmemSegID
Definition: sysv_shmem.c:74
#define IPC_RMID
Definition: win32.h:114
static void * AnonymousShmem
Definition: sysv_shmem.c:79
ino_t inode
Definition: pg_shmem.h:40
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: miscadmin.h:452
static dsm_control_header * dsm_control
Definition: dsm.c:134
dev_t device
Definition: pg_shmem.h:39
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define PGShmemMagic
Definition: pg_shmem.h:32
Size freeoffset
Definition: pg_shmem.h:35
size_t Size
Definition: c.h:353
PGShmemHeader * PGSharedMemoryCreate(Size size, bool makePrivate, int port, PGShmemHeader **shim)
Definition: sysv_shmem.c:536
#define MAXALIGN(LEN)
Definition: c.h:584
int IpcMemoryId
Definition: sysv_shmem.c:71
int huge_pages
Definition: guc.c:489
#define DatumGetPointer(X)
Definition: postgres.h:557
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:267
int FreeFile(FILE *file)
Definition: fd.c:2226
#define Int32GetDatum(X)
Definition: postgres.h:487
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * arg
char * DataDir
Definition: globals.c:59
#define EIDRM
Definition: win32.h:123
#define elog
Definition: elog.h:219
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:222