PostgreSQL Source Code git master
Loading...
Searching...
No Matches
miscadmin.h File Reference
#include <signal.h>
#include "datatype/timestamp.h"
#include "pgtime.h"
Include dependency graph for miscadmin.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define InvalidPid   (-1)
 
#define INTERRUPTS_PENDING_CONDITION()    (unlikely(InterruptPending))
 
#define CHECK_FOR_INTERRUPTS()
 
#define INTERRUPTS_CAN_BE_PROCESSED()
 
#define HOLD_INTERRUPTS()   (InterruptHoldoffCount++)
 
#define RESUME_INTERRUPTS()
 
#define HOLD_CANCEL_INTERRUPTS()   (QueryCancelHoldoffCount++)
 
#define RESUME_CANCEL_INTERRUPTS()
 
#define START_CRIT_SECTION()   (CritSectionCount++)
 
#define END_CRIT_SECTION()
 
#define USE_POSTGRES_DATES   0
 
#define USE_ISO_DATES   1
 
#define USE_SQL_DATES   2
 
#define USE_GERMAN_DATES   3
 
#define USE_XSD_DATES   4
 
#define DATEORDER_YMD   0
 
#define DATEORDER_DMY   1
 
#define DATEORDER_MDY   2
 
#define INTSTYLE_POSTGRES   0
 
#define INTSTYLE_POSTGRES_VERBOSE   1
 
#define INTSTYLE_SQL_STANDARD   2
 
#define INTSTYLE_ISO_8601   3
 
#define MAXTZLEN   10 /* max TZ name len, not counting tr. null */
 
#define MIN_BAS_VAC_RING_SIZE_KB   128
 
#define MAX_BAS_VAC_RING_SIZE_KB   (16 * 1024 * 1024)
 
#define STACK_DEPTH_SLOP   (512 * 1024)
 
#define SECURITY_LOCAL_USERID_CHANGE   0x0001
 
#define SECURITY_RESTRICTED_OPERATION   0x0002
 
#define SECURITY_NOFORCE_RLS   0x0004
 
#define BACKEND_NUM_TYPES   (B_LOGGER + 1)
 
#define AmRegularBackendProcess()   (MyBackendType == B_BACKEND)
 
#define AmAutoVacuumLauncherProcess()   (MyBackendType == B_AUTOVAC_LAUNCHER)
 
#define AmAutoVacuumWorkerProcess()   (MyBackendType == B_AUTOVAC_WORKER)
 
#define AmBackgroundWorkerProcess()   (MyBackendType == B_BG_WORKER)
 
#define AmWalSenderProcess()   (MyBackendType == B_WAL_SENDER)
 
#define AmLogicalSlotSyncWorkerProcess()   (MyBackendType == B_SLOTSYNC_WORKER)
 
#define AmArchiverProcess()   (MyBackendType == B_ARCHIVER)
 
#define AmBackgroundWriterProcess()   (MyBackendType == B_BG_WRITER)
 
#define AmCheckpointerProcess()   (MyBackendType == B_CHECKPOINTER)
 
#define AmStartupProcess()   (MyBackendType == B_STARTUP)
 
#define AmWalReceiverProcess()   (MyBackendType == B_WAL_RECEIVER)
 
#define AmWalSummarizerProcess()   (MyBackendType == B_WAL_SUMMARIZER)
 
#define AmWalWriterProcess()   (MyBackendType == B_WAL_WRITER)
 
#define AmIoWorkerProcess()   (MyBackendType == B_IO_WORKER)
 
#define AmDataChecksumsWorkerProcess()
 
#define AmSpecialWorkerProcess()
 
#define IsExternalConnectionBackend(backend_type)    (backend_type == B_BACKEND || backend_type == B_WAL_SENDER)
 
#define IsBootstrapProcessingMode()   (Mode == BootstrapProcessing)
 
#define IsInitProcessingMode()   (Mode == InitProcessing)
 
#define IsNormalProcessingMode()   (Mode == NormalProcessing)
 
#define GetProcessingMode()   Mode
 
#define SetProcessingMode(mode)
 
#define INIT_PG_LOAD_SESSION_LIBS   0x0001
 
#define INIT_PG_OVERRIDE_ALLOW_CONNS   0x0002
 
#define INIT_PG_OVERRIDE_ROLE_LOGIN   0x0004
 

Typedefs

typedef charpg_stack_base_t
 
typedef enum BackendType BackendType
 
typedef enum ProcessingMode ProcessingMode
 
typedef void(* shmem_request_hook_type) (void)
 

Enumerations

enum  BackendType {
  B_INVALID = 0 , B_BACKEND , B_DEAD_END_BACKEND , B_AUTOVAC_LAUNCHER ,
  B_AUTOVAC_WORKER , B_BG_WORKER , B_WAL_SENDER , B_SLOTSYNC_WORKER ,
  B_STANDALONE_BACKEND , B_ARCHIVER , B_BG_WRITER , B_CHECKPOINTER ,
  B_IO_WORKER , B_STARTUP , B_WAL_RECEIVER , B_WAL_SUMMARIZER ,
  B_WAL_WRITER , B_DATACHECKSUMSWORKER_LAUNCHER , B_DATACHECKSUMSWORKER_WORKER , B_LOGGER
}
 
enum  ProcessingMode { BootstrapProcessing , InitProcessing , NormalProcessing }
 

Functions

void ProcessInterrupts (void)
 
pg_stack_base_t set_stack_base (void)
 
void restore_stack_base (pg_stack_base_t base)
 
void check_stack_depth (void)
 
bool stack_is_too_deep (void)
 
ssize_t get_stack_depth_rlimit (void)
 
void PreventCommandIfReadOnly (const char *cmdname)
 
void PreventCommandIfParallelMode (const char *cmdname)
 
void PreventCommandDuringRecovery (const char *cmdname)
 
void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void InitProcessLocalLatch (void)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
const charGetBackendTypeDesc (BackendType backendType)
 
void SetDatabasePath (const char *path)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
charGetUserNameFromId (Oid roleid, bool noerr)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
Oid GetSessionUserId (void)
 
bool GetSessionUserIsSuperuser (void)
 
Oid GetAuthenticatedUserId (void)
 
void SetAuthenticatedUserId (Oid userid)
 
void GetUserIdAndSecContext (Oid *userid, int *sec_context)
 
void SetUserIdAndSecContext (Oid userid, int sec_context)
 
bool InLocalUserIdChange (void)
 
bool InSecurityRestrictedOperation (void)
 
bool InNoForceRLSOperation (void)
 
void GetUserIdAndContext (Oid *userid, bool *sec_def_context)
 
void SetUserIdAndContext (Oid userid, bool sec_def_context)
 
void InitializeSessionUserId (const char *rolename, Oid roleid, bool bypass_login_check)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
void InitializeSystemUser (const char *authn_id, const char *auth_method)
 
const charGetSystemUser (void)
 
bool superuser (void)
 
bool superuser_arg (Oid roleid)
 
void pg_split_opts (char **argv, int *argcp, const char *optstr)
 
void InitializeMaxBackends (void)
 
void InitializeFastPathLocks (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
 
void BaseInit (void)
 
void StoreConnectionWarning (char *msg, char *detail)
 
void CreateDataDirLockFile (bool amPostmaster)
 
void CreateSocketLockFile (const char *socketfile, bool amPostmaster, const char *socketDir)
 
void TouchSocketLockFiles (void)
 
void AddToDataDirLockFile (int target_line, const char *str)
 
bool RecheckDataDirLockFile (void)
 
void ValidatePgVersion (const char *path)
 
void process_shared_preload_libraries (void)
 
void process_session_preload_libraries (void)
 
void process_shmem_requests (void)
 
void pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
Size EstimateClientConnectionInfoSpace (void)
 
void SerializeClientConnectionInfo (Size maxsize, char *start_address)
 
void RestoreClientConnectionInfo (char *conninfo)
 
size_t get_hash_memory_limit (void)
 

Variables

PGDLLIMPORT volatile sig_atomic_t InterruptPending
 
PGDLLIMPORT volatile sig_atomic_t QueryCancelPending
 
PGDLLIMPORT volatile sig_atomic_t ProcDiePending
 
PGDLLIMPORT volatile int ProcDieSenderPid
 
PGDLLIMPORT volatile int ProcDieSenderUid
 
PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t ProcSignalBarrierPending
 
PGDLLIMPORT volatile sig_atomic_t LogMemoryContextPending
 
PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
 
PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
 
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
 
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
 
PGDLLIMPORT volatile uint32 CritSectionCount
 
PGDLLIMPORT pid_t PostmasterPid
 
PGDLLIMPORT bool IsPostmasterEnvironment
 
PGDLLIMPORT bool IsUnderPostmaster
 
PGDLLIMPORT bool IsBinaryUpgrade
 
PGDLLIMPORT bool ExitOnAnyError
 
PGDLLIMPORT charDataDir
 
PGDLLIMPORT int data_directory_mode
 
PGDLLIMPORT int NBuffers
 
PGDLLIMPORT int MaxBackends
 
PGDLLIMPORT int MaxConnections
 
PGDLLIMPORT int max_worker_processes
 
PGDLLIMPORT int max_parallel_workers
 
PGDLLIMPORT int autovacuum_max_parallel_workers
 
PGDLLIMPORT int commit_timestamp_buffers
 
PGDLLIMPORT int multixact_member_buffers
 
PGDLLIMPORT int multixact_offset_buffers
 
PGDLLIMPORT int notify_buffers
 
PGDLLIMPORT int serializable_buffers
 
PGDLLIMPORT int subtransaction_buffers
 
PGDLLIMPORT int transaction_buffers
 
PGDLLIMPORT int MyProcPid
 
PGDLLIMPORT pg_time_t MyStartTime
 
PGDLLIMPORT TimestampTz MyStartTimestamp
 
PGDLLIMPORT struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
PGDLLIMPORT uint8 MyCancelKey []
 
PGDLLIMPORT int MyCancelKeyLength
 
PGDLLIMPORT int MyPMChildSlot
 
PGDLLIMPORT char OutputFileName []
 
PGDLLIMPORT char my_exec_path []
 
PGDLLIMPORT char pkglib_path []
 
PGDLLIMPORT Oid MyDatabaseId
 
PGDLLIMPORT Oid MyDatabaseTableSpace
 
PGDLLIMPORT bool MyDatabaseHasLoginEventTriggers
 
PGDLLIMPORT int DateStyle
 
PGDLLIMPORT int DateOrder
 
PGDLLIMPORT int IntervalStyle
 
PGDLLIMPORT bool enableFsync
 
PGDLLIMPORT bool allowSystemTableMods
 
PGDLLIMPORT int work_mem
 
PGDLLIMPORT double hash_mem_multiplier
 
PGDLLIMPORT int maintenance_work_mem
 
PGDLLIMPORT int max_parallel_maintenance_workers
 
PGDLLIMPORT int VacuumBufferUsageLimit
 
PGDLLIMPORT int VacuumCostPageHit
 
PGDLLIMPORT int VacuumCostPageMiss
 
PGDLLIMPORT int VacuumCostPageDirty
 
PGDLLIMPORT int VacuumCostLimit
 
PGDLLIMPORT double VacuumCostDelay
 
PGDLLIMPORT int VacuumCostBalance
 
PGDLLIMPORT bool VacuumCostActive
 
PGDLLIMPORT int max_stack_depth
 
PGDLLIMPORT bool accessSharedCatalogsInDecoding
 
PGDLLIMPORT charDatabasePath
 
PGDLLIMPORT BackendType MyBackendType
 
PGDLLIMPORT ProcessingMode Mode
 
PGDLLIMPORT bool IgnoreSystemIndexes
 
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
 
PGDLLIMPORT bool process_shared_preload_libraries_done
 
PGDLLIMPORT bool process_shmem_requests_in_progress
 
PGDLLIMPORT charsession_preload_libraries_string
 
PGDLLIMPORT charshared_preload_libraries_string
 
PGDLLIMPORT charlocal_preload_libraries_string
 
PGDLLIMPORT shmem_request_hook_type shmem_request_hook
 

Macro Definition Documentation

◆ AmArchiverProcess

#define AmArchiverProcess ( )    (MyBackendType == B_ARCHIVER)

Definition at line 402 of file miscadmin.h.

◆ AmAutoVacuumLauncherProcess

#define AmAutoVacuumLauncherProcess ( )    (MyBackendType == B_AUTOVAC_LAUNCHER)

Definition at line 397 of file miscadmin.h.

◆ AmAutoVacuumWorkerProcess

#define AmAutoVacuumWorkerProcess ( )    (MyBackendType == B_AUTOVAC_WORKER)

Definition at line 398 of file miscadmin.h.

◆ AmBackgroundWorkerProcess

#define AmBackgroundWorkerProcess ( )    (MyBackendType == B_BG_WORKER)

Definition at line 399 of file miscadmin.h.

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyBackendType == B_BG_WRITER)

Definition at line 403 of file miscadmin.h.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyBackendType == B_CHECKPOINTER)

Definition at line 404 of file miscadmin.h.

◆ AmDataChecksumsWorkerProcess

#define AmDataChecksumsWorkerProcess ( )
Value:
PGDLLIMPORT BackendType MyBackendType
Definition miscinit.c:65
@ B_DATACHECKSUMSWORKER_WORKER
Definition miscadmin.h:383
@ B_DATACHECKSUMSWORKER_LAUNCHER
Definition miscadmin.h:382

Definition at line 410 of file miscadmin.h.

486{
487 BootstrapProcessing, /* bootstrap creation of template database */
488 InitProcessing, /* initializing system */
489 NormalProcessing, /* normal processing */
491
493
494#define IsBootstrapProcessingMode() (Mode == BootstrapProcessing)
495#define IsInitProcessingMode() (Mode == InitProcessing)
496#define IsNormalProcessingMode() (Mode == NormalProcessing)
497
498#define GetProcessingMode() Mode
499
500#define SetProcessingMode(mode) \
501 do { \
502 Assert((mode) == BootstrapProcessing || \
503 (mode) == InitProcessing || \
504 (mode) == NormalProcessing); \
505 Mode = (mode); \
506 } while(0)
507
508
509/*****************************************************************************
510 * pinit.h -- *
511 * POSTGRES initialization and cleanup definitions. *
512 *****************************************************************************/
513
514/* in utils/init/postinit.c */
515/* flags for InitPostgres() */
516#define INIT_PG_LOAD_SESSION_LIBS 0x0001
517#define INIT_PG_OVERRIDE_ALLOW_CONNS 0x0002
518#define INIT_PG_OVERRIDE_ROLE_LOGIN 0x0004
519extern void pg_split_opts(char **argv, int *argcp, const char *optstr);
520extern void InitializeMaxBackends(void);
521extern void InitializeFastPathLocks(void);
522extern void InitPostgres(const char *in_dbname, Oid dboid,
523 const char *username, Oid useroid,
524 uint32 flags,
525 char *out_dbname);
526extern void BaseInit(void);
527extern void StoreConnectionWarning(char *msg, char *detail);
528
529/* in utils/init/miscinit.c */
537
538extern void CreateDataDirLockFile(bool amPostmaster);
539extern void CreateSocketLockFile(const char *socketfile, bool amPostmaster,
540 const char *socketDir);
541extern void TouchSocketLockFiles(void);
542extern void AddToDataDirLockFile(int target_line, const char *str);
543extern bool RecheckDataDirLockFile(void);
544extern void ValidatePgVersion(const char *path);
545extern void process_shared_preload_libraries(void);
546extern void process_session_preload_libraries(void);
547extern void process_shmem_requests(void);
548extern void pg_bindtextdomain(const char *domain);
549extern bool has_rolreplication(Oid roleid);
550
553
556extern void RestoreClientConnectionInfo(char *conninfo);
557
558/* in executor/nodeHash.c */
559extern size_t get_hash_memory_limit(void);
560
561#endif /* MISCADMIN_H */
#define PGDLLIMPORT
Definition c.h:1421
uint32_t uint32
Definition c.h:624
size_t Size
Definition c.h:689
const char * str
static char * username
Definition initdb.c:153
PGDLLIMPORT shmem_request_hook_type shmem_request_hook
Definition miscinit.c:1791
void process_shmem_requests(void)
Definition miscinit.c:1881
void InitializeMaxBackends(void)
Definition postinit.c:559
ProcessingMode
Definition miscadmin.h:487
@ NormalProcessing
Definition miscadmin.h:490
@ InitProcessing
Definition miscadmin.h:489
@ BootstrapProcessing
Definition miscadmin.h:488
void pg_split_opts(char **argv, int *argcp, const char *optstr)
Definition postinit.c:501
void SerializeClientConnectionInfo(Size maxsize, char *start_address)
Definition miscinit.c:1053
void AddToDataDirLockFile(int target_line, const char *str)
Definition miscinit.c:1521
void BaseInit(void)
Definition postinit.c:616
void StoreConnectionWarning(char *msg, char *detail)
Definition postinit.c:1491
void process_session_preload_libraries(void)
Definition miscinit.c:1867
PGDLLIMPORT char * shared_preload_libraries_string
Definition miscinit.c:1784
Size EstimateClientConnectionInfoSpace(void)
Definition miscinit.c:1037
PGDLLIMPORT bool IgnoreSystemIndexes
Definition miscinit.c:82
PGDLLIMPORT bool process_shmem_requests_in_progress
Definition miscinit.c:1792
void process_shared_preload_libraries(void)
Definition miscinit.c:1853
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
Definition miscinit.c:1788
void InitializeFastPathLocks(void)
Definition postinit.c:584
void TouchSocketLockFiles(void)
Definition miscinit.c:1492
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3680
void RestoreClientConnectionInfo(char *conninfo)
Definition miscinit.c:1086
PGDLLIMPORT char * local_preload_libraries_string
Definition miscinit.c:1785
PGDLLIMPORT char * session_preload_libraries_string
Definition miscinit.c:1783
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:719
PGDLLIMPORT ProcessingMode Mode
Definition miscinit.c:63
void(* shmem_request_hook_type)(void)
Definition miscadmin.h:552
void pg_bindtextdomain(const char *domain)
Definition miscinit.c:1890
bool has_rolreplication(Oid roleid)
Definition miscinit.c:689
PGDLLIMPORT bool process_shared_preload_libraries_done
Definition miscinit.c:1789
void ValidatePgVersion(const char *path)
Definition miscinit.c:1720
bool RecheckDataDirLockFile(void)
Definition miscinit.c:1648
void CreateDataDirLockFile(bool amPostmaster)
Definition miscinit.c:1465
void CreateSocketLockFile(const char *socketfile, bool amPostmaster, const char *socketDir)
Definition miscinit.c:1474
unsigned int Oid
static int fb(int x)

◆ AmIoWorkerProcess

#define AmIoWorkerProcess ( )    (MyBackendType == B_IO_WORKER)

Definition at line 409 of file miscadmin.h.

◆ AmLogicalSlotSyncWorkerProcess

#define AmLogicalSlotSyncWorkerProcess ( )    (MyBackendType == B_SLOTSYNC_WORKER)

Definition at line 401 of file miscadmin.h.

◆ AmRegularBackendProcess

#define AmRegularBackendProcess ( )    (MyBackendType == B_BACKEND)

Definition at line 396 of file miscadmin.h.

◆ AmSpecialWorkerProcess

#define AmSpecialWorkerProcess ( )
Value:

Definition at line 414 of file miscadmin.h.

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyBackendType == B_STARTUP)

Definition at line 405 of file miscadmin.h.

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyBackendType == B_WAL_RECEIVER)

Definition at line 406 of file miscadmin.h.

◆ AmWalSenderProcess

#define AmWalSenderProcess ( )    (MyBackendType == B_WAL_SENDER)

Definition at line 400 of file miscadmin.h.

◆ AmWalSummarizerProcess

#define AmWalSummarizerProcess ( )    (MyBackendType == B_WAL_SUMMARIZER)

Definition at line 407 of file miscadmin.h.

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyBackendType == B_WAL_WRITER)

Definition at line 408 of file miscadmin.h.

◆ BACKEND_NUM_TYPES

#define BACKEND_NUM_TYPES   (B_LOGGER + 1)

Definition at line 392 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

#define CHECK_FOR_INTERRUPTS ( )
Value:
do { \
} while(0)
#define INTERRUPTS_PENDING_CONDITION()
Definition miscadmin.h:115

Definition at line 125 of file miscadmin.h.

126 { \
129} while(0)

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

Definition at line 247 of file miscadmin.h.

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 248 of file miscadmin.h.

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 246 of file miscadmin.h.

◆ END_CRIT_SECTION

#define END_CRIT_SECTION ( )
Value:
do { \
} while(0)
PGDLLIMPORT volatile uint32 CritSectionCount
Definition globals.c:45

Definition at line 154 of file miscadmin.h.

155 { \
158} while(0)

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 499 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 144 of file miscadmin.h.

◆ HOLD_INTERRUPTS

#define HOLD_INTERRUPTS ( )    (InterruptHoldoffCount++)

Definition at line 136 of file miscadmin.h.

◆ INIT_PG_LOAD_SESSION_LIBS

#define INIT_PG_LOAD_SESSION_LIBS   0x0001

Definition at line 517 of file miscadmin.h.

◆ INIT_PG_OVERRIDE_ALLOW_CONNS

#define INIT_PG_OVERRIDE_ALLOW_CONNS   0x0002

Definition at line 518 of file miscadmin.h.

◆ INIT_PG_OVERRIDE_ROLE_LOGIN

#define INIT_PG_OVERRIDE_ROLE_LOGIN   0x0004

Definition at line 519 of file miscadmin.h.

◆ INTERRUPTS_CAN_BE_PROCESSED

#define INTERRUPTS_CAN_BE_PROCESSED ( )
Value:
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
Definition globals.c:43
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
Definition globals.c:44

Definition at line 132 of file miscadmin.h.

◆ INTERRUPTS_PENDING_CONDITION

#define INTERRUPTS_PENDING_CONDITION ( )     (unlikely(InterruptPending))

Definition at line 115 of file miscadmin.h.

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 263 of file miscadmin.h.

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 260 of file miscadmin.h.

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 261 of file miscadmin.h.

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 262 of file miscadmin.h.

◆ InvalidPid

#define InvalidPid   (-1)

Definition at line 32 of file miscadmin.h.

◆ IsBootstrapProcessingMode

#define IsBootstrapProcessingMode ( )    (Mode == BootstrapProcessing)

Definition at line 495 of file miscadmin.h.

◆ IsExternalConnectionBackend

#define IsExternalConnectionBackend (   backend_type)     (backend_type == B_BACKEND || backend_type == B_WAL_SENDER)

Definition at line 423 of file miscadmin.h.

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

Definition at line 496 of file miscadmin.h.

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

Definition at line 497 of file miscadmin.h.

◆ MAX_BAS_VAC_RING_SIZE_KB

#define MAX_BAS_VAC_RING_SIZE_KB   (16 * 1024 * 1024)

Definition at line 282 of file miscadmin.h.

◆ MAXTZLEN

#define MAXTZLEN   10 /* max TZ name len, not counting tr. null */

Definition at line 267 of file miscadmin.h.

◆ MIN_BAS_VAC_RING_SIZE_KB

#define MIN_BAS_VAC_RING_SIZE_KB   128

Definition at line 281 of file miscadmin.h.

◆ RESUME_CANCEL_INTERRUPTS

#define RESUME_CANCEL_INTERRUPTS ( )
Value:

Definition at line 146 of file miscadmin.h.

147 { \
150} while(0)

◆ RESUME_INTERRUPTS

#define RESUME_INTERRUPTS ( )
Value:

Definition at line 138 of file miscadmin.h.

139 { \
142} while(0)

◆ SECURITY_LOCAL_USERID_CHANGE

#define SECURITY_LOCAL_USERID_CHANGE   0x0001

Definition at line 330 of file miscadmin.h.

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 332 of file miscadmin.h.

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

Definition at line 331 of file miscadmin.h.

◆ SetProcessingMode

#define SetProcessingMode (   mode)
Value:
do { \
(mode) == InitProcessing || \
Mode = (mode); \
} while(0)
static PgChecksumMode mode

Definition at line 501 of file miscadmin.h.

502 { \
504 (mode) == InitProcessing || \
505 (mode) == NormalProcessing); \
506 Mode = (mode); \
507 } while(0)

◆ STACK_DEPTH_SLOP

#define STACK_DEPTH_SLOP   (512 * 1024)

Definition at line 300 of file miscadmin.h.

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 152 of file miscadmin.h.

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 242 of file miscadmin.h.

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

Definition at line 240 of file miscadmin.h.

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 239 of file miscadmin.h.

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 241 of file miscadmin.h.

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Definition at line 243 of file miscadmin.h.

Typedef Documentation

◆ BackendType

◆ pg_stack_base_t

Definition at line 302 of file miscadmin.h.

◆ ProcessingMode

◆ shmem_request_hook_type

typedef void(* shmem_request_hook_type) (void)

Definition at line 552 of file miscadmin.h.

Enumeration Type Documentation

◆ BackendType

Enumerator
B_INVALID 
B_BACKEND 
B_DEAD_END_BACKEND 
B_AUTOVAC_LAUNCHER 
B_AUTOVAC_WORKER 
B_BG_WORKER 
B_WAL_SENDER 
B_SLOTSYNC_WORKER 
B_STANDALONE_BACKEND 
B_ARCHIVER 
B_BG_WRITER 
B_CHECKPOINTER 
B_IO_WORKER 
B_STARTUP 
B_WAL_RECEIVER 
B_WAL_SUMMARIZER 
B_WAL_WRITER 
B_DATACHECKSUMSWORKER_LAUNCHER 
B_DATACHECKSUMSWORKER_WORKER 
B_LOGGER 

Definition at line 349 of file miscadmin.h.

350{
351 B_INVALID = 0,
352
353 /* Backends and other backend-like processes */
354 B_BACKEND,
361
363
364 /*
365 * Auxiliary processes. These have PGPROC entries, but they are not
366 * attached to any particular database, and cannot run transactions or
367 * even take heavyweight locks. There can be only one of each of these
368 * running at a time, except for IO workers.
369 *
370 * If you modify these, make sure to update NUM_AUXILIARY_PROCS and the
371 * glossary in the docs.
372 */
377 B_STARTUP,
381
384
385 /*
386 * Logger is not connected to shared memory and does not have a PGPROC
387 * entry.
388 */
389 B_LOGGER,
BackendType
Definition miscadmin.h:350
@ B_WAL_SUMMARIZER
Definition miscadmin.h:379
@ B_WAL_WRITER
Definition miscadmin.h:380
@ B_WAL_RECEIVER
Definition miscadmin.h:378
@ B_CHECKPOINTER
Definition miscadmin.h:375
@ B_WAL_SENDER
Definition miscadmin.h:359
@ B_IO_WORKER
Definition miscadmin.h:376
@ B_LOGGER
Definition miscadmin.h:389
@ B_STARTUP
Definition miscadmin.h:377
@ B_BG_WORKER
Definition miscadmin.h:358
@ B_INVALID
Definition miscadmin.h:351
@ B_STANDALONE_BACKEND
Definition miscadmin.h:362
@ B_BG_WRITER
Definition miscadmin.h:374
@ B_BACKEND
Definition miscadmin.h:354
@ B_ARCHIVER
Definition miscadmin.h:373
@ B_AUTOVAC_LAUNCHER
Definition miscadmin.h:356
@ B_SLOTSYNC_WORKER
Definition miscadmin.h:360
@ B_DEAD_END_BACKEND
Definition miscadmin.h:355
@ B_AUTOVAC_WORKER
Definition miscadmin.h:357

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 486 of file miscadmin.h.

487{
488 BootstrapProcessing, /* bootstrap creation of template database */
489 InitProcessing, /* initializing system */
490 NormalProcessing, /* normal processing */

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char str 
)
extern

Definition at line 1521 of file miscinit.c.

1522{
1523 int fd;
1524 int len;
1525 int lineno;
1526 char *srcptr;
1527 char *destptr;
1528 char srcbuffer[BLCKSZ];
1529 char destbuffer[BLCKSZ];
1530
1532 if (fd < 0)
1533 {
1534 ereport(LOG,
1536 errmsg("could not open file \"%s\": %m",
1538 return;
1539 }
1541 len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1543 if (len < 0)
1544 {
1545 ereport(LOG,
1547 errmsg("could not read from file \"%s\": %m",
1549 close(fd);
1550 return;
1551 }
1552 srcbuffer[len] = '\0';
1553
1554 /*
1555 * Advance over lines we are not supposed to rewrite, then copy them to
1556 * destbuffer.
1557 */
1558 srcptr = srcbuffer;
1559 for (lineno = 1; lineno < target_line; lineno++)
1560 {
1561 char *eol = strchr(srcptr, '\n');
1562
1563 if (eol == NULL)
1564 break; /* not enough lines in file yet */
1565 srcptr = eol + 1;
1566 }
1569
1570 /*
1571 * Fill in any missing lines before the target line, in case lines are
1572 * added to the file out of order.
1573 */
1574 for (; lineno < target_line; lineno++)
1575 {
1576 if (destptr < destbuffer + sizeof(destbuffer))
1577 *destptr++ = '\n';
1578 }
1579
1580 /*
1581 * Write or rewrite the target line.
1582 */
1583 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1585
1586 /*
1587 * If there are more lines in the old file, append them to destbuffer.
1588 */
1589 if ((srcptr = strchr(srcptr, '\n')) != NULL)
1590 {
1591 srcptr++;
1592 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1593 srcptr);
1594 }
1595
1596 /*
1597 * And rewrite the data. Since we write in a single kernel call, this
1598 * update should appear atomic to onlookers.
1599 */
1601 errno = 0;
1603 if (pg_pwrite(fd, destbuffer, len, 0) != len)
1604 {
1606 /* if write didn't set errno, assume problem is no disk space */
1607 if (errno == 0)
1608 errno = ENOSPC;
1609 ereport(LOG,
1611 errmsg("could not write to file \"%s\": %m",
1613 close(fd);
1614 return;
1615 }
1618 if (pg_fsync(fd) != 0)
1619 {
1620 ereport(LOG,
1622 errmsg("could not write to file \"%s\": %m",
1624 }
1626 if (close(fd) != 0)
1627 {
1628 ereport(LOG,
1630 errmsg("could not write to file \"%s\": %m",
1632 }
1633}
#define PG_BINARY
Definition c.h:1374
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
int errcode_for_file_access(void)
Definition elog.c:897
#define LOG
Definition elog.h:32
#define ereport(elevel,...)
Definition elog.h:152
int pg_fsync(int fd)
Definition fd.c:390
#define close(a)
Definition win32.h:12
#define read(a, b, c)
Definition win32.h:13
#define DIRECTORY_LOCK_FILE
Definition miscinit.c:61
static char * errmsg
const void size_t len
#define pg_pwrite
Definition port.h:248
#define snprintf
Definition port.h:260
static int fd(const char *x, int i)
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:67
static void pgstat_report_wait_end(void)
Definition wait_event.h:83

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg, fb(), fd(), len, LOG, memcpy(), PG_BINARY, pg_fsync(), pg_pwrite, pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf, and str.

Referenced by InternalIpcMemoryCreate(), PostmasterMain(), process_pm_child_exit(), process_pm_pmsignal(), and process_pm_shutdown_request().

◆ BaseInit()

void BaseInit ( void  )
extern

Definition at line 616 of file postinit.c.

617{
618 Assert(MyProc != NULL);
619
620 /*
621 * Initialize our input/output/debugging file descriptors.
622 */
624
625 /*
626 * Initialize file access. Done early so other subsystems can access
627 * files.
628 */
630
631 /*
632 * Initialize statistics reporting. This needs to happen early to ensure
633 * that pgstat's shutdown callback runs after the shutdown callbacks of
634 * all subsystems that can produce stats (like e.g. transaction commits
635 * can).
636 */
638
639 /*
640 * Initialize AIO before infrastructure that might need to actually
641 * execute AIO.
642 */
644
645 /* Do local initialization of storage and buffer managers */
646 InitSync();
647 smgrinit();
649
650 /*
651 * Initialize temporary file access after pgstat, so that the temporary
652 * file shutdown hook can report temporary file statistics.
653 */
655
656 /*
657 * Initialize local buffers for WAL record construction, in case we ever
658 * try to insert XLOG.
659 */
661
662 /* Initialize lock manager's local structs */
664
665 /* Initialize logical info WAL logging state */
667
668 /*
669 * Initialize replication slots after pgstat. The exit hook might need to
670 * drop ephemeral slots, which in turn triggers stats reporting.
671 */
673}
void pgaio_init_backend(void)
Definition aio_init.c:238
void InitBufferManagerAccess(void)
Definition bufmgr.c:4216
#define Assert(condition)
Definition c.h:943
void DebugFileOpen(void)
Definition elog.c:2306
void InitFileAccess(void)
Definition fd.c:904
void InitTemporaryFileAccess(void)
Definition fd.c:934
void InitLockManagerAccess(void)
Definition lock.c:503
void InitializeProcessXLogLogicalInfo(void)
Definition logicalctl.c:174
void pgstat_initialize(void)
Definition pgstat.c:669
void ReplicationSlotInitialize(void)
Definition slot.c:240
void smgrinit(void)
Definition smgr.c:188
PGPROC * MyProc
Definition proc.c:71
void InitSync(void)
Definition sync.c:125
void InitXLogInsert(void)

References Assert, DebugFileOpen(), fb(), InitBufferManagerAccess(), InitFileAccess(), InitializeProcessXLogLogicalInfo(), InitLockManagerAccess(), InitSync(), InitTemporaryFileAccess(), InitXLogInsert(), MyProc, pgaio_init_backend(), pgstat_initialize(), ReplicationSlotInitialize(), and smgrinit().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMainCommon(), BackgroundWorkerMain(), BootstrapModeMain(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )
extern

Definition at line 410 of file miscinit.c.

411{
413
414 if (chdir(DataDir) < 0)
417 errmsg("could not change directory to \"%s\": %m",
418 DataDir)));
419}
#define FATAL
Definition elog.h:42
char * DataDir
Definition globals.c:73

References Assert, DataDir, ereport, errcode_for_file_access(), errmsg, FATAL, and fb().

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

◆ check_stack_depth()

void check_stack_depth ( void  )
extern

Definition at line 95 of file stack_depth.c.

96{
98 {
101 errmsg("stack depth limit exceeded"),
102 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
103 "after ensuring the platform's stack depth limit is adequate.",
105 }
106}
int errcode(int sqlerrcode)
Definition elog.c:874
int errhint(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
int max_stack_depth
Definition stack_depth.c:26
bool stack_is_too_deep(void)

References ereport, errcode(), errhint(), errmsg, ERROR, fb(), max_stack_depth, and stack_is_too_deep().

Referenced by _jumbleNode(), AlterTypeRecurse(), apply_scanjoin_target_to_paths(), ATAddCheckNNConstraint(), ATExecAddColumn(), ATExecAlterCheckConstrEnforceability(), ATExecAlterConstrDeferrability(), ATExecAlterFKConstrEnforceability(), ATExecDropColumn(), ATExecSetNotNull(), CheckAttributeType(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json_internal(), datum_to_jsonb_internal(), dofindsubquery(), dropconstraint_internal(), emit_jsp_gin_entries(), equal(), eval_const_expressions_mutator(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode_walker(), execute(), executeAnyItem(), executeBoolItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expr_is_nonnullable(), expression_tree_mutator_impl(), expression_tree_walker_impl(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findDependentObjects(), findoprnd(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), get_graph_label_expr(), get_query_def(), get_rels_with_domain(), get_rule_expr(), get_setop_query(), get_steps_using_prefix_recurse(), gistSplit(), hash_range(), hash_range_extended(), hash_record(), hash_record_extended(), hk_depth_search(), infix(), infix(), infix(), inline_function_in_from(), int_query_opr_selec(), is_simple_union_all_recurse(), json_check_mutability(), JsonbDeepContains(), lseg_inside_poly(), ltree_execute(), makepol(), makepol(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), p_ishost(), p_isURLPath(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker_impl(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), pull_up_sublinks_jointree_recurse(), pull_up_subqueries_recurse(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker_impl(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), regex_selectivity_sub(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), setPath(), split_array(), SplitToVariants(), standard_ProcessUtility(), transformExprRecurse(), transformFromClauseItem(), transformLabelExpr(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute_locations_recurse(), TS_execute_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

◆ checkDataDir()

void checkDataDir ( void  )
extern

Definition at line 297 of file miscinit.c.

298{
299 struct stat stat_buf;
300
302
303 if (stat(DataDir, &stat_buf) != 0)
304 {
305 if (errno == ENOENT)
308 errmsg("data directory \"%s\" does not exist",
309 DataDir)));
310 else
313 errmsg("could not read permissions of directory \"%s\": %m",
314 DataDir)));
315 }
316
317 /* eventual chdir would fail anyway, but let's test ... */
318 if (!S_ISDIR(stat_buf.st_mode))
321 errmsg("specified data directory \"%s\" is not a directory",
322 DataDir)));
323
324 /*
325 * Check that the directory belongs to my userid; if not, reject.
326 *
327 * This check is an essential part of the interlock that prevents two
328 * postmasters from starting in the same directory (see CreateLockFile()).
329 * Do not remove or weaken it.
330 *
331 * XXX can we safely enable this check on Windows?
332 */
333#if !defined(WIN32) && !defined(__CYGWIN__)
334 if (stat_buf.st_uid != geteuid())
337 errmsg("data directory \"%s\" has wrong ownership",
338 DataDir),
339 errhint("The server must be started by the user that owns the data directory.")));
340#endif
341
342 /*
343 * Check if the directory has correct permissions. If not, reject.
344 *
345 * Only two possible modes are allowed, 0700 and 0750. The latter mode
346 * indicates that group read/execute should be allowed on all newly
347 * created files and directories.
348 *
349 * XXX temporarily suppress check when on Windows, because there may not
350 * be proper support for Unix-y file permissions. Need to think of a
351 * reasonable check to apply on Windows.
352 */
353#if !defined(WIN32) && !defined(__CYGWIN__)
354 if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
357 errmsg("data directory \"%s\" has invalid permissions",
358 DataDir),
359 errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
360#endif
361
362 /*
363 * Reset creation modes and mask based on the mode of the data directory.
364 *
365 * The mask was set earlier in startup to disallow group permissions on
366 * newly created files and directories. However, if group read/execute
367 * are present on the data directory then modify the create modes and mask
368 * to allow group read/execute on newly created files and directories and
369 * set the data_directory_mode GUC.
370 *
371 * Suppress when on Windows, because there may not be proper support for
372 * Unix-y file permissions.
373 */
374#if !defined(WIN32) && !defined(__CYGWIN__)
376
379#endif
380
381 /* Check for PG_VERSION */
383}
int errdetail(const char *fmt,...) pg_attribute_printf(1
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition file_perm.c:34
int pg_mode_mask
Definition file_perm.c:25
int pg_dir_create_mode
Definition file_perm.c:18
#define PG_MODE_MASK_GROUP
Definition file_perm.h:29
int data_directory_mode
Definition globals.c:79
void ValidatePgVersion(const char *path)
Definition miscinit.c:1720
#define stat
Definition win32_port.h:74
#define S_ISDIR(m)
Definition win32_port.h:315

References Assert, data_directory_mode, DataDir, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg, FATAL, fb(), pg_dir_create_mode, pg_mode_mask, PG_MODE_MASK_GROUP, S_ISDIR, SetDataDirectoryCreatePerm(), stat, and ValidatePgVersion().

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

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)
extern

Definition at line 1465 of file miscinit.c.

1466{
1468}
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition miscinit.c:1160

References CreateLockFile(), DataDir, DIRECTORY_LOCK_FILE, and fb().

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

◆ CreateSocketLockFile()

void CreateSocketLockFile ( const char socketfile,
bool  amPostmaster,
const char socketDir 
)
extern

Definition at line 1474 of file miscinit.c.

1476{
1477 char lockfile[MAXPGPATH];
1478
1479 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1481}
#define MAXPGPATH

References CreateLockFile(), fb(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )
extern

Definition at line 1037 of file miscinit.c.

1038{
1039 Size size = 0;
1040
1041 size = add_size(size, sizeof(SerializedClientConnectionInfo));
1042
1045
1046 return size;
1047}
ClientConnectionInfo MyClientConnectionInfo
Definition miscinit.c:1020
Size add_size(Size s1, Size s2)
Definition shmem.c:1048
const char * authn_id
Definition libpq-be.h:99

References add_size(), ClientConnectionInfo::authn_id, fb(), and MyClientConnectionInfo.

Referenced by InitializeParallelDSM().

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )
extern

Definition at line 3680 of file nodeHash.c.

3681{
3682 double mem_limit;
3683
3684 /* Do initial calculation in double arithmetic */
3685 mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3686
3687 /* Clamp in case it doesn't fit in size_t */
3688 mem_limit = Min(mem_limit, (double) SIZE_MAX);
3689
3690 return (size_t) mem_limit;
3691}
#define Min(x, y)
Definition c.h:1091
double hash_mem_multiplier
Definition globals.c:134
int work_mem
Definition globals.c:133

References fb(), hash_mem_multiplier, Min, and work_mem.

Referenced by consider_groupingsets_paths(), cost_memoize_rescan(), create_setop_path(), ExecChooseHashTableSize(), ExecInitMemoize(), ExecParallelHashIncreaseNumBatches(), final_cost_hashjoin(), hash_agg_set_limits(), hash_choose_num_partitions(), subpath_is_hashable(), and subplan_is_hashable().

◆ get_stack_depth_rlimit()

ssize_t get_stack_depth_rlimit ( void  )
extern

Definition at line 176 of file stack_depth.c.

177{
178#if defined(HAVE_GETRLIMIT)
179 static ssize_t val = 0;
180
181 /* This won't change after process launch, so check just once */
182 if (val == 0)
183 {
184 struct rlimit rlim;
185
186 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
187 val = -1;
188 else if (rlim.rlim_cur == RLIM_INFINITY)
189 val = SSIZE_MAX;
190 /* rlim_cur is probably of an unsigned type, so check for overflow */
191 else if (rlim.rlim_cur >= SSIZE_MAX)
192 val = SSIZE_MAX;
193 else
194 val = rlim.rlim_cur;
195 }
196 return val;
197#else
198 /* On Windows we set the backend stack size in src/backend/Makefile */
199 return WIN32_STACK_RLIMIT;
200#endif
201}
long val
Definition informix.c:689

References fb(), and val.

Referenced by check_max_stack_depth(), and InitializeGUCOptionsFromEnvironment().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )
extern

Definition at line 546 of file miscinit.c.

547{
549 return AuthenticatedUserId;
550}
#define OidIsValid(objectId)
Definition c.h:858
static Oid AuthenticatedUserId
Definition miscinit.c:450

References Assert, AuthenticatedUserId, and OidIsValid.

Referenced by check_session_authorization(), and InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char * GetBackendTypeDesc ( BackendType  backendType)
extern

Definition at line 264 of file miscinit.c.

265{
266 const char *backendDesc = gettext_noop("unknown process type");
267
268 switch (backendType)
269 {
270#define PG_PROCTYPE(bktype, bkcategory, description, main_func, shmem_attach) \
271 case bktype: backendDesc = description; break;
273#undef PG_PROCTYPE
274 }
275 return backendDesc;
276}
#define gettext_noop(x)
Definition c.h:1285

References fb(), and gettext_noop.

Referenced by BackendInitialize(), BackendStartup(), CleanupBackend(), CountChildren(), get_backend_type_for_log(), init_ps_display(), pg_stat_get_activity(), pg_stat_io_build_tuples(), and signal_child().

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )
extern

Definition at line 937 of file miscinit.c.

938{
939 if (SetRoleIsActive)
940 return OuterUserId;
941 else
942 return InvalidOid;
943}
static Oid OuterUserId
Definition miscinit.c:452
static bool SetRoleIsActive
Definition miscinit.c:462
#define InvalidOid

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by check_role(), InitializeParallelDSM(), and show_role().

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )
extern

Definition at line 481 of file miscinit.c.

482{
484 return OuterUserId;
485}

References Assert, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

◆ GetSessionUserIsSuperuser()

bool GetSessionUserIsSuperuser ( void  )
extern

Definition at line 516 of file miscinit.c.

517{
520}
static bool SessionUserIsSuperuser
Definition miscinit.c:457

References Assert, OidIsValid, SessionUserId, and SessionUserIsSuperuser.

Referenced by check_session_authorization(), and InitializeParallelDSM().

◆ GetSystemUser()

const char * GetSystemUser ( void  )
extern

Definition at line 536 of file miscinit.c.

537{
538 return SystemUser;
539}
static const char * SystemUser
Definition miscinit.c:454

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )
extern

Definition at line 470 of file miscinit.c.

471{
473 return CurrentUserId;
474}
static Oid CurrentUserId
Definition miscinit.c:453

References Assert, CurrentUserId, and OidIsValid.

Referenced by AfterTriggerSaveEvent(), AggregateCreate(), all_rows_selectable(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_unlink(), binary_upgrade_check_logical_slot_pending_wal(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_search_path(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), ConfigOptionIsVisible(), convert_and_check_filename(), copy_sequence(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTriggerFiringOn(), current_user(), currtid_internal(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), emit_audit_message(), EnableDisableRule(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildParamSetEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckOneRelPerms(), ExecCheckpoint(), ExecGetResultRelCheckAsUser(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteTruncateGuts(), extension_is_trusted(), fetch_remote_statistics(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), fmgr_security_definer(), get_connect_string(), get_other_operator(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_repack(), get_tables_to_repack_partitioned(), GetConfigOptionValues(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_largeobject_privilege_id(), has_parameter_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), heap_force_common(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_function_in_from(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockViewRecurse(), LogicalRepSyncTableStart(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_get_database_ddl_internal(), pg_get_multixact_stats(), pg_get_role_ddl_internal(), pg_get_sequence_data(), pg_get_tablespace_ddl_internal(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_recovery(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDblink(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackForStats(), RangeVarCallbackMaintainsTable(), RangeVarCallbackOwnsRelation(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameRole(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), ri_CheckPermissions(), RI_Initial_Check(), ri_ReportViolation(), select_best_grantor(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), SetSequence(), shell_check_detail(), start_repack_decoding_worker(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_permitted_for_relation(), validate_option_array_item(), ValidateJoinEstimator(), ValidateOperatorReference(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)
extern

Definition at line 662 of file miscinit.c.

663{
664 *userid = CurrentUserId;
666}
bool InLocalUserIdChange(void)
Definition miscinit.c:631

References CurrentUserId, fb(), and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char * GetUserNameFromId ( Oid  roleid,
bool  noerr 
)
extern

Definition at line 990 of file miscinit.c.

991{
992 HeapTuple tuple;
993 char *result;
994
995 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
996 if (!HeapTupleIsValid(tuple))
997 {
998 if (!noerr)
1001 errmsg("invalid role OID: %u", roleid)));
1002 result = NULL;
1003 }
1004 else
1005 {
1007 ReleaseSysCache(tuple);
1008 }
1009 return result;
1010}
#define NameStr(name)
Definition c.h:835
uint32 result
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
char * pstrdup(const char *in)
Definition mcxt.c:1781
NameData rolname
Definition pg_authid.h:36
END_CATALOG_STRUCT typedef FormData_pg_authid * Form_pg_authid
Definition pg_authid.h:60
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221

References ereport, errcode(), errmsg, ERROR, fb(), Form_pg_authid, GETSTRUCT(), HeapTupleIsValid, NameStr, ObjectIdGetDatum(), pstrdup(), ReleaseSysCache(), result, rolname, and SearchSysCache1().

Referenced by AddRoleMems(), AlterSubscription(), AlterSubscriptionOwner_internal(), check_can_set_role(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), current_user(), DelRoleMems(), DropOwnedObjects(), DropSubscription(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), GetSubscription(), insert_username(), LogicalRepSyncTableStart(), pg_get_database_ddl_internal(), pg_get_role_ddl_internal(), pg_get_tablespace_ddl_internal(), ReassignOwnedObjects(), regroleout(), select_best_grantor(), session_user(), SwitchToUntrustedUser(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)
extern

Definition at line 689 of file miscinit.c.

690{
691 bool result = false;
693
694 /* Superusers bypass all permission checking. */
695 if (superuser_arg(roleid))
696 return true;
697
700 {
703 }
704 return result;
705}
bool rolreplication
Definition pg_authid.h:42
bool superuser_arg(Oid roleid)
Definition superuser.c:57

References fb(), Form_pg_authid, GETSTRUCT(), HeapTupleIsValid, ObjectIdGetDatum(), ReleaseSysCache(), result, rolreplication, SearchSysCache1(), and superuser_arg().

Referenced by AlterRole(), binary_upgrade_check_logical_slot_pending_wal(), CheckSlotPermissions(), CreateRole(), and InitPostgres().

◆ InitializeFastPathLocks()

void InitializeFastPathLocks ( void  )
extern

Definition at line 584 of file postinit.c.

585{
586 /* Should be initialized only once. */
588
589 /*
590 * Based on the max_locks_per_transaction GUC, as that's a good indicator
591 * of the expected number of locks, figure out the value for
592 * FastPathLockGroupsPerBackend. This must be a power-of-two. We cap the
593 * value at FP_LOCK_GROUPS_PER_BACKEND_MAX and insist the value is at
594 * least 1.
595 *
596 * The default max_locks_per_transaction = 128 means 8 groups by default.
597 */
601
602 /* Validate we did get a power-of-two */
605}
#define Max(x, y)
Definition c.h:1085
int max_locks_per_xact
Definition lock.c:56
int FastPathLockGroupsPerBackend
Definition lock.c:205
static uint32 pg_nextpower2_32(uint32 num)
#define FP_LOCK_GROUPS_PER_BACKEND_MAX
Definition proc.h:95
#define FP_LOCK_SLOTS_PER_GROUP
Definition proc.h:96

References Assert, FastPathLockGroupsPerBackend, FP_LOCK_GROUPS_PER_BACKEND_MAX, FP_LOCK_SLOTS_PER_GROUP, Max, max_locks_per_xact, Min, and pg_nextpower2_32().

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

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )
extern

Definition at line 559 of file postinit.c.

560{
561 Assert(MaxBackends == 0);
562
563 /* Note that this does not include "auxiliary" processes */
566
570 errmsg("too many server processes configured"),
571 errdetail("\"max_connections\" (%d) plus \"autovacuum_worker_slots\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
575}
int autovacuum_worker_slots
Definition autovacuum.c:124
int MaxConnections
Definition globals.c:145
int MaxBackends
Definition globals.c:149
int max_worker_processes
Definition globals.c:146
#define NUM_SPECIAL_WORKER_PROCS
Definition proc.h:514
#define MAX_BACKENDS
Definition procnumber.h:39
int max_wal_senders
Definition walsender.c:141

References Assert, autovacuum_worker_slots, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), MAX_BACKENDS, max_wal_senders, max_worker_processes, MaxBackends, MaxConnections, and NUM_SPECIAL_WORKER_PROCS.

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

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char rolename,
Oid  roleid,
bool  bypass_login_check 
)
extern

Definition at line 711 of file miscinit.c.

713{
716 char *rname;
717 bool is_superuser;
718
719 /*
720 * In a parallel worker, we don't have to do anything here.
721 * ParallelWorkerMain already set our output variables, and we aren't
722 * going to enforce either rolcanlogin or rolconnlimit. Furthermore, we
723 * don't really want to perform a catalog lookup for the role: we don't
724 * want to fail if it's been dropped.
725 */
727 {
729 return;
730 }
731
732 /*
733 * Don't do scans if we're bootstrapping, none of the system catalogs
734 * exist yet, and they should be owned by postgres anyway.
735 */
737
738 /*
739 * Make sure syscache entries are flushed for recent catalog changes. This
740 * allows us to find roles that were created on-the-fly during
741 * authentication.
742 */
744
745 /*
746 * Look up the role, either by name if that's given or by OID if not.
747 */
748 if (rolename != NULL)
749 {
754 errmsg("role \"%s\" does not exist", rolename)));
755 }
756 else
757 {
762 errmsg("role with OID %u does not exist", roleid)));
763 }
764
766 roleid = rform->oid;
767 rname = NameStr(rform->rolname);
768 is_superuser = rform->rolsuper;
769
771
772 /*
773 * Set SessionUserId and related variables, including "role", via the GUC
774 * mechanisms.
775 *
776 * Note: ideally we would use PGC_S_DYNAMIC_DEFAULT here, so that
777 * session_authorization could subsequently be changed from
778 * pg_db_role_setting entries. Instead, session_authorization in
779 * pg_db_role_setting has no effect. Changing that would require solving
780 * two problems:
781 *
782 * 1. If pg_db_role_setting has values for both session_authorization and
783 * role, we could not be sure which order those would be applied in, and
784 * it would matter.
785 *
786 * 2. Sites may have years-old session_authorization entries. There's not
787 * been any particular reason to remove them. Ending the dormancy of
788 * those entries could seriously change application behavior, so only a
789 * major release should do that.
790 */
791 SetConfigOption("session_authorization", rname,
793
794 /*
795 * These next checks are not enforced when in standalone mode, so that
796 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
797 * rolcanlogin = false;".
798 */
800 {
801 /*
802 * Is role allowed to login at all? (But background workers can
803 * override this by setting bypass_login_check.)
804 */
805 if (!bypass_login_check && !rform->rolcanlogin)
808 errmsg("role \"%s\" is not permitted to log in",
809 rname)));
810
811 /*
812 * Check connection limit for this role. We enforce the limit only
813 * for regular backends, since other process types have their own
814 * PGPROC pools.
815 *
816 * There is a race condition here --- we create our PGPROC before
817 * checking for other PGPROCs. If two backends did this at about the
818 * same time, they might both think they were over the limit, while
819 * ideally one should succeed and one fail. Getting that to work
820 * exactly seems more trouble than it is worth, however; instead we
821 * just document that the connection limit is approximate.
822 */
823 if (rform->rolconnlimit >= 0 &&
825 !is_superuser &&
826 CountUserBackends(roleid) > rform->rolconnlimit)
829 errmsg("too many connections for role \"%s\"",
830 rname)));
831 }
832
834}
bool InitializingParallelWorker
Definition parallel.c:123
bool is_superuser(void)
Definition common.c:2480
bool IsUnderPostmaster
Definition globals.c:122
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
@ PGC_S_OVERRIDE
Definition guc.h:123
@ PGC_BACKEND
Definition guc.h:77
void AcceptInvalidationMessages(void)
Definition inval.c:930
#define IsBootstrapProcessingMode()
Definition miscadmin.h:495
#define AmRegularBackendProcess()
Definition miscadmin.h:396
void SetAuthenticatedUserId(Oid userid)
Definition miscinit.c:553
static Datum PointerGetDatum(const void *X)
Definition postgres.h:342
int CountUserBackends(Oid roleid)
Definition procarray.c:3703

References AcceptInvalidationMessages(), AmRegularBackendProcess, Assert, CountUserBackends(), ereport, errcode(), errmsg, FATAL, fb(), Form_pg_authid, GETSTRUCT(), HeapTupleIsValid, InitializingParallelWorker, is_superuser(), IsBootstrapProcessingMode, IsUnderPostmaster, NameStr, ObjectIdGetDatum(), PGC_BACKEND, PGC_S_OVERRIDE, PointerGetDatum(), ReleaseSysCache(), SearchSysCache1(), SetAuthenticatedUserId(), and SetConfigOption().

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )
extern

Definition at line 841 of file miscinit.c.

842{
843 /*
844 * This function should only be called in single-user mode, in autovacuum
845 * workers, in slot sync worker and in background workers.
846 */
850
851 /* call only once */
853
855
856 /*
857 * XXX Ideally we'd do this via SetConfigOption("session_authorization"),
858 * but we lack the role name needed to do that, and we can't fetch it
859 * because one reason for this special case is to be able to start up even
860 * if something's happened to the BOOTSTRAP_SUPERUSERID's pg_authid row.
861 * Since we don't set the GUC itself, C code will see the value as NULL,
862 * and current_setting() will report an empty string within this session.
863 */
865
866 /* We could do SetConfigOption("role"), but let's be consistent */
868}
#define AmAutoVacuumWorkerProcess()
Definition miscadmin.h:398
#define AmBackgroundWorkerProcess()
Definition miscadmin.h:399
#define AmLogicalSlotSyncWorkerProcess()
Definition miscadmin.h:401
#define AmDataChecksumsWorkerProcess()
Definition miscadmin.h:410
void SetSessionAuthorization(Oid userid, bool is_superuser)
Definition miscinit.c:922
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition miscinit.c:958

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmDataChecksumsWorkerProcess, AmLogicalSlotSyncWorkerProcess, Assert, AuthenticatedUserId, fb(), InvalidOid, IsUnderPostmaster, OidIsValid, SetCurrentRoleId(), and SetSessionAuthorization().

Referenced by InitPostgres(), and pg_stash_advice_worker_main().

◆ InitializeSystemUser()

void InitializeSystemUser ( const char authn_id,
const char auth_method 
)
extern

Definition at line 876 of file miscinit.c.

877{
878 char *system_user;
879
880 /* call only once */
882
883 /*
884 * InitializeSystemUser should be called only when authn_id is not NULL,
885 * meaning that auth_method is valid.
886 */
887 Assert(authn_id != NULL);
888
889 system_user = psprintf("%s:%s", auth_method, authn_id);
890
891 /* Store SystemUser in long-lived storage */
894}
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition mcxt.c:1768
void pfree(void *pointer)
Definition mcxt.c:1616
MemoryContext TopMemoryContext
Definition mcxt.c:166
Datum system_user(PG_FUNCTION_ARGS)
Definition miscinit.c:900
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
static char * authn_id
Definition validator.c:41

References Assert, authn_id, fb(), MemoryContextStrdup(), pfree(), psprintf(), system_user(), SystemUser, and TopMemoryContext.

Referenced by InitPostgres(), and ParallelWorkerMain().

◆ InitPostgres()

void InitPostgres ( const char in_dbname,
Oid  dboid,
const char username,
Oid  useroid,
uint32  flags,
char out_dbname 
)
extern

Definition at line 719 of file postinit.c.

723{
725 bool am_superuser;
726 char *fullpath;
727 char dbname[NAMEDATALEN];
728 int nfree = 0;
729
730 elog(DEBUG3, "InitPostgres");
731
732 /*
733 * Add my PGPROC struct to the ProcArray.
734 *
735 * Once I have done this, I am visible to other backends!
736 */
738
739 /* Initialize status reporting */
741
742 /*
743 * And initialize an entry in the PgBackendStatus array. That way, if
744 * LWLocks or third-party authentication should happen to hang, it is
745 * possible to retrieve some information about what is going on.
746 */
747 if (!bootstrap)
748 {
750 INJECTION_POINT("init-pre-auth", NULL);
751 }
752
753 /*
754 * Initialize my entry in the shared-invalidation manager's array of
755 * per-backend data.
756 */
758
760
761 /*
762 * Initialize a local cache of the data_checksum_version, to be updated by
763 * the procsignal-based barriers.
764 *
765 * This intentionally happens after initializing the procsignal, otherwise
766 * we might miss a state change. This means we can get a barrier for the
767 * state we've just initialized.
768 *
769 * The postmaster (which is what gets forked into the new child process)
770 * does not handle barriers, therefore it may not have the current value
771 * of LocalDataChecksumVersion value (it'll have the value read from the
772 * control file, which may be arbitrarily old).
773 *
774 * NB: Even if the postmaster handled barriers, the value might still be
775 * stale, as it might have changed after this process forked.
776 */
778
779 /*
780 * Also set up timeout handlers needed for backend operation. We need
781 * these in every case except bootstrap.
782 */
783 if (!bootstrap)
784 {
795 }
796
797 /*
798 * If this is either a bootstrap process or a standalone backend, start up
799 * the XLOG machinery, and register to have it closed down at exit. In
800 * other cases, the startup process is responsible for starting up the
801 * XLOG machinery, and the checkpointer for closing it down.
802 */
804 {
805 /*
806 * We don't yet have an aux-process resource owner, but StartupXLOG
807 * and ShutdownXLOG will need one. Hence, create said resource owner
808 * (and register a callback to clean it up after ShutdownXLOG runs).
809 */
811
812 StartupXLOG();
813 /* Release (and warn about) any buffer pins leaked in StartupXLOG */
815 /* Reset CurrentResourceOwner to nothing for the moment */
817
818 /*
819 * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
820 * segments etc to work (which in turn is required for pgstats).
821 */
824 }
825
826 /*
827 * Initialize the relation cache and the system catalog caches. Note that
828 * no catalog access happens here; we only set up the hashtable structure.
829 * We must do this before starting a transaction because transaction abort
830 * would try to touch these hashtables.
831 */
835
836 /* Initialize portal manager */
838
839 /*
840 * Load relcache entries for the shared system catalogs. This must create
841 * at least entries for pg_database and catalogs used for authentication.
842 */
844
845 /*
846 * Set up process-exit callback to do pre-shutdown cleanup. This is one
847 * of the first before_shmem_exit callbacks we register; thus, this will
848 * be one of the last things we do before low-level modules like the
849 * buffer manager begin to close down. We need to have this in place
850 * before we begin our first transaction --- if we fail during the
851 * initialization transaction, as is entirely possible, we need the
852 * AbortTransaction call to clean up.
853 */
855
856 /* The autovacuum launcher is done here */
858 {
859 /* fill in the remainder of this entry in the PgBackendStatus array */
861
862 return;
863 }
864
865 /*
866 * Start a new transaction here before first access to db.
867 */
868 if (!bootstrap)
869 {
870 /* statement_timestamp must be set for timeouts to work correctly */
873
874 /*
875 * transaction_isolation will have been set to the default by the
876 * above. If the default is "serializable", and we are in hot
877 * standby, we will fail if we don't change it to something lower.
878 * Fortunately, "read committed" is plenty good enough.
879 */
881 }
882
883 /*
884 * Perform client authentication if necessary, then figure out our
885 * postgres user ID, and see if we are a superuser.
886 *
887 * In standalone mode, autovacuum worker processes and slot sync worker
888 * process, we use a fixed ID, otherwise we figure it out from the
889 * authenticated user name.
890 */
892 {
894 am_superuser = true;
895 }
896 else if (!IsUnderPostmaster)
897 {
899 am_superuser = true;
903 errmsg("no roles are defined in this database system"),
904 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
905 username != NULL ? username : "postgres")));
906 }
908 {
909 if (username == NULL && !OidIsValid(useroid))
910 {
912 am_superuser = true;
913 }
914 else
915 {
917 (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
919 }
920 }
921 else
922 {
923 /* normal multiuser case */
927 /* ensure that auth_method is actually valid, aka authn_id is not NULL */
932 }
933
934 /* Report any SSL/GSS details for the session. */
935 if (MyProcPort != NULL)
936 {
938
940 }
941
942 /*
943 * Binary upgrades only allowed super-user connections
944 */
946 {
949 errmsg("must be superuser to connect in binary upgrade mode")));
950 }
951
952 /*
953 * The last few regular connection slots are reserved for superusers and
954 * roles with privileges of pg_use_reserved_connections. We do not apply
955 * these limits to background processes, since they all have their own
956 * pools of PGPROC slots.
957 *
958 * Note: At this point, the new backend has already claimed a proc struct,
959 * so we must check whether the number of free slots is strictly less than
960 * the reserved connection limits.
961 */
965 {
969 errmsg("remaining connection slots are reserved for roles with the %s attribute",
970 "SUPERUSER")));
971
975 errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
976 "pg_use_reserved_connections")));
977 }
978
979 /* Check replication permissions needed for walsender processes. */
980 if (am_walsender)
981 {
983
987 errmsg("permission denied to start WAL sender"),
988 errdetail("Only roles with the %s attribute may start a WAL sender process.",
989 "REPLICATION")));
990 }
991
992 /*
993 * If this is a plain walsender only supporting physical replication, we
994 * don't want to connect to any particular database. Just finish the
995 * backend startup by processing any options from the startup packet, and
996 * we're done.
997 */
999 {
1000 /* process any options passed in the startup packet */
1001 if (MyProcPort != NULL)
1003
1004 /* Apply PostAuthDelay as soon as we've read all options */
1005 if (PostAuthDelay > 0)
1006 pg_usleep(PostAuthDelay * 1000000L);
1007
1008 /* initialize client encoding */
1010
1011 /* fill in the remainder of this entry in the PgBackendStatus array */
1013
1014 /* close the transaction we started above */
1016
1017 /* send any WARNINGs we've accumulated during initialization */
1019
1020 return;
1021 }
1022
1023 /*
1024 * Set up the global variables holding database id and default tablespace.
1025 * But note we won't actually try to touch the database just yet.
1026 *
1027 * We take a shortcut in the bootstrap case, otherwise we have to look up
1028 * the db's entry in pg_database.
1029 */
1030 if (bootstrap)
1031 {
1032 dboid = Template1DbOid;
1034 }
1035 else if (in_dbname != NULL)
1036 {
1037 HeapTuple tuple;
1039
1040 tuple = GetDatabaseTuple(in_dbname);
1041 if (!HeapTupleIsValid(tuple))
1042 ereport(FATAL,
1044 errmsg("database \"%s\" does not exist", in_dbname)));
1046 dboid = dbform->oid;
1047 }
1048 else if (!OidIsValid(dboid))
1049 {
1050 /*
1051 * If this is a background worker not bound to any particular
1052 * database, we're done now. Everything that follows only makes sense
1053 * if we are bound to a specific database. We do need to close the
1054 * transaction we started before returning.
1055 */
1056 if (!bootstrap)
1057 {
1060 }
1061 return;
1062 }
1063
1064 /*
1065 * Now, take a writer's lock on the database we are trying to connect to.
1066 * If there is a concurrently running DROP DATABASE on that database, this
1067 * will block us until it finishes (and has committed its update of
1068 * pg_database).
1069 *
1070 * Note that the lock is not held long, only until the end of this startup
1071 * transaction. This is OK since we will advertise our use of the
1072 * database in the ProcArray before dropping the lock (in fact, that's the
1073 * next thing to do). Anyone trying a DROP DATABASE after this point will
1074 * see us in the array once they have the lock. Ordering is important for
1075 * this because we don't want to advertise ourselves as being in this
1076 * database until we have the lock; otherwise we create what amounts to a
1077 * deadlock with CountOtherDBBackends().
1078 *
1079 * Note: use of RowExclusiveLock here is reasonable because we envision
1080 * our session as being a concurrent writer of the database. If we had a
1081 * way of declaring a session as being guaranteed-read-only, we could use
1082 * AccessShareLock for such sessions and thereby not conflict against
1083 * CREATE DATABASE.
1084 */
1085 if (!bootstrap)
1087
1088 /*
1089 * Recheck pg_database to make sure the target database hasn't gone away.
1090 * If there was a concurrent DROP DATABASE, this ensures we will die
1091 * cleanly without creating a mess.
1092 */
1093 if (!bootstrap)
1094 {
1095 HeapTuple tuple;
1097
1098 tuple = GetDatabaseTupleByOid(dboid);
1099 if (HeapTupleIsValid(tuple))
1101
1102 if (!HeapTupleIsValid(tuple) ||
1103 (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1104 {
1105 if (in_dbname)
1106 ereport(FATAL,
1108 errmsg("database \"%s\" does not exist", in_dbname),
1109 errdetail("It seems to have just been dropped or renamed.")));
1110 else
1111 ereport(FATAL,
1113 errmsg("database %u does not exist", dboid)));
1114 }
1115
1116 strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1117
1119 {
1120 ereport(FATAL,
1122 errmsg("cannot connect to invalid database \"%s\"", dbname),
1123 errhint("Use DROP DATABASE to drop invalid databases."));
1124 }
1125
1126 MyDatabaseTableSpace = datform->dattablespace;
1127 MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1128 /* pass the database name back to the caller */
1129 if (out_dbname)
1131 }
1132
1133 /*
1134 * Now that we rechecked, we are certain to be connected to a database and
1135 * thus can set MyDatabaseId.
1136 *
1137 * It is important that MyDatabaseId only be set once we are sure that the
1138 * target database can no longer be concurrently dropped or renamed. For
1139 * example, without this guarantee, pgstat_update_dbstats() could create
1140 * entries for databases that were just dropped in the pgstat shutdown
1141 * callback, which could confuse other code paths like the autovacuum
1142 * scheduler.
1143 */
1144 MyDatabaseId = dboid;
1145
1146 /*
1147 * Now we can mark our PGPROC entry with the database ID.
1148 *
1149 * We assume this is an atomic store so no lock is needed; though actually
1150 * things would work fine even if it weren't atomic. Anyone searching the
1151 * ProcArray for this database's ID should hold the database lock, so they
1152 * would not be executing concurrently with this store. A process looking
1153 * for another database's ID could in theory see a chance match if it read
1154 * a partially-updated databaseId value; but as long as all such searches
1155 * wait and retry, as in CountOtherDBBackends(), they will certainly see
1156 * the correct value on their next try.
1157 */
1159
1160 /*
1161 * We established a catalog snapshot while reading pg_authid and/or
1162 * pg_database; but until we have set up MyDatabaseId, we won't react to
1163 * incoming sinval messages for unshared catalogs, so we won't realize it
1164 * if the snapshot has been invalidated. Assume it's no good anymore.
1165 */
1167
1168 /*
1169 * Now we should be able to access the database directory safely. Verify
1170 * it's there and looks reasonable.
1171 */
1173
1174 if (!bootstrap)
1175 {
1176 if (access(fullpath, F_OK) == -1)
1177 {
1178 if (errno == ENOENT)
1179 ereport(FATAL,
1181 errmsg("database \"%s\" does not exist",
1182 dbname),
1183 errdetail("The database subdirectory \"%s\" is missing.",
1184 fullpath)));
1185 else
1186 ereport(FATAL,
1188 errmsg("could not access directory \"%s\": %m",
1189 fullpath)));
1190 }
1191
1192 ValidatePgVersion(fullpath);
1193 }
1194
1195 SetDatabasePath(fullpath);
1196 pfree(fullpath);
1197
1198 /*
1199 * It's now possible to do real access to the system catalogs.
1200 *
1201 * Load relcache entries for the system catalogs. This must create at
1202 * least the minimum set of "nailed-in" cache entries.
1203 */
1205
1206 /* set up ACL framework (so CheckMyDatabase can check permissions) */
1208
1209 /*
1210 * Re-read the pg_database row for our database, check permissions and set
1211 * up database-specific GUC settings. We can't do this until all the
1212 * database-access infrastructure is up. (Also, it wants to know if the
1213 * user is a superuser, so the above stuff has to happen first.)
1214 */
1215 if (!bootstrap)
1217 (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1218
1219 /*
1220 * Now process any command-line switches and any additional GUC variable
1221 * settings passed in the startup packet. We couldn't do this before
1222 * because we didn't know if client is a superuser.
1223 */
1224 if (MyProcPort != NULL)
1226
1227 /* Process pg_db_role_setting options */
1229
1230 /* Apply PostAuthDelay as soon as we've read all options */
1231 if (PostAuthDelay > 0)
1232 pg_usleep(PostAuthDelay * 1000000L);
1233
1234 /*
1235 * Initialize various default states that can't be set up until we've
1236 * selected the active user and gotten the right GUC settings.
1237 */
1238
1239 /* set default namespace search path */
1241
1242 /* initialize client encoding */
1244
1245 /* Initialize this backend's session state. */
1247
1248 /*
1249 * If this is an interactive session, load any libraries that should be
1250 * preloaded at backend start. Since those are determined by GUCs, this
1251 * can't happen until GUC settings are complete, but we want it to happen
1252 * during the initial transaction in case anything that requires database
1253 * access needs to be done.
1254 */
1255 if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1257
1258 /* fill in the remainder of this entry in the PgBackendStatus array */
1259 if (!bootstrap)
1261
1262 /* close the transaction we started above */
1263 if (!bootstrap)
1265
1266 /* send any WARNINGs we've accumulated during initialization */
1268}
void initialize_acl(void)
Definition acl.c:5069
bool has_privs_of_role(Oid member, Oid role)
Definition acl.c:5314
void pgstat_bestart_security(void)
void pgstat_bestart_initial(void)
void pgstat_beinit(void)
void pgstat_bestart_final(void)
bool database_is_invalid_form(Form_pg_database datform)
#define DEBUG3
Definition elog.h:29
#define WARNING
Definition elog.h:37
#define elog(elevel,...)
Definition elog.h:228
bool MyDatabaseHasLoginEventTriggers
Definition globals.c:100
int MyCancelKeyLength
Definition globals.c:55
bool IsBinaryUpgrade
Definition globals.c:123
Oid MyDatabaseTableSpace
Definition globals.c:98
uint8 MyCancelKey[MAX_CANCEL_KEY_LENGTH]
Definition globals.c:54
struct Port * MyProcPort
Definition globals.c:53
Oid MyDatabaseId
Definition globals.c:96
const char * hba_authname(UserAuth auth_method)
Definition hba.c:2948
#define INJECTION_POINT(name, arg)
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
#define RowExclusiveLock
Definition lockdefs.h:38
void InitializeClientEncoding(void)
Definition mbutils.c:290
#define INIT_PG_LOAD_SESSION_LIBS
Definition miscadmin.h:517
#define INIT_PG_OVERRIDE_ROLE_LOGIN
Definition miscadmin.h:519
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition miscadmin.h:518
void InitializeSessionUserId(const char *rolename, Oid roleid, bool bypass_login_check)
Definition miscinit.c:711
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition miscinit.c:876
void InitializeSessionUserIdStandalone(void)
Definition miscinit.c:841
void process_session_preload_libraries(void)
Definition miscinit.c:1867
Oid GetUserId(void)
Definition miscinit.c:470
Oid GetSessionUserId(void)
Definition miscinit.c:509
void SetDatabasePath(const char *path)
Definition miscinit.c:284
bool has_rolreplication(Oid roleid)
Definition miscinit.c:689
int namestrcmp(Name name, const char *str)
Definition name.c:247
void InitializeSearchPath(void)
Definition namespace.c:4808
#define NAMEDATALEN
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
void pgstat_before_server_shutdown(int code, Datum arg)
Definition pgstat.c:590
void InitPlanCache(void)
Definition plancache.c:148
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
void EnablePortalManager(void)
Definition portalmem.c:106
int PostAuthDelay
Definition postgres.c:105
static void ShutdownPostgres(int code, Datum arg)
Definition postinit.c:1374
static void IdleInTransactionSessionTimeoutHandler(void)
Definition postinit.c:1431
static void LockTimeoutHandler(void)
Definition postinit.c:1413
static void IdleStatsUpdateTimeoutHandler(void)
Definition postinit.c:1447
static void process_settings(Oid databaseid, Oid roleid)
Definition postinit.c:1340
static void IdleSessionTimeoutHandler(void)
Definition postinit.c:1439
static void process_startup_options(Port *port, bool am_superuser)
Definition postinit.c:1275
static void StatementTimeoutHandler(void)
Definition postinit.c:1391
static void EmitConnectionWarnings(void)
Definition postinit.c:1516
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition postinit.c:332
static bool ThereIsAtLeastOneRole(void)
Definition postinit.c:1466
static void PerformAuthentication(Port *port)
Definition postinit.c:203
static void ClientCheckTimeoutHandler(void)
Definition postinit.c:1455
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition postinit.c:114
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition postinit.c:157
static void TransactionTimeoutHandler(void)
Definition postinit.c:1423
int ReservedConnections
Definition postmaster.c:231
int SuperuserReservedConnections
Definition postmaster.c:230
short access
void ProcSignalInit(const uint8 *cancel_key, int cancel_key_len)
Definition procsignal.c:170
void RelationCacheInitializePhase3(void)
Definition relcache.c:4099
void RelationCacheInitialize(void)
Definition relcache.c:3994
void RelationCacheInitializePhase2(void)
Definition relcache.c:4040
char * GetDatabasePath(Oid dbOid, Oid spcOid)
Definition relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition resowner.c:1016
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
void CreateAuxProcessResourceOwner(void)
Definition resowner.c:996
void InitializeSession(void)
Definition session.c:54
void pg_usleep(long microsec)
Definition signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition sinvaladt.c:274
void InvalidateCatalogSnapshot(void)
Definition snapmgr.c:455
bool HaveNFreeProcs(int n, int *nfree)
Definition proc.c:787
void CheckDeadLockAlert(void)
Definition proc.c:1914
void InitProcessPhase2(void)
Definition proc.c:583
char * dbname
Definition streamutil.c:49
Oid databaseId
Definition proc.h:201
bool superuser(void)
Definition superuser.c:47
void InitCatalogCache(void)
Definition syscache.c:111
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition timeout.c:505
@ IDLE_SESSION_TIMEOUT
Definition timeout.h:35
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition timeout.h:33
@ LOCK_TIMEOUT
Definition timeout.h:28
@ STATEMENT_TIMEOUT
Definition timeout.h:29
@ DEADLOCK_TIMEOUT
Definition timeout.h:27
@ TRANSACTION_TIMEOUT
Definition timeout.h:34
@ IDLE_STATS_UPDATE_TIMEOUT
Definition timeout.h:36
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition timeout.h:37
bool am_walsender
Definition walsender.c:135
bool am_db_walsender
Definition walsender.c:138
void StartTransactionCommand(void)
Definition xact.c:3109
int XactIsoLevel
Definition xact.c:81
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916
void CommitTransactionCommand(void)
Definition xact.c:3207
#define XACT_READ_COMMITTED
Definition xact.h:37
void StartupXLOG(void)
Definition xlog.c:5846
void ShutdownXLOG(int code, Datum arg)
Definition xlog.c:7098
void InitLocalDataChecksumState(void)
Definition xlog.c:4961

References am_db_walsender, am_walsender, AmAutoVacuumLauncherProcess, AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmDataChecksumsWorkerProcess, AmLogicalSlotSyncWorkerProcess, AmRegularBackendProcess, Assert, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, before_shmem_exit(), CheckDeadLockAlert(), CheckMyDatabase(), CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler(), CommitTransactionCommand(), CreateAuxProcessResourceOwner(), CurrentResourceOwner, database_is_invalid_form(), PGPROC::databaseId, dbname, DEADLOCK_TIMEOUT, DEBUG3, elog, EmitConnectionWarnings(), EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg, FATAL, fb(), Form_pg_database, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT(), GetUserId(), has_privs_of_role(), has_rolreplication(), HaveNFreeProcs(), hba_authname(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), INIT_PG_LOAD_SESSION_LIBS, INIT_PG_OVERRIDE_ALLOW_CONNS, INIT_PG_OVERRIDE_ROLE_LOGIN, InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitializeSystemUser(), InitLocalDataChecksumState(), InitPlanCache(), InitProcessPhase2(), INJECTION_POINT, InvalidateCatalogSnapshot(), IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MyCancelKey, MyCancelKeyLength, MyClientConnectionInfo, MyDatabaseHasLoginEventTriggers, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, namestrcmp(), OidIsValid, PerformAuthentication(), pfree(), pg_usleep(), pgstat_before_server_shutdown(), pgstat_beinit(), pgstat_bestart_final(), pgstat_bestart_initial(), pgstat_bestart_security(), PostAuthDelay, process_session_preload_libraries(), process_settings(), process_startup_options(), ProcSignalInit(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedConnections, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), SuperuserReservedConnections, ThereIsAtLeastOneRole(), TRANSACTION_TIMEOUT, TransactionTimeoutHandler(), username, ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), BackgroundWorkerInitializeConnection(), BackgroundWorkerInitializeConnectionByOid(), BootstrapModeMain(), PostgresMain(), and ReplSlotSyncWorkerMain().

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )
extern

Definition at line 97 of file miscinit.c.

98{
99 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
100
101 /*
102 * Start our win32 signal implementation. This has to be done after we
103 * read the backend variables, because we need to pick up the signal pipe
104 * from the parent process.
105 */
106#ifdef WIN32
108#endif
109
111
112 /*
113 * make sure stderr is in binary mode before anything can possibly be
114 * written to it, in case it's actually the syslogger pipe, so the pipe
115 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
116 * redirection (e.g. via pg_ctl -l) anyway.
117 */
118#ifdef WIN32
119 _setmode(fileno(stderr), _O_BINARY);
120#endif
121
122 /* We don't want the postmaster's proc_exit() handlers */
124
125 /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
126#ifdef EXEC_BACKEND
127 pqinitmask();
128#endif
129
130 /* Initialize process-local latch support */
134
135 /*
136 * If possible, make this process a group leader, so that the postmaster
137 * can signal any child processes too. Not all processes will have
138 * children, but for consistency we make all postmaster child processes do
139 * this.
140 */
141#ifdef HAVE_SETSID
142 if (setsid() < 0)
143 elog(FATAL, "setsid() failed: %m");
144#endif
145
146 /*
147 * Every postmaster child process is expected to respond promptly to
148 * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
149 * BlockSig and install a suitable signal handler. (Client-facing
150 * processes may choose to replace this default choice of handler with
151 * quickdie().) All other blockable signals remain blocked for now.
152 */
154
157
158 /* Request a signal if the postmaster dies, if possible. */
160
161 /* Don't give the pipe to subprograms that we execute. */
162#ifndef WIN32
166 errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
167#endif
168}
void pqinitmask(void)
Definition pqsignal.c:41
sigset_t BlockSig
Definition pqsignal.c:23
int errcode_for_socket_access(void)
Definition elog.c:976
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition interrupt.c:73
void on_exit_reset(void)
Definition ipc.c:423
void InitializeLatchWaitSet(void)
Definition latch.c:35
void InitProcessLocalLatch(void)
Definition miscinit.c:236
void PostmasterDeathSignalInit(void)
Definition pmsignal.c:406
#define pqsignal
Definition port.h:547
void InitProcessGlobals(void)
int postmaster_alive_fds[2]
Definition postmaster.c:486
#define POSTMASTER_FD_WATCH
Definition postmaster.h:83
void pgwin32_signal_initialize(void)
Definition signal.c:79
void InitializeWaitEventSupport(void)
#define SIGQUIT
Definition win32_port.h:159

References BlockSig, elog, ereport, errcode_for_socket_access(), errmsg_internal(), FATAL, fb(), InitializeLatchWaitSet(), InitializeWaitEventSupport(), InitProcessGlobals(), InitProcessLocalLatch(), IsUnderPostmaster, on_exit_reset(), pgwin32_signal_initialize(), postmaster_alive_fds, POSTMASTER_FD_WATCH, PostmasterDeathSignalInit(), pqinitmask(), pqsignal, SignalHandlerForCrashExit(), and SIGQUIT.

Referenced by postmaster_child_launch().

◆ InitProcessLocalLatch()

void InitProcessLocalLatch ( void  )
extern

Definition at line 236 of file miscinit.c.

237{
240}
struct Latch * MyLatch
Definition globals.c:65
void InitLatch(Latch *latch)
Definition latch.c:63
static Latch LocalLatchData
Definition miscinit.c:70

References InitLatch(), LocalLatchData, and MyLatch.

Referenced by InitPostmasterChild(), InitStandaloneProcess(), and PostmasterMain().

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char argv0)
extern

Definition at line 176 of file miscinit.c.

177{
179
181
182 /*
183 * Start our win32 signal implementation
184 */
185#ifdef WIN32
187#endif
188
190
191 /* Initialize process-local latch support */
195
196 /*
197 * For consistency with InitPostmasterChild, initialize signal mask here.
198 * But we don't unblock SIGQUIT or provide a default handler for it.
199 */
200 pqinitmask();
202
203 /* Compute paths, no postmaster to inherit from */
204 if (my_exec_path[0] == '\0')
205 {
207 elog(FATAL, "%s: could not locate my own executable path",
208 argv0);
209 }
210
211 if (pkglib_path[0] == '\0')
213}
int find_my_exec(const char *argv0, char *retpath)
Definition exec.c:161
char pkglib_path[MAXPGPATH]
Definition globals.c:84
bool IsPostmasterEnvironment
Definition globals.c:121
char my_exec_path[MAXPGPATH]
Definition globals.c:83
BackendType MyBackendType
Definition miscinit.c:65
static char * argv0
Definition pg_ctl.c:94
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition path.c:956

References argv0, Assert, B_STANDALONE_BACKEND, BlockSig, elog, FATAL, fb(), find_my_exec(), get_pkglib_path(), InitializeLatchWaitSet(), InitializeWaitEventSupport(), InitProcessGlobals(), InitProcessLocalLatch(), IsPostmasterEnvironment, my_exec_path, MyBackendType, pgwin32_signal_initialize(), pkglib_path, and pqinitmask().

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )
extern

Definition at line 631 of file miscinit.c.

632{
634}
#define SECURITY_LOCAL_USERID_CHANGE
Definition miscadmin.h:330

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_with_handle().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )
extern

Definition at line 649 of file miscinit.c.

650{
652}
#define SECURITY_NOFORCE_RLS
Definition miscadmin.h:332

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )
extern

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char domain)
extern

Definition at line 1890 of file miscinit.c.

1891{
1892#ifdef ENABLE_NLS
1893 if (my_exec_path[0] != '\0')
1894 {
1895 char locale_path[MAXPGPATH];
1896
1898 bindtextdomain(domain, locale_path);
1900 }
1901#endif
1902}
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition path.c:965

References fb(), get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init(), and test_translation().

◆ pg_split_opts()

void pg_split_opts ( char **  argv,
int argcp,
const char optstr 
)
extern

Definition at line 501 of file postinit.c.

502{
504
505 initStringInfo(&s);
506
507 while (*optstr)
508 {
509 bool last_was_escape = false;
510
511 resetStringInfo(&s);
512
513 /* skip over leading space */
514 while (isspace((unsigned char) *optstr))
515 optstr++;
516
517 if (*optstr == '\0')
518 break;
519
520 /*
521 * Parse a single option, stopping at the first space, unless it's
522 * escaped.
523 */
524 while (*optstr)
525 {
526 if (isspace((unsigned char) *optstr) && !last_was_escape)
527 break;
528
529 if (!last_was_escape && *optstr == '\\')
530 last_was_escape = true;
531 else
532 {
533 last_was_escape = false;
535 }
536
537 optstr++;
538 }
539
540 /* now store the option in the next argv[] position */
541 argv[(*argcp)++] = pstrdup(s.data);
542 }
543
544 pfree(s.data);
545}
void resetStringInfo(StringInfo str)
Definition stringinfo.c:126
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97

References appendStringInfoChar(), StringInfoData::data, fb(), initStringInfo(), pfree(), pstrdup(), and resetStringInfo().

Referenced by process_startup_options().

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char cmdname)
extern

Definition at line 446 of file utility.c.

447{
448 if (RecoveryInProgress())
451 /* translator: %s is name of a SQL command, eg CREATE */
452 errmsg("cannot execute %s during recovery",
453 cmdname)));
454}
bool RecoveryInProgress(void)
Definition xlog.c:6830

References ereport, errcode(), errmsg, ERROR, fb(), and RecoveryInProgress().

Referenced by pg_current_xact_id(), pg_notify(), and standard_ProcessUtility().

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char cmdname)
extern

Definition at line 427 of file utility.c.

428{
429 if (IsInParallelMode())
432 /* translator: %s is name of a SQL command, eg CREATE */
433 errmsg("cannot execute %s during a parallel operation",
434 cmdname)));
435}
bool IsInParallelMode(void)
Definition xact.c:1119

References ereport, errcode(), errmsg, ERROR, fb(), and IsInParallelMode().

Referenced by ExecCheckXactReadOnly(), nextval_internal(), SetSequence(), and standard_ProcessUtility().

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char cmdname)
extern

Definition at line 409 of file utility.c.

410{
411 if (XactReadOnly)
414 /* translator: %s is name of a SQL command, eg CREATE */
415 errmsg("cannot execute %s in a read-only transaction",
416 cmdname)));
417}
bool XactReadOnly
Definition xact.c:84

References ereport, errcode(), errmsg, ERROR, fb(), and XactReadOnly.

Referenced by be_lo_creat(), be_lo_create(), be_lo_from_bytea(), be_lo_open(), be_lo_put(), be_lo_truncate(), be_lo_truncate64(), be_lo_unlink(), be_lowrite(), DoCopy(), ExecCheckXactReadOnly(), lo_import_internal(), nextval_internal(), SetSequence(), and standard_ProcessUtility().

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )
extern

Definition at line 1867 of file miscinit.c.

1868{
1870 "session_preload_libraries",
1871 false);
1873 "local_preload_libraries",
1874 true);
1875}
char * session_preload_libraries_string
Definition miscinit.c:1783
char * local_preload_libraries_string
Definition miscinit.c:1785
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition miscinit.c:1801

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by InitPostgres().

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )
extern

Definition at line 1853 of file miscinit.c.

1854{
1857 "shared_preload_libraries",
1858 false);
1861}
bool process_shared_preload_libraries_done
Definition miscinit.c:1789
char * shared_preload_libraries_string
Definition miscinit.c:1784
bool process_shared_preload_libraries_in_progress
Definition miscinit.c:1788

References load_libraries(), process_shared_preload_libraries_done, process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ process_shmem_requests()

void process_shmem_requests ( void  )
extern

Definition at line 1881 of file miscinit.c.

1882{
1887}
bool process_shmem_requests_in_progress
Definition miscinit.c:1792
shmem_request_hook_type shmem_request_hook
Definition miscinit.c:1791

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )
extern

Definition at line 3350 of file postgres.c.

3351{
3352 /* OK to accept any interrupts now? */
3353 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3354 return;
3355 InterruptPending = false;
3356
3357 if (ProcDiePending)
3358 {
3361
3362 ProcDiePending = false;
3363 ProcDieSenderPid = 0;
3364 ProcDieSenderUid = 0;
3365 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3367 /* As in quickdie, don't risk sending to client during auth */
3371 ereport(FATAL,
3373 errmsg("canceling authentication due to timeout")));
3374 else if (AmAutoVacuumWorkerProcess())
3375 ereport(FATAL,
3377 errmsg("terminating autovacuum process due to administrator command"),
3379 else if (IsLogicalWorker())
3380 ereport(FATAL,
3382 errmsg("terminating logical replication worker due to administrator command"),
3384 else if (IsLogicalLauncher())
3385 {
3387 (errmsg_internal("logical replication launcher shutting down"),
3389
3390 /*
3391 * The logical replication launcher can be stopped at any time.
3392 * Use exit status 1 so the background worker is restarted.
3393 */
3394 proc_exit(1);
3395 }
3396 else if (AmWalReceiverProcess())
3397 ereport(FATAL,
3399 errmsg("terminating walreceiver process due to administrator command"),
3401 else if (AmBackgroundWorkerProcess())
3402 ereport(FATAL,
3404 errmsg("terminating background worker \"%s\" due to administrator command",
3407 else if (AmIoWorkerProcess())
3408 {
3410 (errmsg_internal("io worker shutting down due to administrator command"),
3412
3413 proc_exit(0);
3414 }
3415 else
3416 ereport(FATAL,
3418 errmsg("terminating connection due to administrator command"),
3420 }
3421
3423 {
3425
3426 /*
3427 * Check for lost connection and re-arm, if still configured, but not
3428 * if we've arrived back at DoingCommandRead state. We don't want to
3429 * wake up idle sessions, and they already know how to detect lost
3430 * connections.
3431 */
3433 {
3434 if (!pq_check_connection())
3435 ClientConnectionLost = true;
3436 else
3439 }
3440 }
3441
3443 {
3444 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3446 /* don't send to client, we already know the connection to be dead. */
3448 ereport(FATAL,
3450 errmsg("connection to client lost")));
3451 }
3452
3453 /*
3454 * Don't allow query cancel interrupts while reading input from the
3455 * client, because we might lose sync in the FE/BE protocol. (Die
3456 * interrupts are OK, because we won't read any further messages from the
3457 * client in that case.)
3458 *
3459 * See similar logic in ProcessRecoveryConflictInterrupts().
3460 */
3462 {
3463 /*
3464 * Re-arm InterruptPending so that we process the cancel request as
3465 * soon as we're done reading the message. (XXX this is seriously
3466 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3467 * can't use that macro directly as the initial test in this function,
3468 * meaning that this code also creates opportunities for other bugs to
3469 * appear.)
3470 */
3471 InterruptPending = true;
3472 }
3473 else if (QueryCancelPending)
3474 {
3477
3478 QueryCancelPending = false;
3479
3480 /*
3481 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3482 * need to clear both, so always fetch both.
3483 */
3486
3487 /*
3488 * If both were set, we want to report whichever timeout completed
3489 * earlier; this ensures consistent behavior if the machine is slow
3490 * enough that the second timeout triggers before we get here. A tie
3491 * is arbitrarily broken in favor of reporting a lock timeout.
3492 */
3495 lock_timeout_occurred = false; /* report stmt timeout */
3496
3498 {
3500 ereport(ERROR,
3502 errmsg("canceling statement due to lock timeout")));
3503 }
3505 {
3507 ereport(ERROR,
3509 errmsg("canceling statement due to statement timeout")));
3510 }
3512 {
3514 ereport(ERROR,
3516 errmsg("canceling autovacuum task")));
3517 }
3518
3519 /*
3520 * If we are reading a command from the client, just ignore the cancel
3521 * request --- sending an extra error message won't accomplish
3522 * anything. Otherwise, go ahead and throw the error.
3523 */
3524 if (!DoingCommandRead)
3525 {
3527 ereport(ERROR,
3529 errmsg("canceling statement due to user request")));
3530 }
3531 }
3532
3535
3537 {
3538 /*
3539 * If the GUC has been reset to zero, ignore the signal. This is
3540 * important because the GUC update itself won't disable any pending
3541 * interrupt. We need to unset the flag before the injection point,
3542 * otherwise we could loop in interrupts checking.
3543 */
3546 {
3547 INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3548 ereport(FATAL,
3550 errmsg("terminating connection due to idle-in-transaction timeout")));
3551 }
3552 }
3553
3555 {
3556 /* As above, ignore the signal if the GUC has been reset to zero. */
3558 if (TransactionTimeout > 0)
3559 {
3560 INJECTION_POINT("transaction-timeout", NULL);
3561 ereport(FATAL,
3563 errmsg("terminating connection due to transaction timeout")));
3564 }
3565 }
3566
3568 {
3569 /* As above, ignore the signal if the GUC has been reset to zero. */
3571 if (IdleSessionTimeout > 0)
3572 {
3573 INJECTION_POINT("idle-session-timeout", NULL);
3574 ereport(FATAL,
3576 errmsg("terminating connection due to idle-session timeout")));
3577 }
3578 }
3579
3580 /*
3581 * If there are pending stats updates and we currently are truly idle
3582 * (matching the conditions in PostgresMain(), report stats now.
3583 */
3586 {
3588 pgstat_report_stat(true);
3589 }
3590
3593
3596
3599
3602
3605
3608}
volatile sig_atomic_t ParallelApplyMessagePending
void ProcessParallelApplyMessages(void)
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
void ProcessParallelMessages(void)
Definition parallel.c:1057
volatile sig_atomic_t ParallelMessagePending
Definition parallel.c:120
bool IsLogicalWorker(void)
Definition worker.c:6065
@ DestRemote
Definition dest.h:89
@ DestNone
Definition dest.h:87
#define DEBUG1
Definition elog.h:31
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition globals.c:42
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition globals.c:40
volatile sig_atomic_t InterruptPending
Definition globals.c:32
volatile sig_atomic_t IdleSessionTimeoutPending
Definition globals.c:39
volatile int ProcDieSenderPid
Definition globals.c:46
volatile uint32 QueryCancelHoldoffCount
Definition globals.c:44
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition globals.c:37
volatile uint32 InterruptHoldoffCount
Definition globals.c:43
volatile sig_atomic_t TransactionTimeoutPending
Definition globals.c:38
volatile int ProcDieSenderUid
Definition globals.c:47
volatile sig_atomic_t ClientConnectionLost
Definition globals.c:36
volatile uint32 CritSectionCount
Definition globals.c:45
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
volatile sig_atomic_t ProcDiePending
Definition globals.c:34
volatile sig_atomic_t CheckClientConnectionPending
Definition globals.c:35
void proc_exit(int code)
Definition ipc.c:105
bool IsLogicalLauncher(void)
Definition launcher.c:1587
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1340
#define AmWalReceiverProcess()
Definition miscadmin.h:406
#define AmIoWorkerProcess()
Definition miscadmin.h:409
long pgstat_report_stat(bool force)
Definition pgstat.c:722
int client_connection_check_interval
Definition postgres.c:108
CommandDest whereToSendOutput
Definition postgres.c:97
#define ERRDETAIL_SIGNAL_SENDER(pid, uid)
Definition postgres.c:117
static bool DoingCommandRead
Definition postgres.c:150
static void ProcessRecoveryConflictInterrupts(void)
Definition postgres.c:3299
bool ClientAuthInProgress
Definition postmaster.c:373
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:201
bool pq_check_connection(void)
Definition pqcomm.c:2057
void ProcessProcSignalBarrier(void)
Definition procsignal.c:503
volatile sig_atomic_t RepackMessagePending
Definition repack.c:146
void ProcessRepackMessages(void)
Definition repack.c:3515
void ProcessSlotSyncMessage(void)
Definition slotsync.c:1335
volatile sig_atomic_t SlotSyncShutdownPending
Definition slotsync.c:159
int IdleSessionTimeout
Definition proc.c:67
int IdleInTransactionSessionTimeout
Definition proc.c:65
int TransactionTimeout
Definition proc.c:66
void LockErrorCleanup(void)
Definition proc.c:818
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
pg_atomic_uint32 pendingRecoveryConflicts
Definition proc.h:270
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition timeout.c:560
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition timeout.c:827
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition timeout.c:793
bool IsTransactionOrTransactionBlock(void)
Definition xact.c:5040

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmIoWorkerProcess, AmWalReceiverProcess, BackgroundWorker::bgw_type, CheckClientConnectionPending, client_connection_check_interval, CLIENT_CONNECTION_CHECK_TIMEOUT, ClientAuthInProgress, ClientConnectionLost, CritSectionCount, DEBUG1, DestNone, DestRemote, DoingCommandRead, enable_timeout_after(), ereport, errcode(), ERRDETAIL_SIGNAL_SENDER, errmsg, errmsg_internal(), ERROR, FATAL, fb(), get_timeout_finish_time(), get_timeout_indicator(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, IdleStatsUpdateTimeoutPending, INJECTION_POINT, InterruptHoldoffCount, InterruptPending, IsLogicalLauncher(), IsLogicalWorker(), IsTransactionOrTransactionBlock(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, MyProc, ParallelApplyMessagePending, ParallelMessagePending, PGPROC::pendingRecoveryConflicts, pg_atomic_read_u32(), pgstat_report_stat(), pq_check_connection(), proc_exit(), ProcDiePending, ProcDieSenderPid, ProcDieSenderUid, ProcessLogMemoryContextInterrupt(), ProcessParallelApplyMessages(), ProcessParallelMessages(), ProcessProcSignalBarrier(), ProcessRecoveryConflictInterrupts(), ProcessRepackMessages(), ProcessSlotSyncMessage(), ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RepackMessagePending, SlotSyncShutdownPending, STATEMENT_TIMEOUT, TransactionTimeout, TransactionTimeoutPending, and whereToSendOutput.

Referenced by die().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )
extern

Definition at line 1648 of file miscinit.c.

1649{
1650 int fd;
1651 int len;
1652 long file_pid;
1653 char buffer[BLCKSZ];
1654
1656 if (fd < 0)
1657 {
1658 /*
1659 * There are many foreseeable false-positive error conditions. For
1660 * safety, fail only on enumerated clearly-something-is-wrong
1661 * conditions.
1662 */
1663 switch (errno)
1664 {
1665 case ENOENT:
1666 case ENOTDIR:
1667 /* disaster */
1668 ereport(LOG,
1670 errmsg("could not open file \"%s\": %m",
1672 return false;
1673 default:
1674 /* non-fatal, at least for now */
1675 ereport(LOG,
1677 errmsg("could not open file \"%s\": %m; continuing anyway",
1679 return true;
1680 }
1681 }
1683 len = read(fd, buffer, sizeof(buffer) - 1);
1685 if (len < 0)
1686 {
1687 ereport(LOG,
1689 errmsg("could not read from file \"%s\": %m",
1691 close(fd);
1692 return true; /* treat read failure as nonfatal */
1693 }
1694 buffer[len] = '\0';
1695 close(fd);
1696 file_pid = atol(buffer);
1697 if (file_pid == getpid())
1698 return true; /* all is well */
1699
1700 /* Trouble: someone's overwritten the lock file */
1701 ereport(LOG,
1702 (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1703 DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1704 return false;
1705}

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg, fb(), fd(), len, LOG, PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), and read.

Referenced by ServerLoop().

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)
extern

Definition at line 77 of file stack_depth.c.

78{
79 stack_base_ptr = base;
80}
static char * stack_base_ptr
Definition stack_depth.c:35

References stack_base_ptr.

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char conninfo)
extern

Definition at line 1086 of file miscinit.c.

1087{
1089
1090 memcpy(&serialized, conninfo, sizeof(serialized));
1091
1092 /* Copy the fields back into place */
1095
1096 if (serialized.authn_id_len >= 0)
1097 {
1098 char *authn_id;
1099
1100 authn_id = conninfo + sizeof(serialized);
1102 authn_id);
1103 }
1104}

References ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, authn_id, fb(), memcpy(), MemoryContextStrdup(), MyClientConnectionInfo, and TopMemoryContext.

Referenced by ParallelWorkerMain().

◆ SerializeClientConnectionInfo()

void SerializeClientConnectionInfo ( Size  maxsize,
char start_address 
)
extern

Definition at line 1053 of file miscinit.c.

1055{
1057
1060
1063
1064 /* Copy serialized representation to buffer */
1065 Assert(maxsize >= sizeof(serialized));
1067
1068 maxsize -= sizeof(serialized);
1069 start_address += sizeof(serialized);
1070
1071 /* Copy authn_id into the space after the struct */
1072 if (serialized.authn_id_len >= 0)
1073 {
1074 Assert(maxsize >= (serialized.authn_id_len + 1));
1077 /* include the NULL terminator to ease deserialization */
1078 serialized.authn_id_len + 1);
1079 }
1080}

References Assert, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, SerializedClientConnectionInfo::authn_id_len, fb(), memcpy(), and MyClientConnectionInfo.

Referenced by InitializeParallelDSM().

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )
extern

Definition at line 44 of file stack_depth.c.

45{
46#ifndef HAVE__BUILTIN_FRAME_ADDRESS
47 char stack_base;
48#endif
50
52
53 /*
54 * Set up reference point for stack depth checking. On recent gcc we use
55 * __builtin_frame_address() to avoid a warning about storing a local
56 * variable's address in a long-lived variable.
57 */
58#ifdef HAVE__BUILTIN_FRAME_ADDRESS
60#else
62#endif
63
64 return old;
65}
char * pg_stack_base_t
Definition miscadmin.h:302

References fb(), and stack_base_ptr.

Referenced by main().

◆ SetAuthenticatedUserId()

void SetAuthenticatedUserId ( Oid  userid)
extern

Definition at line 553 of file miscinit.c.

554{
555 Assert(OidIsValid(userid));
556
557 /* call only once */
559
560 AuthenticatedUserId = userid;
561
562 /* Also mark our PGPROC entry with the authenticated user id */
563 /* (We assume this is an atomic store so no lock is needed) */
564 MyProc->roleId = userid;
565}
Oid roleId
Definition proc.h:202

References Assert, AuthenticatedUserId, MyProc, OidIsValid, and PGPROC::roleId.

Referenced by InitializeSessionUserId(), and ParallelWorkerMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)
extern

Definition at line 958 of file miscinit.c.

959{
960 /*
961 * Get correct info if it's SET ROLE NONE
962 *
963 * If SessionUserId hasn't been set yet, do nothing beyond updating
964 * SetRoleIsActive --- the eventual SetSessionAuthorization call will
965 * update the derived state. This is needed since we will get called
966 * during GUC initialization.
967 */
968 if (!OidIsValid(roleid))
969 {
970 SetRoleIsActive = false;
971
973 return;
974
975 roleid = SessionUserId;
977 }
978 else
979 SetRoleIsActive = true;
980
982}
static void SetOuterUserId(Oid userid, bool is_superuser)
Definition miscinit.c:489

References is_superuser(), OidIsValid, SessionUserId, SessionUserIsSuperuser, SetOuterUserId(), and SetRoleIsActive.

Referenced by assign_role(), InitializeSessionUserIdStandalone(), and ParallelWorkerMain().

◆ SetDatabasePath()

void SetDatabasePath ( const char path)
extern

Definition at line 284 of file miscinit.c.

285{
286 /* This should happen only once per process */
289}
char * DatabasePath
Definition globals.c:106

References Assert, DatabasePath, MemoryContextStrdup(), and TopMemoryContext.

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char dir)
extern

Definition at line 390 of file miscinit.c.

391{
392 char *new;
393
394 Assert(dir);
395
396 /* If presented path is relative, convert to absolute */
397 new = make_absolute_path(dir);
398
399 free(DataDir);
400 DataDir = new;
401}
char * make_absolute_path(const char *path)
Definition path.c:807
#define free(a)

References Assert, DataDir, free, and make_absolute_path().

Referenced by SelectConfigFiles().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)
extern

Definition at line 922 of file miscinit.c.

923{
925
926 if (!SetRoleIsActive)
928}
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition miscinit.c:523

References is_superuser(), SetOuterUserId(), SetRoleIsActive, and SetSessionUserId().

Referenced by assign_session_authorization(), InitializeSessionUserIdStandalone(), and ParallelWorkerMain().

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)
extern

Definition at line 669 of file miscinit.c.

670{
671 /* We throw the same error SET ROLE would. */
675 errmsg("cannot set parameter \"%s\" within security-restricted operation",
676 "role")));
677 CurrentUserId = userid;
678 if (sec_def_context)
680 else
682}
bool InSecurityRestrictedOperation(void)
Definition miscinit.c:640

References CurrentUserId, ereport, errcode(), errmsg, ERROR, fb(), InSecurityRestrictedOperation(), SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

◆ SetUserIdAndSecContext()

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )
extern

Definition at line 109 of file stack_depth.c.

110{
111 char stack_top_loc;
113
114 /*
115 * Compute distance from reference point to my local variables
116 */
118
119 /*
120 * Take abs value, since stacks grow up on some machines, down on others
121 */
122 if (stack_depth < 0)
124
125 /*
126 * Trouble?
127 *
128 * The test on stack_base_ptr prevents us from erroring out if called
129 * before that's been set. Logically it should be done first, but putting
130 * it last avoids wasting cycles during normal cases.
131 */
134 return true;
135
136 return false;
137}
static ssize_t max_stack_depth_bytes
Definition stack_depth.c:29

References fb(), max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), IsSquashableConstant(), MemoryContextStatsInternal(), rstacktoodeep(), and ShowTransactionStateRec().

◆ StoreConnectionWarning()

void StoreConnectionWarning ( char msg,
char detail 
)
extern

Definition at line 1491 of file postinit.c.

1492{
1493 MemoryContext oldcontext;
1494
1495 Assert(msg);
1496 Assert(detail);
1497
1499 elog(ERROR, "StoreConnectionWarning() called after EmitConnectionWarnings()");
1500
1502
1505
1506 MemoryContextSwitchTo(oldcontext);
1507}
List * lappend(List *list, void *datum)
Definition list.c:339
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
static List * ConnectionWarningDetails
Definition postinit.c:79
static bool ConnectionWarningsEmitted
Definition postinit.c:75
static List * ConnectionWarningMessages
Definition postinit.c:78

References Assert, ConnectionWarningDetails, ConnectionWarningMessages, ConnectionWarningsEmitted, elog, ERROR, lappend(), MemoryContextSwitchTo(), and TopMemoryContext.

Referenced by get_role_password(), and md5_crypt_verify().

◆ superuser()

bool superuser ( void  )
extern

Definition at line 47 of file superuser.c.

48{
49 return superuser_arg(GetUserId());
50}

References GetUserId(), and superuser_arg().

Referenced by AlterForeignDataWrapper(), AlterForeignDataWrapperOwner_internal(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOpFamily(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterType(), AlterTypeOwner(), ATExecChangeOwner(), brin_metapage_info(), brin_page_items(), brin_page_type(), brin_revmap_data(), bt_metap(), bt_multi_page_stats(), bt_page_items_bytea(), bt_page_items_internal(), bt_page_stats_internal(), check_encoding_locale_matches(), CheckAlterPublication(), CreateAccessMethod(), CreateCast(), CreateEventTrigger(), CreateForeignDataWrapper(), CreateFunction(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateSubscription(), CreateTableSpace(), dblink_connstr_check(), dblink_security_check(), DefineAggregate(), DefineOpClass(), DefineOpFamily(), DefineTSParser(), DefineTSTemplate(), DefineType(), disable_data_checksums(), DropRole(), dummy_object_relabel(), enable_data_checksums(), EnableDisableTrigger(), ExecSetVariableStmt(), execute_extension_script(), ExecuteDoStmt(), fmgr_security_definer(), fsm_page_contents(), get_extension_location(), get_raw_page_internal(), gin_leafpage_items(), gin_metapage_info(), gin_page_opaque_info(), gist_page_items(), gist_page_items_bytea(), gist_page_opaque_info(), GUCArrayReset(), hash_bitmap_info(), hash_metapage_info(), hash_page_items(), hash_page_stats(), hash_page_type(), have_createdb_privilege(), heap_page_items(), heap_tuple_infomask_flags(), InitPostgres(), interpret_func_support(), main(), page_checksum_internal(), page_header(), pg_buffercache_superuser_check(), pg_import_system_collations(), pg_nextoid(), pg_relpages(), pg_relpagesbyid(), pg_signal_backend(), pg_stop_making_pinned_objects(), pgstat_get_backend_current_activity(), pgstatginindex(), pgstatindex(), pgstatindexbyid(), pgstattuple(), pgstattuple_approx(), pgstattuplebyid(), postgres_fdw_validator(), ProcedureCreate(), regress_setenv(), RenameRole(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), standard_ProcessUtility(), TerminateOtherDBBackends(), tuple_data_split(), validate_option_array_item(), ValidateJoinEstimator(), ValidateRestrictionEstimator(), and wait_pid().

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)
extern

Definition at line 57 of file superuser.c.

58{
59 bool result;
61
62 /* Quick out for cache hit */
63 if (OidIsValid(last_roleid) && last_roleid == roleid)
65
66 /* Special escape path in case you deleted all your users. */
68 return true;
69
70 /* OK, look up the information in pg_authid */
73 {
76 }
77 else
78 {
79 /* Report "not superuser" for invalid roleids */
80 result = false;
81 }
82
83 /* If first time through, set up callback for cache flushes */
85 {
88 (Datum) 0);
90 }
91
92 /* Cache the result for next time */
93 last_roleid = roleid;
95
96 return result;
97}
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1816
bool rolsuper
Definition pg_authid.h:37
uint64_t Datum
Definition postgres.h:70
static Oid last_roleid
Definition superuser.c:35
static bool roleid_callback_registered
Definition superuser.c:37
static void RoleidCallback(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
Definition superuser.c:104
static bool last_roleid_is_super
Definition superuser.c:36

References CacheRegisterSyscacheCallback(), fb(), Form_pg_authid, GETSTRUCT(), HeapTupleIsValid, IsUnderPostmaster, last_roleid, last_roleid_is_super, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), result, roleid_callback_registered, RoleidCallback(), rolsuper, and SearchSysCache1().

Referenced by AlterEventTriggerOwner_internal(), AlterForeignDataWrapperOwner_internal(), AlterPublicationOwner_internal(), check_conn_params(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), check_session_authorization(), CreateRole(), CreateSubscription(), DropSubscription(), emit_audit_message(), GetSubscription(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), has_rolreplication(), is_admin_of_role(), is_member_of_role(), LockGXact(), member_can_set_role(), object_aclmask_ext(), object_ownercheck(), pg_class_aclmask_ext(), pg_largeobject_aclmask_snapshot(), pg_namespace_aclmask_ext(), pg_parameter_acl_aclmask(), pg_parameter_aclmask(), pg_signal_backend(), pg_type_aclmask_ext(), pgfdw_security_check(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), select_best_grantor(), superuser(), and TerminateOtherDBBackends().

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )
extern

Definition at line 243 of file miscinit.c.

244{
247
249
250 if (FeBeWaitSet)
252 MyLatch);
253
255}
void SetLatch(Latch *latch)
Definition latch.c:290
#define FeBeWaitSetLatchPos
Definition libpq.h:67
WaitEventSet * FeBeWaitSet
Definition pqcomm.c:167
Latch procLatch
Definition proc.h:256
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
#define WL_LATCH_SET

References Assert, fb(), FeBeWaitSet, FeBeWaitSetLatchPos, LocalLatchData, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by AuxiliaryProcKill(), and ProcKill().

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )
extern

Definition at line 216 of file miscinit.c.

217{
219 Assert(MyProc != NULL);
220
222
223 if (FeBeWaitSet)
225 MyLatch);
226
227 /*
228 * Set the shared latch as the local one might have been set. This
229 * shouldn't normally be necessary as code is supposed to check the
230 * condition before waiting for the latch, but a bit care can't hurt.
231 */
233}

References Assert, fb(), FeBeWaitSet, FeBeWaitSetLatchPos, LocalLatchData, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )
extern

Definition at line 1492 of file miscinit.c.

1493{
1494 ListCell *l;
1495
1496 foreach(l, lock_files)
1497 {
1498 char *socketLockFile = (char *) lfirst(l);
1499
1500 /* No need to touch the data directory lock file, we trust */
1502 continue;
1503
1504 /* we just ignore any error here */
1506 }
1507}
static List * lock_files
Definition miscinit.c:68
#define lfirst(lc)
Definition pg_list.h:172

References DIRECTORY_LOCK_FILE, fb(), lfirst, and lock_files.

Referenced by ServerLoop().

◆ ValidatePgVersion()

void ValidatePgVersion ( const char path)
extern

Definition at line 1720 of file miscinit.c.

1721{
1722 char full_path[MAXPGPATH];
1723 FILE *file;
1724 int ret;
1725 long file_major;
1726 long my_major;
1727 char *endptr;
1728 char file_version_string[64];
1729 const char *my_version_string = PG_VERSION;
1730
1731 my_major = strtol(my_version_string, &endptr, 10);
1732
1733 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1734
1735 file = AllocateFile(full_path, "r");
1736 if (!file)
1737 {
1738 if (errno == ENOENT)
1739 ereport(FATAL,
1741 errmsg("\"%s\" is not a valid data directory",
1742 path),
1743 errdetail("File \"%s\" is missing.", full_path)));
1744 else
1745 ereport(FATAL,
1747 errmsg("could not open file \"%s\": %m", full_path)));
1748 }
1749
1750 file_version_string[0] = '\0';
1751 ret = fscanf(file, "%63s", file_version_string);
1752 file_major = strtol(file_version_string, &endptr, 10);
1753
1754 if (ret != 1 || endptr == file_version_string)
1755 ereport(FATAL,
1757 errmsg("\"%s\" is not a valid data directory",
1758 path),
1759 errdetail("File \"%s\" does not contain valid data.",
1760 full_path),
1761 errhint("You might need to initdb.")));
1762
1763 FreeFile(file);
1764
1765 if (my_major != file_major)
1766 ereport(FATAL,
1768 errmsg("database files are incompatible with server"),
1769 errdetail("The data directory was initialized by PostgreSQL version %s, "
1770 "which is not compatible with this version %s.",
1772}
int FreeFile(FILE *file)
Definition fd.c:2827
FILE * AllocateFile(const char *name, const char *mode)
Definition fd.c:2628

References AllocateFile(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg, FATAL, fb(), FreeFile(), MAXPGPATH, and snprintf.

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ accessSharedCatalogsInDecoding

PGDLLIMPORT bool accessSharedCatalogsInDecoding
extern

◆ allowSystemTableMods

◆ autovacuum_max_parallel_workers

PGDLLIMPORT int autovacuum_max_parallel_workers
extern

Definition at line 148 of file globals.c.

Referenced by parallel_vacuum_compute_workers().

◆ CheckClientConnectionPending

PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
extern

Definition at line 35 of file globals.c.

Referenced by ClientCheckTimeoutHandler(), and ProcessInterrupts().

◆ ClientConnectionLost

PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
extern

Definition at line 36 of file globals.c.

Referenced by internal_flush_buffer(), and ProcessInterrupts().

◆ commit_timestamp_buffers

PGDLLIMPORT int commit_timestamp_buffers
extern

Definition at line 164 of file globals.c.

Referenced by CommitTsShmemBuffers(), and CommitTsShmemRequest().

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode
extern

Definition at line 79 of file globals.c.

Referenced by checkDataDir(), RetrieveDataDirCreatePerm(), and show_data_directory_mode().

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder
extern

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError
extern

◆ hash_mem_multiplier

PGDLLIMPORT double hash_mem_multiplier
extern

Definition at line 134 of file globals.c.

Referenced by get_hash_memory_limit().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
extern

Definition at line 37 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
extern

Definition at line 39 of file globals.c.

Referenced by IdleSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleStatsUpdateTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
extern

Definition at line 42 of file globals.c.

Referenced by IdleStatsUpdateTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

◆ InterruptHoldoffCount

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle
extern

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster
extern

Definition at line 122 of file globals.c.

Referenced by _PG_init(), AdvanceNextFullTransactionIdPastXid(), AuxiliaryProcessMainCommon(), bootstrap_signals(), BootstrapModeMain(), CheckMyDatabase(), CheckRecoveryConsistency(), createdb(), CreateRestartPoint(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), dsm_attach(), dsm_backend_startup(), dsm_create(), dsm_impl_pin_segment(), dsm_impl_posix_resize(), dsm_impl_unpin_segment(), dsm_postmaster_startup(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerOnLogin(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForwardSyncRequest(), get_slru_entry(), GetNewMultiXactId(), GetNewTransactionId(), GetQuitSignalReason(), init_ps_display(), InitAuxiliaryProcess(), InitializeLatchWaitSet(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitializeWaitEventSupport(), InitPostgres(), InitPostmasterChild(), InitProcess(), InitShmemAllocator(), InitSync(), LockBufferInternal(), LWLockAcquire(), LWLockShmemRequest(), MaintainLatestCompletedXidRecovery(), parallel_vacuum_compute_workers(), PerformRecoveryXLogAction(), PerformWalRecovery(), pg_get_shmem_pagesize(), pgaio_io_wait(), pgaio_worker_needs_synchronous_execution(), PGSemaphoreCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_init(), pgstat_fetch_entry(), pgstat_read_statsfile(), pgstat_report_autovac(), pgstat_report_recovery_conflict(), pgstat_shutdown_hook(), pgstat_wal_flush_cb(), pgstat_write_statsfile(), plan_create_index_workers(), PostgresMain(), PostgresSingleUserMain(), postmaster_child_launch(), process_postgres_switches(), process_settings(), ProcessConfigFile(), ProcessConfigFileInternal(), ProcessStartupProcInterrupts(), ProcGlobalShmemRequest(), ReadRecord(), readRecoverySignalFile(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), RegisterShmemCallbacks(), ReplicationSlotAcquire(), ResetShmemAllocator(), SendPostmasterSignal(), set_config_sourcefile(), set_config_with_handle(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitRequested(), ShmemInitStruct(), ShmemRequestInternal(), standard_planner(), start_xact_command(), superuser_arg(), UpdateLogicalDecodingStatusEndOfRecovery(), vacuum_delay_point(), verify_dictoptions(), WaitLatch(), WaitLatchOrSocket(), XLogArchiveNotify(), XLogPageRead(), XLogPrefetchIncrement(), XLogRecGetFullXid(), XLogShutdownWalRcv(), and XLogWrite().

◆ local_preload_libraries_string

PGDLLIMPORT char* local_preload_libraries_string
extern

Definition at line 1785 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LogMemoryContextPending

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers
extern

Definition at line 136 of file globals.c.

Referenced by parallel_vacuum_compute_workers(), and plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers
extern

Definition at line 147 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_stack_depth

PGDLLIMPORT int max_stack_depth
extern

Definition at line 26 of file stack_depth.c.

Referenced by check_stack_depth().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 63 of file miscinit.c.

◆ multixact_member_buffers

PGDLLIMPORT int multixact_member_buffers
extern

Definition at line 165 of file globals.c.

Referenced by MultiXactShmemRequest().

◆ multixact_offset_buffers

PGDLLIMPORT int multixact_offset_buffers
extern

Definition at line 166 of file globals.c.

Referenced by MultiXactShmemRequest().

◆ my_exec_path

◆ MyBackendType

◆ MyCancelKey

PGDLLIMPORT uint8 MyCancelKey[]
extern

Definition at line 54 of file globals.c.

Referenced by InitPostgres(), and PostgresMain().

◆ MyCancelKeyLength

PGDLLIMPORT int MyCancelKeyLength
extern

Definition at line 55 of file globals.c.

Referenced by InitPostgres(), and PostgresMain().

◆ MyDatabaseHasLoginEventTriggers

PGDLLIMPORT bool MyDatabaseHasLoginEventTriggers
extern

Definition at line 100 of file globals.c.

Referenced by EventTriggerOnLogin(), and InitPostgres().

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId
extern

Definition at line 96 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner(), AlterSubscriptionOwner_internal(), ApplyPendingListenActions(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), ATExecDetachPartition(), AutoVacuumRequestWork(), BecomeRegisteredListener(), CacheInvalidateCatalog(), CacheInvalidateHeapTupleCommon(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), CacheInvalidateRelSync(), check_default_table_access_method(), check_default_tablespace(), check_default_text_search_config(), check_temp_tablespaces(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), checkTempNamespaceStatus(), classIdGetDbId(), CleanupListenersOnExit(), ComputeXidHorizons(), ConditionalLockDatabaseObject(), create_pg_locale_builtin(), create_pg_locale_icu(), create_pg_locale_libc(), CreateDecodingContext(), CreateInitDecodingContext(), CreatePublication(), CreateSchemaCommand(), CreateSubscription(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), DropSubscription(), EventTriggerOnLogin(), exec_object_restorecon(), exec_replication_command(), ExecuteTruncateGuts(), ExpandColumnRefStar(), ExportSnapshot(), extension_is_trusted(), find_funcstat_entry(), find_tabstat_entry(), get_subscription_oid(), GetCurrentVirtualXIDs(), GetNewRelFileNumber(), GetOldestActiveTransactionId(), GetRunningTransactionData(), heap_inplace_update_and_unlock(), heap_vacuum_rel(), IdentifySystem(), ImportSnapshot(), init_database_collation(), initialize_acl(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), InitWalSender(), InitWalSenderSlot(), libpqrcv_exec(), LocalExecuteInvalidationMessage(), LockApplyTransactionForSession(), LockDatabaseFrozenIds(), LockDatabaseObject(), LockGXact(), logical_heap_rewrite_flush_mappings(), logical_rewrite_log_mapping(), LogLogicalMessage(), LogStandbyInvalidations(), map_sql_catalog_to_xmlschema_types(), map_sql_schema_to_xmlschema_types(), map_sql_table_to_xmlschema(), map_sql_type_to_xml_name(), match_db_entries(), movedb(), perform_relmap_update(), perform_work_item(), pg_collation_actual_version(), pg_namespace_aclmask_ext(), pg_relation_filepath(), pg_stat_reset_single_function_counters(), pg_stat_reset_single_table_counters(), pgss_store(), pgstat_bestart_final(), pgstat_build_snapshot(), pgstat_copy_relation_stats(), pgstat_create_function(), pgstat_create_relation(), pgstat_drop_function(), pgstat_drop_relation(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry_ext(), pgstat_init_function_usage(), pgstat_prep_database_pending(), pgstat_prep_relation_pending(), pgstat_report_analyze(), pgstat_report_deadlock(), pgstat_report_recovery_conflict(), pgstat_report_tempfile(), pgstat_report_vacuum(), pgstat_reset_counters(), pgstat_shutdown_hook(), pgstat_update_dbstats(), pgstat_update_parallel_workers_stats(), PostgresMain(), PrepareTableEntriesForListen(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), RangeVarCallbackForStats(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), read_stream_begin_impl(), ReindexMultipleTables(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationMapFinishBootstrap(), RenameDatabase(), RenameSchema(), ReplicationSlotCreate(), roles_is_member_of(), ScanPgRelation(), SearchSysCacheLocked1(), sepgsql_schema_post_create(), SetDatabaseHasLoginEventTriggers(), SetLocktagRelationOid(), shdepDropOwned(), shdepReassignOwned(), SignalBackends(), SnapBuildProcessRunningXacts(), start_repack_decoding_worker(), transformColumnRef(), TwoPhaseGetOldestXidInCommit(), UnlockApplyTransactionForSession(), UnlockDatabaseObject(), UpdateLogicalMappings(), vac_truncate_clog(), vac_update_datfrozenxid(), vacuum_is_permitted_for_relation(), XactLogAbortRecord(), and XactLogCommitRecord().

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch
extern

Definition at line 65 of file globals.c.

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), avl_sigusr2_handler(), BackgroundWriterMain(), CheckDeadLockAlert(), CheckpointerMain(), CheckpointWriteDelay(), ClientCheckTimeoutHandler(), ConditionVariableTimedSleep(), ConfigurePostmasterWaitSet(), copy_read_data(), DataChecksumsWorkerMain(), dc_delay_barrier(), die(), do_pg_backup_stop(), ExecAppendAsyncEventWait(), gather_readnext(), handle_pm_child_exit_signal(), handle_pm_pmsignal_signal(), handle_pm_reload_request_signal(), handle_pm_shutdown_request_signal(), handle_sig_alarm(), HandleRepackMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), InitializeLatchWaitSet(), InitProcessLocalLatch(), IoWorkerMain(), launcher_cancel_handler(), lazy_truncate_heap(), libpqsrv_cancel(), libpqsrv_connect_internal(), libpqsrv_get_result(), LogicalParallelApplyLoop(), logicalrep_worker_stop_internal(), LogicalRepApplyLoop(), mq_putmessage(), pa_send_data(), pa_wait_for_xact_state(), pg_promote(), pg_sleep(), pg_stash_advice_worker_main(), pg_wait_until_termination(), pgarch_MainLoop(), pgarch_waken_stop(), pgfdw_get_cleanup_result(), pq_check_connection(), pq_init(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessPendingWrites(), procsignal_sigusr1_handler(), ProcSleep(), ProcWaitForSignal(), ReqShutdownXLOG(), secure_read(), secure_write(), ServerLoop(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), ShutDownSlotSync(), SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), sigUsr1Handler(), StatementCancelHandler(), summarizer_wait_for_wal(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), TransactionTimeoutHandler(), wait_for_slot_activity(), wait_for_table_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForAllTransactionsToFinish(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForLSN(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLastCycleHandler(), WalSndLoop(), WalSndWaitForWal(), WalWriterMain(), and worker_spi_main().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid
extern

Definition at line 49 of file globals.c.

Referenced by AddWaitEventToSet(), ApplyLauncherMain(), apw_detach_shmem(), apw_dump_now(), apw_load_buffers(), apw_start_database_worker(), apw_start_leader_worker(), Async_Listen(), Async_Unlisten(), Async_UnlistenAll(), asyncQueueNotificationToEntry(), asyncQueueReadAllNotifications(), ATExecMergePartitions(), ATExecSplitPartition(), autoprewarm_main(), AutoVacLauncherMain(), basic_archive_file(), BecomeRegisteredListener(), CheckpointerMain(), CleanupListenersOnExit(), CleanupProcSignalState(), DisownLatch(), ExportSnapshot(), FileSetInit(), fork_process(), get_backend_type_for_log(), GetSerializableTransactionSnapshotInt(), HandleWalSndInitStopping(), InitAuxiliaryProcess(), initialize_prng(), InitializeParallelDSM(), InitializeWaitEventSupport(), InitLatch(), InitPostmasterDeathWatchHandle(), InitProcess(), InitProcessGlobals(), InitWalSenderSlot(), injection_point_allowed(), injection_points_attach(), IsLogicalLauncher(), LaunchParallelWorkers(), llvm_compile_module(), LockAcquireExtended(), LockTimeoutHandler(), log_status_format(), logicalrep_worker_launch(), main(), ModifyWaitEvent(), OpenTemporaryFileInTablespace(), OwnLatch(), pg_backend_pid(), pg_stash_advice_worker_main(), pgsa_detach_shmem(), pgsa_start_worker(), pgstat_bestart_initial(), PostgresMain(), PostmasterMain(), proc_exit(), process_pgfdw_appname(), ProcessDatabase(), ProcessLogMemoryContextInterrupt(), ProcSignalInit(), ProcSleep(), repack_setup_logical_decoding(), replorigin_session_reset(), replorigin_session_reset_internal(), replorigin_session_setup(), ReplSlotSyncWorkerMain(), ResetLatch(), ServerLoop(), SetLatch(), setup_background_workers(), SharedInvalBackendInit(), SignalBackends(), SnapBuildSerialize(), start_repack_decoding_worker(), StartDataChecksumsWorkerLauncher(), StatementTimeoutHandler(), SyncReplicationSlots(), WakeupMyProc(), WalRcvDie(), WalReceiverMain(), worker_spi_launch(), write_csvlog(), write_jsonlog(), write_pipe_chunks(), and write_relcache_init_file().

◆ MyProcPort

◆ MyStartTime

◆ MyStartTimestamp

PGDLLIMPORT TimestampTz MyStartTimestamp
extern

◆ NBuffers

PGDLLIMPORT int NBuffers
extern

Definition at line 144 of file globals.c.

◆ notify_buffers

PGDLLIMPORT int notify_buffers
extern

Definition at line 167 of file globals.c.

Referenced by AsyncShmemRequest().

◆ OutputFileName

PGDLLIMPORT char OutputFileName[]
extern

Definition at line 81 of file globals.c.

Referenced by BootstrapModeMain(), DebugFileOpen(), and process_postgres_switches().

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ ProcDieSenderPid

PGDLLIMPORT volatile int ProcDieSenderPid
extern

Definition at line 46 of file globals.c.

Referenced by ProcessInterrupts(), and SyncRepWaitForLSN().

◆ ProcDieSenderUid

PGDLLIMPORT volatile int ProcDieSenderUid
extern

Definition at line 47 of file globals.c.

Referenced by ProcessInterrupts(), and SyncRepWaitForLSN().

◆ process_shared_preload_libraries_done

PGDLLIMPORT bool process_shared_preload_libraries_done
extern

◆ process_shared_preload_libraries_in_progress

◆ process_shmem_requests_in_progress

PGDLLIMPORT bool process_shmem_requests_in_progress
extern

◆ ProcSignalBarrierPending

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
extern

Definition at line 44 of file globals.c.

Referenced by errfinish(), ProcessInterrupts(), and report_recovery_conflict().

◆ QueryCancelPending

◆ serializable_buffers

PGDLLIMPORT int serializable_buffers
extern

Definition at line 168 of file globals.c.

Referenced by PredicateLockShmemRequest().

◆ session_preload_libraries_string

PGDLLIMPORT char* session_preload_libraries_string
extern

Definition at line 1783 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

PGDLLIMPORT char* shared_preload_libraries_string
extern

Definition at line 1784 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

PGDLLIMPORT shmem_request_hook_type shmem_request_hook
extern

Definition at line 1791 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ subtransaction_buffers

PGDLLIMPORT int subtransaction_buffers
extern

Definition at line 169 of file globals.c.

Referenced by SUBTRANSShmemBuffers(), and SUBTRANSShmemRequest().

◆ transaction_buffers

PGDLLIMPORT int transaction_buffers
extern

Definition at line 170 of file globals.c.

Referenced by CLOGShmemBuffers(), and CLOGShmemRequest().

◆ TransactionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t TransactionTimeoutPending
extern

Definition at line 38 of file globals.c.

Referenced by ProcessInterrupts(), and TransactionTimeoutHandler().

◆ VacuumBufferUsageLimit

PGDLLIMPORT int VacuumBufferUsageLimit
extern

Definition at line 152 of file globals.c.

Referenced by do_autovacuum(), and ExecVacuum().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

PGDLLIMPORT double VacuumCostDelay
extern

◆ VacuumCostLimit

◆ VacuumCostPageDirty

◆ VacuumCostPageHit

◆ VacuumCostPageMiss

◆ work_mem