PostgreSQL Source Code  git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
ipc.h File Reference
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
 
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
 

Typedefs

typedef void(* pg_on_exit_callback) (int code, Datum arg)
 
typedef void(* shmem_startup_hook_type) (void)
 

Functions

void proc_exit (int code) pg_attribute_noreturn()
 
void shmem_exit (int code)
 
void on_proc_exit (pg_on_exit_callback function, Datum arg)
 
void on_shmem_exit (pg_on_exit_callback function, Datum arg)
 
void before_shmem_exit (pg_on_exit_callback function, Datum arg)
 
void cancel_before_shmem_exit (pg_on_exit_callback function, Datum arg)
 
void on_exit_reset (void)
 
void check_on_shmem_exit_lists_are_empty (void)
 
Size CalculateShmemSize (int *num_semaphores)
 
void CreateSharedMemoryAndSemaphores (void)
 
void InitializeShmemGUCs (void)
 

Variables

PGDLLIMPORT bool proc_exit_inprogress
 
PGDLLIMPORT bool shmem_exit_inprogress
 
PGDLLIMPORT shmem_startup_hook_type shmem_startup_hook
 

Macro Definition Documentation

◆ PG_END_ENSURE_ERROR_CLEANUP

#define PG_END_ENSURE_ERROR_CLEANUP (   cleanup_function,
  arg 
)
Value:
cancel_before_shmem_exit(cleanup_function, arg); \
PG_CATCH(); \
{ \
cancel_before_shmem_exit(cleanup_function, arg); \
cleanup_function (0, arg); \
PG_RE_THROW(); \
} \
PG_END_TRY(); \
} while (0)
void cancel_before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:394
void * arg

Definition at line 52 of file ipc.h.

◆ PG_ENSURE_ERROR_CLEANUP

#define PG_ENSURE_ERROR_CLEANUP (   cleanup_function,
  arg 
)
Value:
do { \
before_shmem_exit(cleanup_function, arg); \
PG_TRY()

Definition at line 47 of file ipc.h.

Typedef Documentation

◆ pg_on_exit_callback

typedef void(* pg_on_exit_callback) (int code, Datum arg)

Definition at line 21 of file ipc.h.

◆ shmem_startup_hook_type

typedef void(* shmem_startup_hook_type) (void)

Definition at line 22 of file ipc.h.

Function Documentation

◆ before_shmem_exit()

void before_shmem_exit ( pg_on_exit_callback  function,
Datum  arg 
)

Definition at line 337 of file ipc.c.

338 {
340  ereport(FATAL,
341  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
342  errmsg_internal("out of before_shmem_exit slots")));
343 
346 
348 
350  {
351  atexit(atexit_callback);
352  atexit_callback_setup = true;
353  }
354 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errcode(int sqlerrcode)
Definition: elog.c:853
#define FATAL
Definition: elog.h:41
#define ereport(elevel,...)
Definition: elog.h:149
static bool atexit_callback_setup
Definition: ipc.c:51
static void atexit_callback(void)
Definition: ipc.c:294
#define MAX_ON_EXITS
Definition: ipc.c:71
static int before_shmem_exit_index
Definition: ipc.c:85
static struct ONEXIT before_shmem_exit_list[MAX_ON_EXITS]
Definition: ipc.c:81
Datum arg
Definition: ipc.c:76
pg_on_exit_callback function
Definition: ipc.c:75

References ONEXIT::arg, arg, atexit_callback(), atexit_callback_setup, before_shmem_exit_index, before_shmem_exit_list, ereport, errcode(), errmsg_internal(), FATAL, ONEXIT::function, and MAX_ON_EXITS.

Referenced by ApplyLauncherMain(), AtEOXact_Namespace(), autoprewarm_main(), AuxiliaryProcessMainCommon(), CheckpointerMain(), Exec_ListenPreCommit(), InitPostgres(), InitTemporaryFileAccess(), injection_points_set_local(), LoadArchiveLibrary(), LockGXact(), logicalrep_worker_attach(), MarkAsPreparing(), ParallelApplyWorkerMain(), ParallelWorkerMain(), pgstat_initialize(), register_persistent_abort_backup_handler(), ReplicationSlotInitialize(), ReplSlotSyncWorkerMain(), and SetupApplyOrSyncWorker().

◆ CalculateShmemSize()

Size CalculateShmemSize ( int *  num_semaphores)

Definition at line 88 of file ipci.c.

89 {
90  Size size;
91  int numSemas;
92 
93  /* Compute number of semaphores we'll need */
94  numSemas = ProcGlobalSemas();
95 
96  /* Return the number of semaphores if requested by the caller */
97  if (num_semaphores)
98  *num_semaphores = numSemas;
99 
100  /*
101  * Size of the Postgres shared-memory block is estimated via moderately-
102  * accurate estimates for the big hogs, plus 100K for the stuff that's too
103  * small to bother with estimating.
104  *
105  * We take some care to ensure that the total size request doesn't
106  * overflow size_t. If this gets through, we don't need to be so careful
107  * during the actual allocation phase.
108  */
109  size = 100000;
110  size = add_size(size, PGSemaphoreShmemSize(numSemas));
112  sizeof(ShmemIndexEnt)));
151 
152  /* include additional requested shmem from preload libraries */
154 
155  /* might as well round it off to a multiple of a typical page size */
156  size = add_size(size, 8192 - (size % 8192));
157 
158  return size;
159 }
Size AsyncShmemSize(void)
Definition: async.c:485
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3267
Size BackendStatusShmemSize(void)
Size BackgroundWorkerShmemSize(void)
Definition: bgworker.c:146
Size BufferManagerShmemSize(void)
Definition: buf_init.c:159
size_t Size
Definition: c.h:610
Size CheckpointerShmemSize(void)
Definition: checkpointer.c:890
Size CLOGShmemSize(void)
Definition: clog.c:781
Size CommitTsShmemSize(void)
Definition: commit_ts.c:519
size_t dsm_estimate_size(void)
Definition: dsm.c:470
Size DSMRegistryShmemSize(void)
Definition: dsm_registry.c:63
Size hash_estimate_size(long num_entries, Size entrysize)
Definition: dynahash.c:783
Size InjectionPointShmemSize(void)
static Size total_addin_request
Definition: ipci.c:59
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:905
Size LockManagerShmemSize(void)
Definition: lock.c:3663
Size LWLockShmemSize(void)
Definition: lwlock.c:420
Size MultiXactShmemSize(void)
Definition: multixact.c:1947
Size BTreeShmemSize(void)
Definition: nbtutils.c:4523
Size ReplicationOriginShmemSize(void)
Definition: origin.c:510
Size PgArchShmemSize(void)
Definition: pgarch.c:155
Size StatsShmemSize(void)
Definition: pgstat_shmem.c:127
Size PMSignalShmemSize(void)
Definition: pmsignal.c:130
Size PGSemaphoreShmemSize(int maxSemas)
Definition: posix_sema.c:165
Size PredicateLockShmemSize(void)
Definition: predicate.c:1347
Size ProcArrayShmemSize(void)
Definition: procarray.c:376
Size ProcSignalShmemSize(void)
Definition: procsignal.c:116
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
#define SHMEM_INDEX_SIZE
Definition: shmem.h:50
Size SharedInvalShmemSize(void)
Definition: sinvaladt.c:217
static pg_noinline void Size size
Definition: slab.c:607
Size ReplicationSlotsShmemSize(void)
Definition: slot.c:171
Size SlotSyncShmemSize(void)
Definition: slotsync.c:1658
Size ProcGlobalShmemSize(void)
Definition: proc.c:97
int ProcGlobalSemas(void)
Definition: proc.c:130
Size SUBTRANSShmemSize(void)
Definition: subtrans.c:214
Size SyncScanShmemSize(void)
Definition: syncscan.c:126
Size TwoPhaseShmemSize(void)
Definition: twophase.c:237
Size VarsupShmemSize(void)
Definition: varsup.c:41
Size WaitEventCustomShmemSize(void)
Definition: wait_event.c:103
Size WalRcvShmemSize(void)
Size WalSndShmemSize(void)
Definition: walsender.c:3581
Size WalSummarizerShmemSize(void)
Size XLOGShmemSize(void)
Definition: xlog.c:4868
size_t XLogPrefetchShmemSize(void)
Size XLogRecoveryShmemSize(void)
Definition: xlogrecovery.c:447

References add_size(), ApplyLauncherShmemSize(), AsyncShmemSize(), AutoVacuumShmemSize(), BackendStatusShmemSize(), BackgroundWorkerShmemSize(), BTreeShmemSize(), BufferManagerShmemSize(), CheckpointerShmemSize(), CLOGShmemSize(), CommitTsShmemSize(), dsm_estimate_size(), DSMRegistryShmemSize(), hash_estimate_size(), InjectionPointShmemSize(), LockManagerShmemSize(), LWLockShmemSize(), MultiXactShmemSize(), PgArchShmemSize(), PGSemaphoreShmemSize(), PMSignalShmemSize(), PredicateLockShmemSize(), ProcArrayShmemSize(), ProcGlobalSemas(), ProcGlobalShmemSize(), ProcSignalShmemSize(), ReplicationOriginShmemSize(), ReplicationSlotsShmemSize(), SharedInvalShmemSize(), SHMEM_INDEX_SIZE, size, SlotSyncShmemSize(), StatsShmemSize(), SUBTRANSShmemSize(), SyncScanShmemSize(), total_addin_request, TwoPhaseShmemSize(), VarsupShmemSize(), WaitEventCustomShmemSize(), WalRcvShmemSize(), WalSndShmemSize(), WalSummarizerShmemSize(), XLogPrefetchShmemSize(), XLogRecoveryShmemSize(), and XLOGShmemSize().

Referenced by CreateSharedMemoryAndSemaphores(), and InitializeShmemGUCs().

◆ cancel_before_shmem_exit()

void cancel_before_shmem_exit ( pg_on_exit_callback  function,
Datum  arg 
)

Definition at line 394 of file ipc.c.

395 {
396  if (before_shmem_exit_index > 0 &&
398  == function &&
401  else
402  elog(ERROR, "before_shmem_exit callback (%p,0x%llx) is not the latest entry",
403  function, (long long) arg);
404 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225

References arg, before_shmem_exit_index, before_shmem_exit_list, elog, and ERROR.

◆ check_on_shmem_exit_lists_are_empty()

void check_on_shmem_exit_lists_are_empty ( void  )

Definition at line 432 of file ipc.c.

433 {
435  elog(FATAL, "before_shmem_exit has been called prematurely");
437  elog(FATAL, "on_shmem_exit has been called prematurely");
438  /* Checking DSM detach state seems unnecessary given the above */
439 }
static int on_shmem_exit_index
Definition: ipc.c:84

References before_shmem_exit_index, elog, FATAL, and on_shmem_exit_index.

Referenced by BackendInitialize().

◆ CreateSharedMemoryAndSemaphores()

void CreateSharedMemoryAndSemaphores ( void  )

Definition at line 198 of file ipci.c.

199 {
200  PGShmemHeader *shim;
201  PGShmemHeader *seghdr;
202  Size size;
203  int numSemas;
204 
206 
207  /* Compute the size of the shared-memory block */
208  size = CalculateShmemSize(&numSemas);
209  elog(DEBUG3, "invoking IpcMemoryCreate(size=%zu)", size);
210 
211  /*
212  * Create the shmem segment
213  */
214  seghdr = PGSharedMemoryCreate(size, &shim);
215 
216  /*
217  * Make sure that huge pages are never reported as "unknown" while the
218  * server is running.
219  */
220  Assert(strcmp("unknown",
221  GetConfigOption("huge_pages_status", false, false)) != 0);
222 
223  InitShmemAccess(seghdr);
224 
225  /*
226  * Create semaphores
227  */
228  PGReserveSemaphores(numSemas);
229 
230  /*
231  * Set up shared memory allocation mechanism
232  */
234 
235  /* Initialize subsystems */
237 
238  /* Initialize dynamic shared memory facilities. */
240 
241  /*
242  * Now give loadable modules a chance to set up their shmem allocations
243  */
244  if (shmem_startup_hook)
246 }
#define Assert(condition)
Definition: c.h:863
void dsm_postmaster_startup(PGShmemHeader *shim)
Definition: dsm.c:177
#define DEBUG3
Definition: elog.h:28
bool IsUnderPostmaster
Definition: globals.c:119
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4355
shmem_startup_hook_type shmem_startup_hook
Definition: ipci.c:57
Size CalculateShmemSize(int *num_semaphores)
Definition: ipci.c:88
static void CreateOrAttachShmemStructs(void)
Definition: ipci.c:264
void PGReserveSemaphores(int maxSemas)
Definition: posix_sema.c:196
void InitShmemAllocation(void)
Definition: shmem.c:115
void InitShmemAccess(void *seghdr)
Definition: shmem.c:100
PGShmemHeader * PGSharedMemoryCreate(Size size, PGShmemHeader **shim)
Definition: sysv_shmem.c:700

References Assert, CalculateShmemSize(), CreateOrAttachShmemStructs(), DEBUG3, dsm_postmaster_startup(), elog, GetConfigOption(), InitShmemAccess(), InitShmemAllocation(), IsUnderPostmaster, PGReserveSemaphores(), PGSharedMemoryCreate(), shmem_startup_hook, and size.

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), PostmasterMain(), and PostmasterStateMachine().

◆ InitializeShmemGUCs()

void InitializeShmemGUCs ( void  )

Definition at line 352 of file ipci.c.

353 {
354  char buf[64];
355  Size size_b;
356  Size size_mb;
357  Size hp_size;
358  int num_semas;
359 
360  /*
361  * Calculate the shared memory size and round up to the nearest megabyte.
362  */
363  size_b = CalculateShmemSize(&num_semas);
364  size_mb = add_size(size_b, (1024 * 1024) - 1) / (1024 * 1024);
365  sprintf(buf, "%zu", size_mb);
366  SetConfigOption("shared_memory_size", buf,
368 
369  /*
370  * Calculate the number of huge pages required.
371  */
372  GetHugePageSize(&hp_size, NULL);
373  if (hp_size != 0)
374  {
375  Size hp_required;
376 
377  hp_required = add_size(size_b / hp_size, 1);
378  sprintf(buf, "%zu", hp_required);
379  SetConfigOption("shared_memory_size_in_huge_pages", buf,
381  }
382 
383  sprintf(buf, "%d", num_semas);
384  SetConfigOption("num_os_semaphores", buf, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
385 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_INTERNAL
Definition: guc.h:69
static char * buf
Definition: pg_test_fsync.c:72
#define sprintf
Definition: port.h:240
void GetHugePageSize(Size *hugepagesize, int *mmap_flags)
Definition: sysv_shmem.c:479

References add_size(), buf, CalculateShmemSize(), GetHugePageSize(), PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SetConfigOption(), and sprintf.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ on_exit_reset()

void on_exit_reset ( void  )

Definition at line 416 of file ipc.c.

417 {
420  on_proc_exit_index = 0;
422 }
void reset_on_dsm_detach(void)
Definition: dsm.c:1170
static int on_proc_exit_index
Definition: ipc.c:83

References before_shmem_exit_index, on_proc_exit_index, on_shmem_exit_index, and reset_on_dsm_detach().

Referenced by InitPostmasterChild().

◆ on_proc_exit()

void on_proc_exit ( pg_on_exit_callback  function,
Datum  arg 
)

Definition at line 309 of file ipc.c.

310 {
312  ereport(FATAL,
313  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
314  errmsg_internal("out of on_proc_exit slots")));
315 
318 
320 
322  {
323  atexit(atexit_callback);
324  atexit_callback_setup = true;
325  }
326 }
static struct ONEXIT on_proc_exit_list[MAX_ON_EXITS]
Definition: ipc.c:79

References ONEXIT::arg, arg, atexit_callback(), atexit_callback_setup, ereport, errcode(), errmsg_internal(), FATAL, ONEXIT::function, MAX_ON_EXITS, on_proc_exit_index, and on_proc_exit_list.

Referenced by CreateLockFile(), InitCatCache(), llvm_session_initialize(), PostgresMain(), PostmasterMain(), pq_init(), select_perl_context(), sepgsql_avc_init(), and smgrinit().

◆ on_shmem_exit()

◆ proc_exit()

void proc_exit ( int  code)

Definition at line 104 of file ipc.c.

105 {
106  /* not safe if forked by system(), etc. */
107  if (MyProcPid != (int) getpid())
108  elog(PANIC, "proc_exit() called in child process");
109 
110  /* Clean up everything that must be cleaned up */
111  proc_exit_prepare(code);
112 
113 #ifdef PROFILE_PID_DIR
114  {
115  /*
116  * If we are profiling ourself then gprof's mcleanup() is about to
117  * write out a profile to ./gmon.out. Since mcleanup() always uses a
118  * fixed file name, each backend will overwrite earlier profiles. To
119  * fix that, we create a separate subdirectory for each backend
120  * (./gprof/pid) and 'cd' to that subdirectory before we exit() - that
121  * forces mcleanup() to write each profile into its own directory. We
122  * end up with something like: $PGDATA/gprof/8829/gmon.out
123  * $PGDATA/gprof/8845/gmon.out ...
124  *
125  * To avoid undesirable disk space bloat, autovacuum workers are
126  * discriminated against: all their gmon.out files go into the same
127  * subdirectory. Without this, an installation that is "just sitting
128  * there" nonetheless eats megabytes of disk space every few seconds.
129  *
130  * Note that we do this here instead of in an on_proc_exit() callback
131  * because we want to ensure that this code executes last - we don't
132  * want to interfere with any other on_proc_exit() callback. For the
133  * same reason, we do not include it in proc_exit_prepare ... so if
134  * you are exiting in the "wrong way" you won't drop your profile in a
135  * nice place.
136  */
137  char gprofDirName[32];
138 
140  snprintf(gprofDirName, 32, "gprof/avworker");
141  else
142  snprintf(gprofDirName, 32, "gprof/%d", (int) getpid());
143 
144  /*
145  * Use mkdir() instead of MakePGDirectory() since we aren't making a
146  * PG directory here.
147  */
148  mkdir("gprof", S_IRWXU | S_IRWXG | S_IRWXO);
149  mkdir(gprofDirName, S_IRWXU | S_IRWXG | S_IRWXO);
150  chdir(gprofDirName);
151  }
152 #endif
153 
154  elog(DEBUG3, "exit(%d)", code);
155 
156  exit(code);
157 }
#define PANIC
Definition: elog.h:42
int MyProcPid
Definition: globals.c:46
static void proc_exit_prepare(int code)
Definition: ipc.c:165
exit(1)
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:373
#define snprintf
Definition: port.h:238
#define S_IRWXG
Definition: win32_port.h:310
#define S_IRWXO
Definition: win32_port.h:322
#define mkdir(a, b)
Definition: win32_port.h:80
#define S_IRWXU
Definition: win32_port.h:298

References AmAutoVacuumWorkerProcess, DEBUG3, elog, exit(), mkdir, MyProcPid, PANIC, proc_exit_prepare(), S_IRWXG, S_IRWXO, S_IRWXU, and snprintf.

Referenced by apply_worker_exit(), ApplyWorkerMain(), auth_failed(), AutoVacWorkerMain(), BackendInitialize(), BackgroundWorkerMain(), BootstrapModeMain(), CheckerModeMain(), DisableSubscriptionAndExit(), errfinish(), ExitPostmaster(), HandleCheckpointerInterrupts(), HandleMainLoopInterrupts(), HandlePgArchInterrupts(), HandleStartupProcInterrupts(), HandleWalSummarizerInterrupts(), InitializeLogRepWorker(), maybe_reread_subscription(), PerformWalRecovery(), pg_attribute_noreturn(), PgArchiverMain(), PostgresMain(), PostgresSingleUserMain(), PreRestoreCommand(), process_syncing_tables_for_apply(), ProcessInterrupts(), ProcessParallelApplyInterrupts(), ProcessRepliesIfAny(), ProcessSlotSyncInterrupts(), ProcessStandbyMessage(), ReplSlotSyncWorkerMain(), RestoreArchivedFile(), slotsync_reread_config(), StartLogicalReplication(), StartReplication(), StartupProcessMain(), StartupProcShutdownHandler(), SysLoggerMain(), test_shm_mq_main(), WaitEventSetWaitBlock(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndDone(), WalSndErrorCleanup(), WalSndWait(), and WalSummarizerMain().

◆ shmem_exit()

void shmem_exit ( int  code)

Definition at line 228 of file ipc.c.

229 {
230  shmem_exit_inprogress = true;
231 
232  /*
233  * Call before_shmem_exit callbacks.
234  *
235  * These should be things that need most of the system to still be up and
236  * working, such as cleanup of temp relations, which requires catalog
237  * access; or things that need to be completed because later cleanup steps
238  * depend on them, such as releasing lwlocks.
239  */
240  elog(DEBUG3, "shmem_exit(%d): %d before_shmem_exit callbacks to make",
242  while (--before_shmem_exit_index >= 0)
246 
247  /*
248  * Call dynamic shared memory callbacks.
249  *
250  * These serve the same purpose as late callbacks, but for dynamic shared
251  * memory segments rather than the main shared memory segment.
252  * dsm_backend_shutdown() has the same kind of progressive logic we use
253  * for the main shared memory segment; namely, it unregisters each
254  * callback before invoking it, so that we don't get stuck in an infinite
255  * loop if one of those callbacks itself throws an ERROR or FATAL.
256  *
257  * Note that explicitly calling this function here is quite different from
258  * registering it as an on_shmem_exit callback for precisely this reason:
259  * if one dynamic shared memory callback errors out, the remaining
260  * callbacks will still be invoked. Thus, hard-coding this call puts it
261  * equal footing with callbacks for the main shared memory segment.
262  */
264 
265  /*
266  * Call on_shmem_exit callbacks.
267  *
268  * These are generally releasing low-level shared memory resources. In
269  * some cases, this is a backstop against the possibility that the early
270  * callbacks might themselves fail, leading to re-entry to this routine;
271  * in other cases, it's cleanup that only happens at process exit.
272  */
273  elog(DEBUG3, "shmem_exit(%d): %d on_shmem_exit callbacks to make",
274  code, on_shmem_exit_index);
275  while (--on_shmem_exit_index >= 0)
279 
280  shmem_exit_inprogress = false;
281 }
void dsm_backend_shutdown(void)
Definition: dsm.c:757
bool shmem_exit_inprogress
Definition: ipc.c:45

References arg, before_shmem_exit_index, before_shmem_exit_list, DEBUG3, dsm_backend_shutdown(), elog, ONEXIT::function, on_shmem_exit_index, on_shmem_exit_list, and shmem_exit_inprogress.

Referenced by PostmasterStateMachine(), and proc_exit_prepare().

Variable Documentation

◆ proc_exit_inprogress

◆ shmem_exit_inprogress

PGDLLIMPORT bool shmem_exit_inprogress
extern

Definition at line 45 of file ipc.c.

Referenced by AtAbort_Portals(), and shmem_exit().

◆ shmem_startup_hook

PGDLLIMPORT shmem_startup_hook_type shmem_startup_hook
extern

Definition at line 57 of file ipci.c.

Referenced by _PG_init(), and CreateSharedMemoryAndSemaphores().