1 /*-------------------------------------------------------------------------
4 * This file contains general postgres administration and initialization
5 * stuff that used to be spread out between the following files:
6 * globals.h global variables
7 * pdir.h directory path crud
8 * pinit.h postgres initialization
9 * pmod.h processing modes
10 * Over time, this has also become the preferred place for widely known
11 * resource-limitation stuff, such as work_mem and check_stack_depth().
13 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
16 * src/include/miscadmin.h
19 * some of the information in this file should be moved to other files.
21 *-------------------------------------------------------------------------
28 #include "datatype/timestamp.h" /* for TimestampTz */
29 #include "pgtime.h" /* for pg_time_t */
32 #define InvalidPid (-1)
35 /*****************************************************************************
36 * System interrupt and critical section handling
38 * There are two types of interrupts that a running backend needs to accept
39 * without messing up its state: QueryCancel (SIGINT) and ProcDie (SIGTERM).
40 * In both cases, we need to be able to clean up the current transaction
41 * gracefully, so we can't respond to the interrupt instantaneously ---
42 * there's no guarantee that internal data structures would be self-consistent
43 * if the code is interrupted at an arbitrary instant. Instead, the signal
44 * handlers set flags that are checked periodically during execution.
46 * The CHECK_FOR_INTERRUPTS() macro is called at strategically located spots
47 * where it is normally safe to accept a cancel or die interrupt. In some
48 * cases, we invoke CHECK_FOR_INTERRUPTS() inside low-level subroutines that
49 * might sometimes be called in contexts that do *not* want to allow a cancel
50 * or die interrupt. The HOLD_INTERRUPTS() and RESUME_INTERRUPTS() macros
51 * allow code to ensure that no cancel or die interrupt will be accepted,
52 * even if CHECK_FOR_INTERRUPTS() gets called in a subroutine. The interrupt
53 * will be held off until CHECK_FOR_INTERRUPTS() is done outside any
54 * HOLD_INTERRUPTS() ... RESUME_INTERRUPTS() section.
56 * There is also a mechanism to prevent query cancel interrupts, while still
57 * allowing die interrupts: HOLD_CANCEL_INTERRUPTS() and
58 * RESUME_CANCEL_INTERRUPTS().
60 * Note that ProcessInterrupts() has also acquired a number of tasks that
61 * do not necessarily cause a query-cancel-or-die response. Hence, it's
62 * possible that it will just clear InterruptPending and return.
64 * INTERRUPTS_PENDING_CONDITION() can be checked to see whether an
65 * interrupt needs to be serviced, without trying to do so immediately.
66 * Some callers are also interested in INTERRUPTS_CAN_BE_PROCESSED(),
67 * which tells whether ProcessInterrupts is sure to clear the interrupt.
69 * Special mechanisms are used to let an interrupt be accepted when we are
70 * waiting for a lock or when we are waiting for command input (but, of
71 * course, only if the interrupt holdoff counter is zero). See the
72 * related code for details.
74 * A lost connection is handled similarly, although the loss of connection
75 * does not raise a signal, but is detected when we fail to write to the
76 * socket. If there was a signal for a broken connection, we could make use of
77 * it by setting ClientConnectionLost in the signal handler.
79 * A related, but conceptually distinct, mechanism is the "critical section"
80 * mechanism. A critical section not only holds off cancel/die interrupts,
81 * but causes any ereport(ERROR) or ereport(FATAL) to become ereport(PANIC)
82 * --- that is, a system-wide reset is forced. Needless to say, only really
83 * *critical* code should be marked as a critical section! Currently, this
84 * mechanism is only used for XLOG-related code.
86 *****************************************************************************/
89 /* these are marked volatile because they are set by signal handlers: */
90 extern PGDLLIMPORT
volatile sig_atomic_t InterruptPending
;
91 extern PGDLLIMPORT
volatile sig_atomic_t QueryCancelPending
;
92 extern PGDLLIMPORT
volatile sig_atomic_t ProcDiePending
;
93 extern PGDLLIMPORT
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
;
94 extern PGDLLIMPORT
volatile sig_atomic_t IdleSessionTimeoutPending
;
95 extern PGDLLIMPORT
volatile sig_atomic_t ProcSignalBarrierPending
;
96 extern PGDLLIMPORT
volatile sig_atomic_t LogMemoryContextPending
;
97 extern PGDLLIMPORT
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
;
99 extern PGDLLIMPORT
volatile sig_atomic_t CheckClientConnectionPending
;
100 extern PGDLLIMPORT
volatile sig_atomic_t ClientConnectionLost
;
102 /* these are marked volatile because they are examined by signal handlers: */
103 extern PGDLLIMPORT
volatile uint32 InterruptHoldoffCount
;
104 extern PGDLLIMPORT
volatile uint32 QueryCancelHoldoffCount
;
105 extern PGDLLIMPORT
volatile uint32 CritSectionCount
;
107 /* in tcop/postgres.c */
108 extern void ProcessInterrupts(void);
110 /* Test whether an interrupt is pending */
112 #define INTERRUPTS_PENDING_CONDITION() \
113 (unlikely(InterruptPending))
115 #define INTERRUPTS_PENDING_CONDITION() \
116 (unlikely(UNBLOCKED_SIGNAL_QUEUE()) ? pgwin32_dispatch_queued_signals() : 0, \
117 unlikely(InterruptPending))
120 /* Service interrupt, if one is pending and it's safe to service it now */
121 #define CHECK_FOR_INTERRUPTS() \
123 if (INTERRUPTS_PENDING_CONDITION()) \
124 ProcessInterrupts(); \
127 /* Is ProcessInterrupts() guaranteed to clear InterruptPending? */
128 #define INTERRUPTS_CAN_BE_PROCESSED() \
129 (InterruptHoldoffCount == 0 && CritSectionCount == 0 && \
130 QueryCancelHoldoffCount == 0)
132 #define HOLD_INTERRUPTS() (InterruptHoldoffCount++)
134 #define RESUME_INTERRUPTS() \
136 Assert(InterruptHoldoffCount > 0); \
137 InterruptHoldoffCount--; \
140 #define HOLD_CANCEL_INTERRUPTS() (QueryCancelHoldoffCount++)
142 #define RESUME_CANCEL_INTERRUPTS() \
144 Assert(QueryCancelHoldoffCount > 0); \
145 QueryCancelHoldoffCount--; \
148 #define START_CRIT_SECTION() (CritSectionCount++)
150 #define END_CRIT_SECTION() \
152 Assert(CritSectionCount > 0); \
153 CritSectionCount--; \
157 /*****************************************************************************
159 *****************************************************************************/
162 * from utils/init/globals.c
164 extern PGDLLIMPORT pid_t PostmasterPid
;
165 extern PGDLLIMPORT
bool IsPostmasterEnvironment
;
166 extern PGDLLIMPORT
bool IsUnderPostmaster
;
167 extern PGDLLIMPORT
bool IsBackgroundWorker
;
168 extern PGDLLIMPORT
bool IsBinaryUpgrade
;
170 extern PGDLLIMPORT
bool ExitOnAnyError
;
172 extern PGDLLIMPORT
char *DataDir
;
173 extern PGDLLIMPORT
int data_directory_mode
;
175 extern PGDLLIMPORT
int NBuffers
;
176 extern PGDLLIMPORT
int MaxBackends
;
177 extern PGDLLIMPORT
int MaxConnections
;
178 extern PGDLLIMPORT
int max_worker_processes
;
179 extern PGDLLIMPORT
int max_parallel_workers
;
181 extern PGDLLIMPORT
int MyProcPid
;
182 extern PGDLLIMPORT pg_time_t MyStartTime
;
183 extern PGDLLIMPORT TimestampTz MyStartTimestamp
;
184 extern PGDLLIMPORT
struct Port
*MyProcPort
;
185 extern PGDLLIMPORT
struct Latch
*MyLatch
;
186 extern PGDLLIMPORT int32 MyCancelKey
;
187 extern PGDLLIMPORT
int MyPMChildSlot
;
189 extern PGDLLIMPORT
char OutputFileName
[];
190 extern PGDLLIMPORT
char my_exec_path
[];
191 extern PGDLLIMPORT
char pkglib_path
[];
194 extern PGDLLIMPORT
char postgres_exec_path
[];
198 * done in storage/backendid.h for now.
200 * extern BackendId MyBackendId;
202 extern PGDLLIMPORT Oid MyDatabaseId
;
204 extern PGDLLIMPORT Oid MyDatabaseTableSpace
;
207 * Date/Time Configuration
209 * DateStyle defines the output formatting choice for date/time types:
210 * USE_POSTGRES_DATES specifies traditional Postgres format
211 * USE_ISO_DATES specifies ISO-compliant format
212 * USE_SQL_DATES specifies Oracle/Ingres-compliant format
213 * USE_GERMAN_DATES specifies German-style dd.mm/yyyy
215 * DateOrder defines the field order to be assumed when reading an
216 * ambiguous date (anything not in YYYY-MM-DD format, with a four-digit
217 * year field first, is taken to be ambiguous):
218 * DATEORDER_YMD specifies field order yy-mm-dd
219 * DATEORDER_DMY specifies field order dd-mm-yy ("European" convention)
220 * DATEORDER_MDY specifies field order mm-dd-yy ("US" convention)
222 * In the Postgres and SQL DateStyles, DateOrder also selects output field
223 * order: day comes before month in DMY style, else month comes before day.
225 * The user-visible "DateStyle" run-time parameter subsumes both of these.
228 /* valid DateStyle values */
229 #define USE_POSTGRES_DATES 0
230 #define USE_ISO_DATES 1
231 #define USE_SQL_DATES 2
232 #define USE_GERMAN_DATES 3
233 #define USE_XSD_DATES 4
235 /* valid DateOrder values */
236 #define DATEORDER_YMD 0
237 #define DATEORDER_DMY 1
238 #define DATEORDER_MDY 2
240 extern PGDLLIMPORT
int DateStyle
;
241 extern PGDLLIMPORT
int DateOrder
;
245 * INTSTYLE_POSTGRES Like Postgres < 8.4 when DateStyle = 'iso'
246 * INTSTYLE_POSTGRES_VERBOSE Like Postgres < 8.4 when DateStyle != 'iso'
247 * INTSTYLE_SQL_STANDARD SQL standard interval literals
248 * INTSTYLE_ISO_8601 ISO-8601-basic formatted intervals
250 #define INTSTYLE_POSTGRES 0
251 #define INTSTYLE_POSTGRES_VERBOSE 1
252 #define INTSTYLE_SQL_STANDARD 2
253 #define INTSTYLE_ISO_8601 3
255 extern PGDLLIMPORT
int IntervalStyle
;
257 #define MAXTZLEN 10 /* max TZ name len, not counting tr. null */
259 extern PGDLLIMPORT
bool enableFsync
;
260 extern PGDLLIMPORT
bool allowSystemTableMods
;
261 extern PGDLLIMPORT
int work_mem
;
262 extern PGDLLIMPORT
double hash_mem_multiplier
;
263 extern PGDLLIMPORT
int maintenance_work_mem
;
264 extern PGDLLIMPORT
int max_parallel_maintenance_workers
;
267 * Upper and lower hard limits for the buffer access strategy ring size
268 * specified by the VacuumBufferUsageLimit GUC and BUFFER_USAGE_LIMIT option
269 * to VACUUM and ANALYZE.
271 #define MIN_BAS_VAC_RING_SIZE_KB 128
272 #define MAX_BAS_VAC_RING_SIZE_KB (16 * 1024 * 1024)
274 extern PGDLLIMPORT
int VacuumBufferUsageLimit
;
275 extern PGDLLIMPORT
int VacuumCostPageHit
;
276 extern PGDLLIMPORT
int VacuumCostPageMiss
;
277 extern PGDLLIMPORT
int VacuumCostPageDirty
;
278 extern PGDLLIMPORT
int VacuumCostLimit
;
279 extern PGDLLIMPORT
double VacuumCostDelay
;
281 extern PGDLLIMPORT int64 VacuumPageHit
;
282 extern PGDLLIMPORT int64 VacuumPageMiss
;
283 extern PGDLLIMPORT int64 VacuumPageDirty
;
285 extern PGDLLIMPORT
int VacuumCostBalance
;
286 extern PGDLLIMPORT
bool VacuumCostActive
;
289 /* in tcop/postgres.c */
291 typedef char *pg_stack_base_t
;
293 extern pg_stack_base_t
set_stack_base(void);
294 extern void restore_stack_base(pg_stack_base_t base
);
295 extern void check_stack_depth(void);
296 extern bool stack_is_too_deep(void);
298 /* in tcop/utility.c */
299 extern void PreventCommandIfReadOnly(const char *cmdname
);
300 extern void PreventCommandIfParallelMode(const char *cmdname
);
301 extern void PreventCommandDuringRecovery(const char *cmdname
);
303 /* in utils/misc/guc_tables.c */
304 extern PGDLLIMPORT
int trace_recovery_messages
;
305 extern int trace_recovery(int trace_level
);
307 /*****************************************************************************
309 * POSTGRES directory path definitions. *
310 *****************************************************************************/
312 /* flags to be OR'd to form sec_context */
313 #define SECURITY_LOCAL_USERID_CHANGE 0x0001
314 #define SECURITY_RESTRICTED_OPERATION 0x0002
315 #define SECURITY_NOFORCE_RLS 0x0004
317 extern PGDLLIMPORT
char *DatabasePath
;
319 /* now in utils/init/miscinit.c */
320 extern void InitPostmasterChild(void);
321 extern void InitStandaloneProcess(const char *argv0
);
322 extern void InitProcessLocalLatch(void);
323 extern void SwitchToSharedLatch(void);
324 extern void SwitchBackToLocalLatch(void);
326 typedef enum BackendType
337 B_STANDALONE_BACKEND
,
344 #define BACKEND_NUM_TYPES (B_WAL_WRITER + 1)
346 extern PGDLLIMPORT BackendType MyBackendType
;
348 extern const char *GetBackendTypeDesc(BackendType backendType
);
350 extern void SetDatabasePath(const char *path
);
351 extern void checkDataDir(void);
352 extern void SetDataDir(const char *dir
);
353 extern void ChangeToDataDir(void);
355 extern char *GetUserNameFromId(Oid roleid
, bool noerr
);
356 extern Oid
GetUserId(void);
357 extern Oid
GetOuterUserId(void);
358 extern Oid
GetSessionUserId(void);
359 extern Oid
GetAuthenticatedUserId(void);
360 extern void GetUserIdAndSecContext(Oid
*userid
, int *sec_context
);
361 extern void SetUserIdAndSecContext(Oid userid
, int sec_context
);
362 extern bool InLocalUserIdChange(void);
363 extern bool InSecurityRestrictedOperation(void);
364 extern bool InNoForceRLSOperation(void);
365 extern void GetUserIdAndContext(Oid
*userid
, bool *sec_def_context
);
366 extern void SetUserIdAndContext(Oid userid
, bool sec_def_context
);
367 extern void InitializeSessionUserId(const char *rolename
, Oid roleid
);
368 extern void InitializeSessionUserIdStandalone(void);
369 extern void SetSessionAuthorization(Oid userid
, bool is_superuser
);
370 extern Oid
GetCurrentRoleId(void);
371 extern void SetCurrentRoleId(Oid roleid
, bool is_superuser
);
372 extern void InitializeSystemUser(const char *authn_id
,
373 const char *auth_method
);
374 extern const char *GetSystemUser(void);
376 /* in utils/misc/superuser.c */
377 extern bool superuser(void); /* current user is superuser */
378 extern bool superuser_arg(Oid roleid
); /* given user is superuser */
381 /*****************************************************************************
383 * POSTGRES processing mode definitions. *
384 *****************************************************************************/
388 * There are three processing modes in POSTGRES. They are
389 * BootstrapProcessing or "bootstrap," InitProcessing or
390 * "initialization," and NormalProcessing or "normal."
392 * The first two processing modes are used during special times. When the
393 * system state indicates bootstrap processing, transactions are all given
394 * transaction id "one" and are consequently guaranteed to commit. This mode
395 * is used during the initial generation of template databases.
397 * Initialization mode: used while starting a backend, until all normal
398 * initialization is complete. Some code behaves differently when executed
399 * in this mode to enable system bootstrapping.
401 * If a POSTGRES backend process is in normal mode, then all code may be
405 typedef enum ProcessingMode
407 BootstrapProcessing
, /* bootstrap creation of template database */
408 InitProcessing
, /* initializing system */
409 NormalProcessing
/* normal processing */
412 extern PGDLLIMPORT ProcessingMode Mode
;
414 #define IsBootstrapProcessingMode() (Mode == BootstrapProcessing)
415 #define IsInitProcessingMode() (Mode == InitProcessing)
416 #define IsNormalProcessingMode() (Mode == NormalProcessing)
418 #define GetProcessingMode() Mode
420 #define SetProcessingMode(mode) \
422 Assert((mode) == BootstrapProcessing || \
423 (mode) == InitProcessing || \
424 (mode) == NormalProcessing); \
430 * Auxiliary-process type identifiers. These used to be in bootstrap.h
431 * but it seems saner to have them here, with the ProcessingMode stuff.
432 * The MyAuxProcType global is defined and set in auxprocess.c.
434 * Make sure to list in the glossary any items you add here.
439 NotAnAuxProcess
= -1,
447 NUM_AUXPROCTYPES
/* Must be last! */
450 extern PGDLLIMPORT AuxProcType MyAuxProcType
;
452 #define AmStartupProcess() (MyAuxProcType == StartupProcess)
453 #define AmBackgroundWriterProcess() (MyAuxProcType == BgWriterProcess)
454 #define AmArchiverProcess() (MyAuxProcType == ArchiverProcess)
455 #define AmCheckpointerProcess() (MyAuxProcType == CheckpointerProcess)
456 #define AmWalWriterProcess() (MyAuxProcType == WalWriterProcess)
457 #define AmWalReceiverProcess() (MyAuxProcType == WalReceiverProcess)
460 /*****************************************************************************
462 * POSTGRES initialization and cleanup definitions. *
463 *****************************************************************************/
465 /* in utils/init/postinit.c */
466 extern void pg_split_opts(char **argv
, int *argcp
, const char *optstr
);
467 extern void InitializeMaxBackends(void);
468 extern void InitPostgres(const char *in_dbname
, Oid dboid
,
469 const char *username
, Oid useroid
,
470 bool load_session_libraries
,
471 bool override_allow_connections
,
473 extern void BaseInit(void);
475 /* in utils/init/miscinit.c */
476 extern PGDLLIMPORT
bool IgnoreSystemIndexes
;
477 extern PGDLLIMPORT
bool process_shared_preload_libraries_in_progress
;
478 extern PGDLLIMPORT
bool process_shared_preload_libraries_done
;
479 extern PGDLLIMPORT
bool process_shmem_requests_in_progress
;
480 extern PGDLLIMPORT
char *session_preload_libraries_string
;
481 extern PGDLLIMPORT
char *shared_preload_libraries_string
;
482 extern PGDLLIMPORT
char *local_preload_libraries_string
;
484 extern void CreateDataDirLockFile(bool amPostmaster
);
485 extern void CreateSocketLockFile(const char *socketfile
, bool amPostmaster
,
486 const char *socketDir
);
487 extern void TouchSocketLockFiles(void);
488 extern void AddToDataDirLockFile(int target_line
, const char *str
);
489 extern bool RecheckDataDirLockFile(void);
490 extern void ValidatePgVersion(const char *path
);
491 extern void process_shared_preload_libraries(void);
492 extern void process_session_preload_libraries(void);
493 extern void process_shmem_requests(void);
494 extern void pg_bindtextdomain(const char *domain
);
495 extern bool has_rolreplication(Oid roleid
);
497 typedef void (*shmem_request_hook_type
) (void);
498 extern PGDLLIMPORT shmem_request_hook_type shmem_request_hook
;
500 extern Size
EstimateClientConnectionInfoSpace(void);
501 extern void SerializeClientConnectionInfo(Size maxsize
, char *start_address
);
502 extern void RestoreClientConnectionInfo(char *conninfo
);
504 /* in executor/nodeHash.c */
505 extern size_t get_hash_memory_limit(void);
507 #endif /* MISCADMIN_H */