PostgreSQL Source Code  git master
sysv_shmem.c File Reference
#include "postgres.h"
#include <signal.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include "miscadmin.h"
#include "port/pg_bitutils.h"
#include "portability/mem.h"
#include "storage/dsm.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
#include "utils/guc_hooks.h"
#include "utils/pidfile.h"
Include dependency graph for sysv_shmem.c:

Go to the source code of this file.

Typedefs

typedef key_t IpcMemoryKey
 
typedef int IpcMemoryId
 

Enumerations

enum  IpcMemoryState {
  SHMSTATE_ANALYSIS_FAILURE , SHMSTATE_ATTACHED , SHMSTATE_ENOENT , SHMSTATE_FOREIGN ,
  SHMSTATE_UNATTACHED
}
 

Functions

static void * InternalIpcMemoryCreate (IpcMemoryKey memKey, Size size)
 
static void IpcMemoryDetach (int status, Datum shmaddr)
 
static void IpcMemoryDelete (int status, Datum shmId)
 
static IpcMemoryState PGSharedMemoryAttach (IpcMemoryId shmId, void *attachAt, PGShmemHeader **addr)
 
bool PGSharedMemoryIsInUse (unsigned long id1, unsigned long id2)
 
void GetHugePageSize (Size *hugepagesize, int *mmap_flags)
 
bool check_huge_page_size (int *newval, void **extra, GucSource source)
 
static void * CreateAnonymousSegment (Size *size)
 
static void AnonymousShmemDetach (int status, Datum arg)
 
PGShmemHeaderPGSharedMemoryCreate (Size size, PGShmemHeader **shim)
 
void PGSharedMemoryDetach (void)
 

Variables

unsigned long UsedShmemSegID = 0
 
void * UsedShmemSegAddr = NULL
 
static Size AnonymousShmemSize
 
static void * AnonymousShmem = NULL
 

Typedef Documentation

◆ IpcMemoryId

typedef int IpcMemoryId

Definition at line 70 of file sysv_shmem.c.

◆ IpcMemoryKey

Definition at line 69 of file sysv_shmem.c.

Enumeration Type Documentation

◆ IpcMemoryState

Enumerator
SHMSTATE_ANALYSIS_FAILURE 
SHMSTATE_ATTACHED 
SHMSTATE_ENOENT 
SHMSTATE_FOREIGN 
SHMSTATE_UNATTACHED 

Definition at line 83 of file sysv_shmem.c.

84 {
85  SHMSTATE_ANALYSIS_FAILURE, /* unexpected failure to analyze the ID */
86  SHMSTATE_ATTACHED, /* pertinent to DataDir, has attached PIDs */
87  SHMSTATE_ENOENT, /* no segment of that ID */
88  SHMSTATE_FOREIGN, /* exists, but not pertinent to DataDir */
89  SHMSTATE_UNATTACHED /* pertinent to DataDir, no attached PIDs */
IpcMemoryState
Definition: sysv_shmem.c:84
@ SHMSTATE_ATTACHED
Definition: sysv_shmem.c:86
@ SHMSTATE_UNATTACHED
Definition: sysv_shmem.c:89
@ SHMSTATE_FOREIGN
Definition: sysv_shmem.c:88
@ SHMSTATE_ENOENT
Definition: sysv_shmem.c:87
@ SHMSTATE_ANALYSIS_FAILURE
Definition: sysv_shmem.c:85

Function Documentation

◆ AnonymousShmemDetach()

static void AnonymousShmemDetach ( int  status,
Datum  arg 
)
static

Definition at line 666 of file sysv_shmem.c.

667 {
668  /* Release anonymous shared memory block, if any. */
669  if (AnonymousShmem != NULL)
670  {
671  if (munmap(AnonymousShmem, AnonymousShmemSize) < 0)
672  elog(LOG, "munmap(%p, %zu) failed: %m",
674  AnonymousShmem = NULL;
675  }
676 }
#define LOG
Definition: elog.h:31
static Size AnonymousShmemSize
Definition: sysv_shmem.c:96
static void * AnonymousShmem
Definition: sysv_shmem.c:97

References AnonymousShmem, AnonymousShmemSize, elog(), and LOG.

Referenced by PGSharedMemoryCreate().

◆ check_huge_page_size()

bool check_huge_page_size ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 577 of file sysv_shmem.c.

578 {
579 #if !(defined(MAP_HUGE_MASK) && defined(MAP_HUGE_SHIFT))
580  /* Recent enough Linux only, for now. See GetHugePageSize(). */
581  if (*newval != 0)
582  {
583  GUC_check_errdetail("huge_page_size must be 0 on this platform.");
584  return false;
585  }
586 #endif
587  return true;
588 }
#define newval
#define GUC_check_errdetail
Definition: guc.h:437

References GUC_check_errdetail, and newval.

◆ CreateAnonymousSegment()

static void* CreateAnonymousSegment ( Size size)
static

Definition at line 598 of file sysv_shmem.c.

599 {
600  Size allocsize = *size;
601  void *ptr = MAP_FAILED;
602  int mmap_errno = 0;
603 
604 #ifndef MAP_HUGETLB
605  /* PGSharedMemoryCreate should have dealt with this case */
607 #else
609  {
610  /*
611  * Round up the request size to a suitable large value.
612  */
613  Size hugepagesize;
614  int mmap_flags;
615 
616  GetHugePageSize(&hugepagesize, &mmap_flags);
617 
618  if (allocsize % hugepagesize != 0)
619  allocsize += hugepagesize - (allocsize % hugepagesize);
620 
621  ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
622  PG_MMAP_FLAGS | mmap_flags, -1, 0);
623  mmap_errno = errno;
624  if (huge_pages == HUGE_PAGES_TRY && ptr == MAP_FAILED)
625  elog(DEBUG1, "mmap(%zu) with MAP_HUGETLB failed, huge pages disabled: %m",
626  allocsize);
627  }
628 #endif
629 
630  if (ptr == MAP_FAILED && huge_pages != HUGE_PAGES_ON)
631  {
632  /*
633  * Use the original size, not the rounded-up value, when falling back
634  * to non-huge pages.
635  */
636  allocsize = *size;
637  ptr = mmap(NULL, allocsize, PROT_READ | PROT_WRITE,
638  PG_MMAP_FLAGS, -1, 0);
639  mmap_errno = errno;
640  }
641 
642  if (ptr == MAP_FAILED)
643  {
644  errno = mmap_errno;
645  ereport(FATAL,
646  (errmsg("could not map anonymous shared memory: %m"),
647  (mmap_errno == ENOMEM) ?
648  errhint("This error usually means that PostgreSQL's request "
649  "for a shared memory segment exceeded available memory, "
650  "swap space, or huge pages. To reduce the request size "
651  "(currently %zu bytes), reduce PostgreSQL's shared "
652  "memory usage, perhaps by reducing shared_buffers or "
653  "max_connections.",
654  allocsize) : 0));
655  }
656 
657  *size = allocsize;
658  return ptr;
659 }
size_t Size
Definition: c.h:589
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define FATAL
Definition: elog.h:41
#define DEBUG1
Definition: elog.h:30
#define ereport(elevel,...)
Definition: elog.h:149
int huge_pages
Definition: guc_tables.c:535
Assert(fmt[strlen(fmt) - 1] !='\n')
#define PG_MMAP_FLAGS
Definition: mem.h:41
#define MAP_FAILED
Definition: mem.h:45
@ HUGE_PAGES_ON
Definition: pg_shmem.h:53
@ HUGE_PAGES_TRY
Definition: pg_shmem.h:54
void GetHugePageSize(Size *hugepagesize, int *mmap_flags)
Definition: sysv_shmem.c:478

References Assert(), DEBUG1, elog(), ereport, errhint(), errmsg(), FATAL, GetHugePageSize(), huge_pages, HUGE_PAGES_ON, HUGE_PAGES_TRY, MAP_FAILED, and PG_MMAP_FLAGS.

Referenced by PGSharedMemoryCreate().

◆ GetHugePageSize()

void GetHugePageSize ( Size hugepagesize,
int *  mmap_flags 
)

Definition at line 478 of file sysv_shmem.c.

479 {
480 #ifdef MAP_HUGETLB
481 
482  Size default_hugepagesize = 0;
483  Size hugepagesize_local = 0;
484  int mmap_flags_local = 0;
485 
486  /*
487  * System-dependent code to find out the default huge page size.
488  *
489  * On Linux, read /proc/meminfo looking for a line like "Hugepagesize:
490  * nnnn kB". Ignore any failures, falling back to the preset default.
491  */
492 #ifdef __linux__
493 
494  {
495  FILE *fp = AllocateFile("/proc/meminfo", "r");
496  char buf[128];
497  unsigned int sz;
498  char ch;
499 
500  if (fp)
501  {
502  while (fgets(buf, sizeof(buf), fp))
503  {
504  if (sscanf(buf, "Hugepagesize: %u %c", &sz, &ch) == 2)
505  {
506  if (ch == 'k')
507  {
508  default_hugepagesize = sz * (Size) 1024;
509  break;
510  }
511  /* We could accept other units besides kB, if needed */
512  }
513  }
514  FreeFile(fp);
515  }
516  }
517 #endif /* __linux__ */
518 
519  if (huge_page_size != 0)
520  {
521  /* If huge page size is requested explicitly, use that. */
522  hugepagesize_local = (Size) huge_page_size * 1024;
523  }
524  else if (default_hugepagesize != 0)
525  {
526  /* Otherwise use the system default, if we have it. */
527  hugepagesize_local = default_hugepagesize;
528  }
529  else
530  {
531  /*
532  * If we fail to find out the system's default huge page size, or no
533  * huge page size is requested explicitly, assume it is 2MB. This will
534  * work fine when the actual size is less. If it's more, we might get
535  * mmap() or munmap() failures due to unaligned requests; but at this
536  * writing, there are no reports of any non-Linux systems being picky
537  * about that.
538  */
539  hugepagesize_local = 2 * 1024 * 1024;
540  }
541 
542  mmap_flags_local = MAP_HUGETLB;
543 
544  /*
545  * On recent enough Linux, also include the explicit page size, if
546  * necessary.
547  */
548 #if defined(MAP_HUGE_MASK) && defined(MAP_HUGE_SHIFT)
549  if (hugepagesize_local != default_hugepagesize)
550  {
551  int shift = pg_ceil_log2_64(hugepagesize_local);
552 
553  mmap_flags_local |= (shift & MAP_HUGE_MASK) << MAP_HUGE_SHIFT;
554  }
555 #endif
556 
557  /* assign the results found */
558  if (mmap_flags)
559  *mmap_flags = mmap_flags_local;
560  if (hugepagesize)
561  *hugepagesize = hugepagesize_local;
562 
563 #else
564 
565  if (hugepagesize)
566  *hugepagesize = 0;
567  if (mmap_flags)
568  *mmap_flags = 0;
569 
570 #endif /* MAP_HUGETLB */
571 }
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2383
int FreeFile(FILE *file)
Definition: fd.c:2581
int huge_page_size
Definition: guc_tables.c:536
static uint64 pg_ceil_log2_64(uint64 num)
Definition: pg_bitutils.h:222
static char * buf
Definition: pg_test_fsync.c:67

References AllocateFile(), buf, FreeFile(), huge_page_size, and pg_ceil_log2_64().

Referenced by CreateAnonymousSegment(), and InitializeShmemGUCs().

◆ InternalIpcMemoryCreate()

static void * InternalIpcMemoryCreate ( IpcMemoryKey  memKey,
Size  size 
)
static

Definition at line 120 of file sysv_shmem.c.

121 {
122  IpcMemoryId shmid;
123  void *requestedAddress = NULL;
124  void *memAddress;
125 
126  /*
127  * Normally we just pass requestedAddress = NULL to shmat(), allowing the
128  * system to choose where the segment gets mapped. But in an EXEC_BACKEND
129  * build, it's possible for whatever is chosen in the postmaster to not
130  * work for backends, due to variations in address space layout. As a
131  * rather klugy workaround, allow the user to specify the address to use
132  * via setting the environment variable PG_SHMEM_ADDR. (If this were of
133  * interest for anything except debugging, we'd probably create a cleaner
134  * and better-documented way to set it, such as a GUC.)
135  */
136 #ifdef EXEC_BACKEND
137  {
138  char *pg_shmem_addr = getenv("PG_SHMEM_ADDR");
139 
140  if (pg_shmem_addr)
141  requestedAddress = (void *) strtoul(pg_shmem_addr, NULL, 0);
142  else
143  {
144 #if defined(__darwin__) && SIZEOF_VOID_P == 8
145  /*
146  * Provide a default value that is believed to avoid problems with
147  * ASLR on the current macOS release.
148  */
149  requestedAddress = (void *) 0x80000000000;
150 #endif
151  }
152  }
153 #endif
154 
155  shmid = shmget(memKey, size, IPC_CREAT | IPC_EXCL | IPCProtection);
156 
157  if (shmid < 0)
158  {
159  int shmget_errno = errno;
160 
161  /*
162  * Fail quietly if error indicates a collision with existing segment.
163  * One would expect EEXIST, given that we said IPC_EXCL, but perhaps
164  * we could get a permission violation instead? Also, EIDRM might
165  * occur if an old seg is slated for destruction but not gone yet.
166  */
167  if (shmget_errno == EEXIST || shmget_errno == EACCES
168 #ifdef EIDRM
169  || shmget_errno == EIDRM
170 #endif
171  )
172  return NULL;
173 
174  /*
175  * Some BSD-derived kernels are known to return EINVAL, not EEXIST, if
176  * there is an existing segment but it's smaller than "size" (this is
177  * a result of poorly-thought-out ordering of error tests). To
178  * distinguish between collision and invalid size in such cases, we
179  * make a second try with size = 0. These kernels do not test size
180  * against SHMMIN in the preexisting-segment case, so we will not get
181  * EINVAL a second time if there is such a segment.
182  */
183  if (shmget_errno == EINVAL)
184  {
185  shmid = shmget(memKey, 0, IPC_CREAT | IPC_EXCL | IPCProtection);
186 
187  if (shmid < 0)
188  {
189  /* As above, fail quietly if we verify a collision */
190  if (errno == EEXIST || errno == EACCES
191 #ifdef EIDRM
192  || errno == EIDRM
193 #endif
194  )
195  return NULL;
196  /* Otherwise, fall through to report the original error */
197  }
198  else
199  {
200  /*
201  * On most platforms we cannot get here because SHMMIN is
202  * greater than zero. However, if we do succeed in creating a
203  * zero-size segment, free it and then fall through to report
204  * the original error.
205  */
206  if (shmctl(shmid, IPC_RMID, NULL) < 0)
207  elog(LOG, "shmctl(%d, %d, 0) failed: %m",
208  (int) shmid, IPC_RMID);
209  }
210  }
211 
212  /*
213  * Else complain and abort.
214  *
215  * Note: at this point EINVAL should mean that either SHMMIN or SHMMAX
216  * is violated. SHMALL violation might be reported as either ENOMEM
217  * (BSDen) or ENOSPC (Linux); the Single Unix Spec fails to say which
218  * it should be. SHMMNI violation is ENOSPC, per spec. Just plain
219  * not-enough-RAM is ENOMEM.
220  */
221  errno = shmget_errno;
222  ereport(FATAL,
223  (errmsg("could not create shared memory segment: %m"),
224  errdetail("Failed system call was shmget(key=%lu, size=%zu, 0%o).",
225  (unsigned long) memKey, size,
227  (shmget_errno == EINVAL) ?
228  errhint("This error usually means that PostgreSQL's request for a shared memory "
229  "segment exceeded your kernel's SHMMAX parameter, or possibly that "
230  "it is less than "
231  "your kernel's SHMMIN parameter.\n"
232  "The PostgreSQL documentation contains more information about shared "
233  "memory configuration.") : 0,
234  (shmget_errno == ENOMEM) ?
235  errhint("This error usually means that PostgreSQL's request for a shared "
236  "memory segment exceeded your kernel's SHMALL parameter. You might need "
237  "to reconfigure the kernel with larger SHMALL.\n"
238  "The PostgreSQL documentation contains more information about shared "
239  "memory configuration.") : 0,
240  (shmget_errno == ENOSPC) ?
241  errhint("This error does *not* mean that you have run out of disk space. "
242  "It occurs either if all available shared memory IDs have been taken, "
243  "in which case you need to raise the SHMMNI parameter in your kernel, "
244  "or because the system's overall limit for shared memory has been "
245  "reached.\n"
246  "The PostgreSQL documentation contains more information about shared "
247  "memory configuration.") : 0));
248  }
249 
250  /* Register on-exit routine to delete the new segment */
252 
253  /* OK, should be able to attach to the segment */
254  memAddress = shmat(shmid, requestedAddress, PG_SHMAT_FLAGS);
255 
256  if (memAddress == (void *) -1)
257  elog(FATAL, "shmat(id=%d, addr=%p, flags=0x%x) failed: %m",
258  shmid, requestedAddress, PG_SHMAT_FLAGS);
259 
260  /* Register on-exit routine to detach new segment before deleting */
262 
263  /*
264  * Store shmem key and ID in data directory lockfile. Format to try to
265  * keep it the same length always (trailing junk in the lockfile won't
266  * hurt, but might confuse humans).
267  */
268  {
269  char line[64];
270 
271  sprintf(line, "%9lu %9lu",
272  (unsigned long) memKey, (unsigned long) shmid);
274  }
275 
276  return memAddress;
277 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
#define PG_SHMAT_FLAGS
Definition: mem.h:20
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1503
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: pidfile.h:43
#define sprintf
Definition: port.h:240
#define IPCProtection
Definition: posix_sema.c:59
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
int IpcMemoryId
Definition: sysv_shmem.c:70
static void IpcMemoryDetach(int status, Datum shmaddr)
Definition: sysv_shmem.c:285
static void IpcMemoryDelete(int status, Datum shmId)
Definition: sysv_shmem.c:297
#define IPC_RMID
Definition: win32_port.h:103
#define IPC_EXCL
Definition: win32_port.h:105
#define IPC_CREAT
Definition: win32_port.h:104
#define EIDRM
Definition: win32_port.h:112

References AddToDataDirLockFile(), EIDRM, elog(), ereport, errdetail(), errhint(), errmsg(), FATAL, Int32GetDatum(), IPC_CREAT, IPC_EXCL, IPC_RMID, IpcMemoryDelete(), IpcMemoryDetach(), IPCProtection, LOCK_FILE_LINE_SHMEM_KEY, LOG, on_shmem_exit(), PG_SHMAT_FLAGS, PointerGetDatum(), and sprintf.

Referenced by PGSharedMemoryCreate().

◆ IpcMemoryDelete()

static void IpcMemoryDelete ( int  status,
Datum  shmId 
)
static

Definition at line 297 of file sysv_shmem.c.

298 {
299  if (shmctl(DatumGetInt32(shmId), IPC_RMID, NULL) < 0)
300  elog(LOG, "shmctl(%d, %d, 0) failed: %m",
301  DatumGetInt32(shmId), IPC_RMID);
302 }
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:202

References DatumGetInt32(), elog(), IPC_RMID, and LOG.

Referenced by InternalIpcMemoryCreate().

◆ IpcMemoryDetach()

static void IpcMemoryDetach ( int  status,
Datum  shmaddr 
)
static

Definition at line 285 of file sysv_shmem.c.

286 {
287  /* Detach System V shared memory block. */
288  if (shmdt((void *) DatumGetPointer(shmaddr)) < 0)
289  elog(LOG, "shmdt(%p) failed: %m", DatumGetPointer(shmaddr));
290 }
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312

References DatumGetPointer(), elog(), and LOG.

Referenced by InternalIpcMemoryCreate().

◆ PGSharedMemoryAttach()

static IpcMemoryState PGSharedMemoryAttach ( IpcMemoryId  shmId,
void *  attachAt,
PGShmemHeader **  addr 
)
static

Definition at line 346 of file sysv_shmem.c.

349 {
350  struct shmid_ds shmStat;
351  struct stat statbuf;
352  PGShmemHeader *hdr;
353 
354  *addr = NULL;
355 
356  /*
357  * First, try to stat the shm segment ID, to see if it exists at all.
358  */
359  if (shmctl(shmId, IPC_STAT, &shmStat) < 0)
360  {
361  /*
362  * EINVAL actually has multiple possible causes documented in the
363  * shmctl man page, but we assume it must mean the segment no longer
364  * exists.
365  */
366  if (errno == EINVAL)
367  return SHMSTATE_ENOENT;
368 
369  /*
370  * EACCES implies we have no read permission, which means it is not a
371  * Postgres shmem segment (or at least, not one that is relevant to
372  * our data directory).
373  */
374  if (errno == EACCES)
375  return SHMSTATE_FOREIGN;
376 
377  /*
378  * Some Linux kernel versions (in fact, all of them as of July 2007)
379  * sometimes return EIDRM when EINVAL is correct. The Linux kernel
380  * actually does not have any internal state that would justify
381  * returning EIDRM, so we can get away with assuming that EIDRM is
382  * equivalent to EINVAL on that platform.
383  */
384 #ifdef HAVE_LINUX_EIDRM_BUG
385  if (errno == EIDRM)
386  return SHMSTATE_ENOENT;
387 #endif
388 
389  /*
390  * Otherwise, we had better assume that the segment is in use. The
391  * only likely case is (non-Linux, assumed spec-compliant) EIDRM,
392  * which implies that the segment has been IPC_RMID'd but there are
393  * still processes attached to it.
394  */
396  }
397 
398  /*
399  * Try to attach to the segment and see if it matches our data directory.
400  * This avoids any risk of duplicate-shmem-key conflicts on machines that
401  * are running several postmasters under the same userid.
402  *
403  * (When we're called from PGSharedMemoryCreate, this stat call is
404  * duplicative; but since this isn't a high-traffic case it's not worth
405  * trying to optimize.)
406  */
407  if (stat(DataDir, &statbuf) < 0)
408  return SHMSTATE_ANALYSIS_FAILURE; /* can't stat; be conservative */
409 
410  hdr = (PGShmemHeader *) shmat(shmId, attachAt, PG_SHMAT_FLAGS);
411  if (hdr == (PGShmemHeader *) -1)
412  {
413  /*
414  * Attachment failed. The cases we're interested in are the same as
415  * for the shmctl() call above. In particular, note that the owning
416  * postmaster could have terminated and removed the segment between
417  * shmctl() and shmat().
418  *
419  * If attachAt isn't NULL, it's possible that EINVAL reflects a
420  * problem with that address not a vanished segment, so it's best to
421  * pass NULL when probing for conflicting segments.
422  */
423  if (errno == EINVAL)
424  return SHMSTATE_ENOENT; /* segment disappeared */
425  if (errno == EACCES)
426  return SHMSTATE_FOREIGN; /* must be non-Postgres */
427 #ifdef HAVE_LINUX_EIDRM_BUG
428  if (errno == EIDRM)
429  return SHMSTATE_ENOENT; /* segment disappeared */
430 #endif
431  /* Otherwise, be conservative. */
433  }
434  *addr = hdr;
435 
436  if (hdr->magic != PGShmemMagic ||
437  hdr->device != statbuf.st_dev ||
438  hdr->inode != statbuf.st_ino)
439  {
440  /*
441  * It's either not a Postgres segment, or not one for my data
442  * directory.
443  */
444  return SHMSTATE_FOREIGN;
445  }
446 
447  /*
448  * It does match our data directory, so now test whether any processes are
449  * still attached to it. (We are, now, but the shm_nattch result is from
450  * before we attached to it.)
451  */
452  return shmStat.shm_nattch == 0 ? SHMSTATE_UNATTACHED : SHMSTATE_ATTACHED;
453 }
char * DataDir
Definition: globals.c:66
#define PGShmemMagic
Definition: pg_shmem.h:32
#define stat
Definition: win32_port.h:286
#define IPC_STAT
Definition: win32_port.h:108

References DataDir, EIDRM, IPC_STAT, PG_SHMAT_FLAGS, PGShmemMagic, SHMSTATE_ANALYSIS_FAILURE, SHMSTATE_ATTACHED, SHMSTATE_ENOENT, SHMSTATE_FOREIGN, SHMSTATE_UNATTACHED, stat::st_dev, stat::st_ino, and stat.

Referenced by PGSharedMemoryCreate(), and PGSharedMemoryIsInUse().

◆ PGSharedMemoryCreate()

PGShmemHeader* PGSharedMemoryCreate ( Size  size,
PGShmemHeader **  shim 
)

Definition at line 691 of file sysv_shmem.c.

693 {
694  IpcMemoryKey NextShmemSegID;
695  void *memAddress;
696  PGShmemHeader *hdr;
697  struct stat statbuf;
698  Size sysvsize;
699 
700  /*
701  * We use the data directory's ID info (inode and device numbers) to
702  * positively identify shmem segments associated with this data dir, and
703  * also as seeds for searching for a free shmem key.
704  */
705  if (stat(DataDir, &statbuf) < 0)
706  ereport(FATAL,
708  errmsg("could not stat data directory \"%s\": %m",
709  DataDir)));
710 
711  /* Complain if hugepages demanded but we can't possibly support them */
712 #if !defined(MAP_HUGETLB)
713  if (huge_pages == HUGE_PAGES_ON)
714  ereport(ERROR,
715  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
716  errmsg("huge pages not supported on this platform")));
717 #endif
718 
719  /* For now, we don't support huge pages in SysV memory */
721  ereport(ERROR,
722  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
723  errmsg("huge pages not supported with the current shared_memory_type setting")));
724 
725  /* Room for a header? */
726  Assert(size > MAXALIGN(sizeof(PGShmemHeader)));
727 
729  {
731  AnonymousShmemSize = size;
732 
733  /* Register on-exit routine to unmap the anonymous segment */
735 
736  /* Now we need only allocate a minimal-sized SysV shmem block. */
737  sysvsize = sizeof(PGShmemHeader);
738  }
739  else
740  sysvsize = size;
741 
742  /*
743  * Loop till we find a free IPC key. Trust CreateDataDirLockFile() to
744  * ensure no more than one postmaster per data directory can enter this
745  * loop simultaneously. (CreateDataDirLockFile() does not entirely ensure
746  * that, but prefer fixing it over coping here.)
747  */
748  NextShmemSegID = statbuf.st_ino;
749 
750  for (;;)
751  {
752  IpcMemoryId shmid;
753  PGShmemHeader *oldhdr;
755 
756  /* Try to create new segment */
757  memAddress = InternalIpcMemoryCreate(NextShmemSegID, sysvsize);
758  if (memAddress)
759  break; /* successful create and attach */
760 
761  /* Check shared memory and possibly remove and recreate */
762 
763  /*
764  * shmget() failure is typically EACCES, hence SHMSTATE_FOREIGN.
765  * ENOENT, a narrow possibility, implies SHMSTATE_ENOENT, but one can
766  * safely treat SHMSTATE_ENOENT like SHMSTATE_FOREIGN.
767  */
768  shmid = shmget(NextShmemSegID, sizeof(PGShmemHeader), 0);
769  if (shmid < 0)
770  {
771  oldhdr = NULL;
773  }
774  else
775  state = PGSharedMemoryAttach(shmid, NULL, &oldhdr);
776 
777  switch (state)
778  {
780  case SHMSTATE_ATTACHED:
781  ereport(FATAL,
782  (errcode(ERRCODE_LOCK_FILE_EXISTS),
783  errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
784  (unsigned long) NextShmemSegID,
785  (unsigned long) shmid),
786  errhint("Terminate any old server processes associated with data directory \"%s\".",
787  DataDir)));
788  break;
789  case SHMSTATE_ENOENT:
790 
791  /*
792  * To our surprise, some other process deleted since our last
793  * InternalIpcMemoryCreate(). Moments earlier, we would have
794  * seen SHMSTATE_FOREIGN. Try that same ID again.
795  */
796  elog(LOG,
797  "shared memory block (key %lu, ID %lu) deleted during startup",
798  (unsigned long) NextShmemSegID,
799  (unsigned long) shmid);
800  break;
801  case SHMSTATE_FOREIGN:
802  NextShmemSegID++;
803  break;
804  case SHMSTATE_UNATTACHED:
805 
806  /*
807  * The segment pertains to DataDir, and every process that had
808  * used it has died or detached. Zap it, if possible, and any
809  * associated dynamic shared memory segments, as well. This
810  * shouldn't fail, but if it does, assume the segment belongs
811  * to someone else after all, and try the next candidate.
812  * Otherwise, try again to create the segment. That may fail
813  * if some other process creates the same shmem key before we
814  * do, in which case we'll try the next key.
815  */
816  if (oldhdr->dsm_control != 0)
818  if (shmctl(shmid, IPC_RMID, NULL) < 0)
819  NextShmemSegID++;
820  break;
821  }
822 
823  if (oldhdr && shmdt((void *) oldhdr) < 0)
824  elog(LOG, "shmdt(%p) failed: %m", oldhdr);
825  }
826 
827  /* Initialize new segment. */
828  hdr = (PGShmemHeader *) memAddress;
829  hdr->creatorPID = getpid();
830  hdr->magic = PGShmemMagic;
831  hdr->dsm_control = 0;
832 
833  /* Fill in the data directory ID info, too */
834  hdr->device = statbuf.st_dev;
835  hdr->inode = statbuf.st_ino;
836 
837  /*
838  * Initialize space allocation status for segment.
839  */
840  hdr->totalsize = size;
841  hdr->freeoffset = MAXALIGN(sizeof(PGShmemHeader));
842  *shim = hdr;
843 
844  /* Save info for possible future use */
845  UsedShmemSegAddr = memAddress;
846  UsedShmemSegID = (unsigned long) NextShmemSegID;
847 
848  /*
849  * If AnonymousShmem is NULL here, then we're not using anonymous shared
850  * memory, and should return a pointer to the System V shared memory
851  * block. Otherwise, the System V shared memory block is only a shim, and
852  * we must return a pointer to the real block.
853  */
854  if (AnonymousShmem == NULL)
855  return hdr;
856  memcpy(AnonymousShmem, hdr, sizeof(PGShmemHeader));
857  return (PGShmemHeader *) AnonymousShmem;
858 }
#define MAXALIGN(LEN)
Definition: c.h:795
void dsm_cleanup_using_control_segment(dsm_handle old_control_handle)
Definition: dsm.c:211
int errcode_for_file_access(void)
Definition: elog.c:881
int errcode(int sqlerrcode)
Definition: elog.c:858
#define ERROR
Definition: elog.h:39
int shared_memory_type
Definition: ipci.c:54
@ SHMEM_TYPE_MMAP
Definition: pg_shmem.h:62
struct PGShmemHeader PGShmemHeader
uintptr_t Datum
Definition: postgres.h:64
dsm_handle dsm_control
Definition: pg_shmem.h:36
ino_t inode
Definition: pg_shmem.h:40
Size freeoffset
Definition: pg_shmem.h:35
pid_t creatorPID
Definition: pg_shmem.h:33
dev_t device
Definition: pg_shmem.h:39
int32 magic
Definition: pg_shmem.h:31
Size totalsize
Definition: pg_shmem.h:34
Definition: regguts.h:318
static void AnonymousShmemDetach(int status, Datum arg)
Definition: sysv_shmem.c:666
static void * CreateAnonymousSegment(Size *size)
Definition: sysv_shmem.c:598
key_t IpcMemoryKey
Definition: sysv_shmem.c:69
unsigned long UsedShmemSegID
Definition: sysv_shmem.c:93
static void * InternalIpcMemoryCreate(IpcMemoryKey memKey, Size size)
Definition: sysv_shmem.c:120
void * UsedShmemSegAddr
Definition: sysv_shmem.c:94
static IpcMemoryState PGSharedMemoryAttach(IpcMemoryId shmId, void *attachAt, PGShmemHeader **addr)
Definition: sysv_shmem.c:346

References AnonymousShmem, AnonymousShmemDetach(), AnonymousShmemSize, Assert(), CreateAnonymousSegment(), PGShmemHeader::creatorPID, DataDir, PGShmemHeader::device, dsm_cleanup_using_control_segment(), PGShmemHeader::dsm_control, elog(), ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, FATAL, PGShmemHeader::freeoffset, huge_pages, HUGE_PAGES_ON, PGShmemHeader::inode, InternalIpcMemoryCreate(), IPC_RMID, LOG, PGShmemHeader::magic, MAXALIGN, on_shmem_exit(), PGSharedMemoryAttach(), PGShmemMagic, shared_memory_type, SHMEM_TYPE_MMAP, SHMSTATE_ANALYSIS_FAILURE, SHMSTATE_ATTACHED, SHMSTATE_ENOENT, SHMSTATE_FOREIGN, SHMSTATE_UNATTACHED, stat::st_dev, stat::st_ino, stat, PGShmemHeader::totalsize, UsedShmemSegAddr, and UsedShmemSegID.

Referenced by CreateSharedMemoryAndSemaphores().

◆ PGSharedMemoryDetach()

void PGSharedMemoryDetach ( void  )

Definition at line 955 of file sysv_shmem.c.

956 {
957  if (UsedShmemSegAddr != NULL)
958  {
959  if ((shmdt(UsedShmemSegAddr) < 0)
960 #if defined(EXEC_BACKEND) && defined(__CYGWIN__)
961  /* Work-around for cygipc exec bug */
962  && shmdt(NULL) < 0
963 #endif
964  )
965  elog(LOG, "shmdt(%p) failed: %m", UsedShmemSegAddr);
966  UsedShmemSegAddr = NULL;
967  }
968 
969  if (AnonymousShmem != NULL)
970  {
971  if (munmap(AnonymousShmem, AnonymousShmemSize) < 0)
972  elog(LOG, "munmap(%p, %zu) failed: %m",
974  AnonymousShmem = NULL;
975  }
976 }

References AnonymousShmem, AnonymousShmemSize, elog(), LOG, and UsedShmemSegAddr.

Referenced by SysLogger_Start().

◆ PGSharedMemoryIsInUse()

bool PGSharedMemoryIsInUse ( unsigned long  id1,
unsigned long  id2 
)

Definition at line 316 of file sysv_shmem.c.

317 {
318  PGShmemHeader *memAddress;
320 
321  state = PGSharedMemoryAttach((IpcMemoryId) id2, NULL, &memAddress);
322  if (memAddress && shmdt((void *) memAddress) < 0)
323  elog(LOG, "shmdt(%p) failed: %m", memAddress);
324  switch (state)
325  {
326  case SHMSTATE_ENOENT:
327  case SHMSTATE_FOREIGN:
328  case SHMSTATE_UNATTACHED:
329  return false;
331  case SHMSTATE_ATTACHED:
332  return true;
333  }
334  return true;
335 }

References elog(), LOG, PGSharedMemoryAttach(), SHMSTATE_ANALYSIS_FAILURE, SHMSTATE_ATTACHED, SHMSTATE_ENOENT, SHMSTATE_FOREIGN, and SHMSTATE_UNATTACHED.

Referenced by CreateLockFile().

Variable Documentation

◆ AnonymousShmem

void* AnonymousShmem = NULL
static

Definition at line 97 of file sysv_shmem.c.

Referenced by AnonymousShmemDetach(), PGSharedMemoryCreate(), and PGSharedMemoryDetach().

◆ AnonymousShmemSize

Size AnonymousShmemSize
static

Definition at line 96 of file sysv_shmem.c.

Referenced by AnonymousShmemDetach(), PGSharedMemoryCreate(), and PGSharedMemoryDetach().

◆ UsedShmemSegAddr

void* UsedShmemSegAddr = NULL

Definition at line 94 of file sysv_shmem.c.

Referenced by PGSharedMemoryCreate(), and PGSharedMemoryDetach().

◆ UsedShmemSegID

unsigned long UsedShmemSegID = 0

Definition at line 93 of file sysv_shmem.c.

Referenced by PGSharedMemoryCreate().