PostgreSQL Source Code  git master
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 91 of file ipci.c.

92 {
93  Size size;
94  int numSemas;
95 
96  /* Compute number of semaphores we'll need */
97  numSemas = ProcGlobalSemas();
98 
99  /* Return the number of semaphores if requested by the caller */
100  if (num_semaphores)
101  *num_semaphores = numSemas;
102 
103  /*
104  * Size of the Postgres shared-memory block is estimated via moderately-
105  * accurate estimates for the big hogs, plus 100K for the stuff that's too
106  * small to bother with estimating.
107  *
108  * We take some care to ensure that the total size request doesn't
109  * overflow size_t. If this gets through, we don't need to be so careful
110  * during the actual allocation phase.
111  */
112  size = 100000;
113  size = add_size(size, PGSemaphoreShmemSize(numSemas));
115  sizeof(ShmemIndexEnt)));
155 
156  /* include additional requested shmem from preload libraries */
158 
159  /* might as well round it off to a multiple of a typical page size */
160  size = add_size(size, 8192 - (size % 8192));
161 
162  return size;
163 }
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:160
size_t Size
Definition: c.h:596
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:62
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:905
Size LockManagerShmemSize(void)
Definition: lock.c:3666
Size LWLockShmemSize(void)
Definition: lwlock.c:420
Size MultiXactShmemSize(void)
Definition: multixact.c:1947
Size BTreeShmemSize(void)
Definition: nbtutils.c:4506
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:132
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:218
static pg_noinline void Size size
Definition: slab.c:607
Size ReplicationSlotsShmemSize(void)
Definition: slot.c:171
Size SlotSyncShmemSize(void)
Definition: slotsync.c:1660
Size ProcGlobalShmemSize(void)
Definition: proc.c:101
int ProcGlobalSemas(void)
Definition: proc.c:134
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:104
Size WaitLSNShmemSize(void)
Definition: waitlsn.c:41
Size WalRcvShmemSize(void)
Size WalSndShmemSize(void)
Definition: walsender.c:3581
Size WalSummarizerShmemSize(void)
Size XLOGShmemSize(void)
Definition: xlog.c:4861
size_t XLogPrefetchShmemSize(void)
Size XLogRecoveryShmemSize(void)
Definition: xlogrecovery.c:448

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(), WaitLSNShmemSize(), 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 202 of file ipci.c.

203 {
204  PGShmemHeader *shim;
205  PGShmemHeader *seghdr;
206  Size size;
207  int numSemas;
208 
210 
211  /* Compute the size of the shared-memory block */
212  size = CalculateShmemSize(&numSemas);
213  elog(DEBUG3, "invoking IpcMemoryCreate(size=%zu)", size);
214 
215  /*
216  * Create the shmem segment
217  */
218  seghdr = PGSharedMemoryCreate(size, &shim);
219 
220  /*
221  * Make sure that huge pages are never reported as "unknown" while the
222  * server is running.
223  */
224  Assert(strcmp("unknown",
225  GetConfigOption("huge_pages_status", false, false)) != 0);
226 
227  InitShmemAccess(seghdr);
228 
229  /*
230  * Create semaphores
231  */
232  PGReserveSemaphores(numSemas);
233 
234  /*
235  * Set up shared memory allocation mechanism
236  */
238 
239  /* Initialize subsystems */
241 
242  /* Initialize dynamic shared memory facilities. */
244 
245  /*
246  * Now give loadable modules a chance to set up their shmem allocations
247  */
248  if (shmem_startup_hook)
250 }
#define Assert(condition)
Definition: c.h:849
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:4313
shmem_startup_hook_type shmem_startup_hook
Definition: ipci.c:60
Size CalculateShmemSize(int *num_semaphores)
Definition: ipci.c:91
static void CreateOrAttachShmemStructs(void)
Definition: ipci.c:268
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 357 of file ipci.c.

358 {
359  char buf[64];
360  Size size_b;
361  Size size_mb;
362  Size hp_size;
363  int num_semas;
364 
365  /*
366  * Calculate the shared memory size and round up to the nearest megabyte.
367  */
368  size_b = CalculateShmemSize(&num_semas);
369  size_mb = add_size(size_b, (1024 * 1024) - 1) / (1024 * 1024);
370  sprintf(buf, "%zu", size_mb);
371  SetConfigOption("shared_memory_size", buf,
373 
374  /*
375  * Calculate the number of huge pages required.
376  */
377  GetHugePageSize(&hp_size, NULL);
378  if (hp_size != 0)
379  {
380  Size hp_required;
381 
382  hp_required = add_size(size_b / hp_size, 1);
383  sprintf(buf, "%zu", hp_required);
384  SetConfigOption("shared_memory_size_in_huge_pages", buf,
386  }
387 
388  sprintf(buf, "%d", num_semas);
389  SetConfigOption("num_os_semaphores", buf, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
390 }
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4290
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_INTERNAL
Definition: guc.h:69
static char * buf
Definition: pg_test_fsync.c:73
#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:372
#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 60 of file ipci.c.

Referenced by _PG_init(), and CreateSharedMemoryAndSemaphores().