PostgreSQL Source Code  git master
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 SECURITY_LOCAL_USERID_CHANGE   0x0001
 
#define SECURITY_RESTRICTED_OPERATION   0x0002
 
#define SECURITY_NOFORCE_RLS   0x0004
 
#define IsBootstrapProcessingMode()   (Mode == BootstrapProcessing)
 
#define IsInitProcessingMode()   (Mode == InitProcessing)
 
#define IsNormalProcessingMode()   (Mode == NormalProcessing)
 
#define GetProcessingMode()   Mode
 
#define SetProcessingMode(mode)
 
#define AmStartupProcess()   (MyAuxProcType == StartupProcess)
 
#define AmBackgroundWriterProcess()   (MyAuxProcType == BgWriterProcess)
 
#define AmArchiverProcess()   (MyAuxProcType == ArchiverProcess)
 
#define AmCheckpointerProcess()   (MyAuxProcType == CheckpointerProcess)
 
#define AmWalWriterProcess()   (MyAuxProcType == WalWriterProcess)
 
#define AmWalReceiverProcess()   (MyAuxProcType == WalReceiverProcess)
 

Typedefs

typedef char * pg_stack_base_t
 
typedef enum BackendType BackendType
 
typedef enum ProcessingMode ProcessingMode
 

Enumerations

enum  BackendType {
  B_INVALID = 0, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND,
  B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_STARTUP,
  B_WAL_RECEIVER, B_WAL_SENDER, B_WAL_WRITER, B_ARCHIVER,
  B_STATS_COLLECTOR, B_LOGGER
}
 
enum  ProcessingMode { BootstrapProcessing, InitProcessing, NormalProcessing }
 
enum  AuxProcType {
  NotAnAuxProcess = -1, StartupProcess = 0, BgWriterProcess, ArchiverProcess,
  CheckpointerProcess, WalWriterProcess, WalReceiverProcess, NUM_AUXPROCTYPES
}
 

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)
 
void PreventCommandIfReadOnly (const char *cmdname)
 
void PreventCommandIfParallelMode (const char *cmdname)
 
void PreventCommandDuringRecovery (const char *cmdname)
 
int trace_recovery (int trace_level)
 
void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
const char * GetBackendTypeDesc (BackendType backendType)
 
void SetDatabasePath (const char *path)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
Oid GetSessionUserId (void)
 
Oid GetAuthenticatedUserId (void)
 
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 useroid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
bool superuser (void)
 
bool superuser_arg (Oid roleid)
 
void pg_split_opts (char **argv, int *argcp, const char *optstr)
 
void InitializeMaxBackends (void)
 
void InitPostgres (const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
 
void BaseInit (void)
 
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 pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
bool BackupInProgress (void)
 
void CancelBackup (void)
 
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 sig_atomic_t IdleInTransactionSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t ProcSignalBarrierPending
 
PGDLLIMPORT volatile sig_atomic_t LogMemoryContextPending
 
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 IsBackgroundWorker
 
PGDLLIMPORT bool IsBinaryUpgrade
 
PGDLLIMPORT bool ExitOnAnyError
 
PGDLLIMPORT char * DataDir
 
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 MyProcPid
 
PGDLLIMPORT pg_time_t MyStartTime
 
PGDLLIMPORT TimestampTz MyStartTimestamp
 
PGDLLIMPORT struct PortMyProcPort
 
PGDLLIMPORT struct LatchMyLatch
 
int32 MyCancelKey
 
int MyPMChildSlot
 
char OutputFileName []
 
PGDLLIMPORT char my_exec_path []
 
char pkglib_path []
 
PGDLLIMPORT Oid MyDatabaseId
 
PGDLLIMPORT Oid MyDatabaseTableSpace
 
PGDLLIMPORT int DateStyle
 
PGDLLIMPORT int DateOrder
 
PGDLLIMPORT int IntervalStyle
 
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
 
int VacuumCostPageHit
 
int VacuumCostPageMiss
 
int VacuumCostPageDirty
 
int VacuumCostLimit
 
double VacuumCostDelay
 
int64 VacuumPageHit
 
int64 VacuumPageMiss
 
int64 VacuumPageDirty
 
int VacuumCostBalance
 
bool VacuumCostActive
 
int trace_recovery_messages
 
char * DatabasePath
 
BackendType MyBackendType
 
ProcessingMode Mode
 
AuxProcType MyAuxProcType
 
bool IgnoreSystemIndexes
 
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
 
char * session_preload_libraries_string
 
char * shared_preload_libraries_string
 
char * local_preload_libraries_string
 

Macro Definition Documentation

◆ AmArchiverProcess

#define AmArchiverProcess ( )    (MyAuxProcType == ArchiverProcess)

Definition at line 446 of file miscadmin.h.

◆ AmBackgroundWriterProcess

#define AmBackgroundWriterProcess ( )    (MyAuxProcType == BgWriterProcess)

Definition at line 445 of file miscadmin.h.

Referenced by ForwardSyncRequest().

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

◆ AmStartupProcess

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 449 of file miscadmin.h.

Referenced by get_sync_bit().

◆ AmWalWriterProcess

#define AmWalWriterProcess ( )    (MyAuxProcType == WalWriterProcess)

Definition at line 448 of file miscadmin.h.

◆ CHECK_FOR_INTERRUPTS

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

Definition at line 120 of file miscadmin.h.

Referenced by _bt_buildadd(), _bt_pagedel(), _bt_readnextpage(), _bt_unlink_halfdead_page(), _bt_walk_left(), _crypt_blowfish_rn(), _hash_init(), _hash_readnext(), _hash_readprev(), add_partial_path(), add_path(), agg_refill_hash_table(), agg_retrieve_hash_table_in_memory(), analyze_rel(), apply_spooled_messages(), ApplyLauncherMain(), apw_dump_now(), ATRewriteTable(), autoprewarm_database_main(), backend_read_statsfile(), BipartiteMatch(), BitmapHeapNext(), blgetbitmap(), bloomBuildCallback(), brin_evacuate_page(), brin_getinsertbuffer(), brin_vacuum_scan(), bringetbitmap(), brinGetTupleForHeapBlock(), brininsert(), brinsummarize(), bt_check_level_from_leftmost(), bt_downlink_missing_check(), bt_right_page_check_scankey(), bt_target_page_check(), BufFileDeleteFileSet(), BufFileOpenFileSet(), calculate_database_size(), calculate_relation_size(), calculate_tablespace_size(), check_default_partition_contents(), checkCond(), CheckMD5Auth(), ClientAuthentication(), cluster_rel(), collect_corrupt_items(), collect_visibility_data(), ConditionVariableTimedSleep(), copy_file(), copy_messages(), copy_read_data(), copydir(), CopyFrom(), count_nondeletable_pages(), CountOtherDBBackends(), db_dir_size(), DecodingContextFindStartpoint(), do_autovacuum(), do_des(), do_pg_stop_backup(), DoCopyTo(), dofindsubquery(), dsm_impl_op(), errfinish(), exec_execute_message(), exec_parse_message(), exec_replication_command(), exec_simple_query(), exec_stmts(), exec_toplevel_block(), ExecAgg(), ExecAppend(), ExecAppendAsyncGetNext(), ExecCustomScan(), ExecFindPartition(), ExecGather(), ExecGatherMerge(), ExecGroup(), ExecHashIncreaseNumBatches(), ExecHashIncreaseNumBuckets(), ExecHashJoinGetSavedTuple(), ExecHashJoinImpl(), ExecHashRemoveNextSkewBucket(), ExecIncrementalSort(), ExecLimit(), ExecLockRows(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecMergeAppend(), ExecMergeJoin(), ExecModifyTable(), ExecNestLoop(), ExecParallelHashIncreaseNumBuckets(), ExecParallelHashJoinPartitionOuter(), ExecParallelHashRepartitionFirst(), ExecParallelHashRepartitionRest(), ExecProjectSet(), ExecRecursiveUnion(), ExecResult(), ExecScanFetch(), ExecScanHashTableForUnmatched(), ExecSetOp(), ExecSort(), ExecSubPlan(), ExecUnique(), executeItemOptUnwrapTarget(), ExecWindowAgg(), fetch_input_tuple(), findPartialMatch(), flattenJsonPathParseItem(), fsm_vacuum_page(), gather_getnext(), gather_merge_init(), gather_readnext(), gcd_var(), get_query_def(), get_rule_expr(), get_setop_query(), GetMultiXactIdMembers(), GetNewOidWithIndex(), GetNewRelFileNode(), getNextNearest(), ginbuild(), ginBuildCallback(), gingetbitmap(), gist_indexsortbuild_pagestate_flush(), gistgetbitmap(), gistgettuple(), gistProcessItup(), gm_readnext_tuple(), HandleFunctionRequest(), heap_force_common(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heapam_index_build_range_scan(), heapam_index_validate_scan(), heapam_relation_copy_for_cluster(), heapam_scan_sample_next_tuple(), heapgetpage(), hypothetical_dense_rank_final(), hypothetical_rank_common(), ident_inet(), IndexCheckExclusion(), IndexNext(), IndexNextWithReorder(), IndexOnlyNext(), initialize_worker_spi(), interactive_getc(), lazy_truncate_heap(), log_newpage_range(), logicalrep_worker_stop(), LogicalRepApplyLoop(), lseg_inside_poly(), make_bounded_heap(), mode_final(), mq_putmessage(), MultiExecBitmapIndexScan(), MultiExecProcNode(), nfalsepos_for_missing_strings(), numeric_fac(), OpenTableList(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), pg_prewarm(), pg_promote(), pg_sleep(), pg_visibility_map_summary(), pg_wait_until_termination(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PGSemaphoreLock(), pgstat_collect_oids(), pgstat_get_backend_current_activity(), pgstat_heap(), pgstat_index(), pgstat_read_current_status(), pgstat_vacuum_stat(), pgstathashindex(), pgstatindex_impl(), plperl_spi_prepare(), populate_with_dummy_strings(), PortalRunMulti(), postgresAcquireSampleRowsFunc(), PostgresMain(), predicate_implied_by_simple_clause(), predicate_refuted_by_simple_clause(), printJsonPathItem(), process_ordered_aggregate_multi(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessWalRcvInterrupts(), ProcSleep(), ProcWaitForSignal(), puttuple_common(), random_relative_prime(), RE_compile_and_cache(), RE_wchar_execute(), read_local_xlog_page(), refresh_matview_datafill(), regexp_fixed_prefix(), ReindexRelationConcurrently(), RelationCopyStorage(), repeat(), replace_text(), replace_text_regexp(), replorigin_create(), RequestCheckpoint(), revmap_extend_and_get_blkno(), sendAuthRequest(), sendDir(), set_rtable_names(), setop_retrieve_hash_table(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), spgdoinsert(), spgWalk(), split_text(), statapprox_heap(), storeQueryResult(), summarize_range(), test_re_compile(), test_re_execute(), test_shm_mq_pipelined(), tfuncLoadRows(), throttle(), TidNext(), toast_save_datum(), TS_execute_recurse(), tuplesort_heap_insert(), tuplesort_heap_replace_top(), tuplesort_skiptuples(), tuplestore_skiptuples(), vacuum_delay_point(), vacuum_rel(), validateForeignKeyConstraint(), verify_heapam(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), wait_pid(), WaitExceedsMaxStandbyDelay(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), walkdir(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), and window_gettupleslot().

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 237 of file miscadmin.h.

Referenced by check_datestyle(), locale_date_order(), and setup_config().

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 235 of file miscadmin.h.

Referenced by check_datestyle(), DecodeNumber(), locale_date_order(), and setup_config().

◆ END_CRIT_SECTION

#define END_CRIT_SECTION ( )
Value:
do { \
Assert(CritSectionCount > 0); \
CritSectionCount--; \
} while(0)
PGDLLIMPORT volatile uint32 CritSectionCount
Definition: globals.c:41

Definition at line 149 of file miscadmin.h.

Referenced by _bt_dedup_pass(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_set_cleanup_info(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), AbsorbSyncRequests(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), brinRevmapDesummarizeRange(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateOverwriteContrecordRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), FreeSpaceMapPrepareTruncateRel(), GenericXLogFinish(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistdeletepage(), gistplacetopage(), gistprunepage(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_force_common(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), lazy_scan_heap(), lazy_scan_prune(), lazy_vacuum_heap_page(), log_newpage_range(), moveLeafs(), MultiXactIdCreateFromMembers(), nextval_internal(), PostPrepare_Locks(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), RecordTransactionCommitPrepared(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_prepare_truncate(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 410 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 139 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

◆ HOLD_INTERRUPTS

◆ INTERRUPTS_CAN_BE_PROCESSED

#define INTERRUPTS_CAN_BE_PROCESSED ( )
Value:
QueryCancelHoldoffCount == 0)
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
Definition: globals.c:39
PGDLLIMPORT volatile uint32 CritSectionCount
Definition: globals.c:41

Definition at line 127 of file miscadmin.h.

Referenced by spgdoinsert().

◆ INTERRUPTS_PENDING_CONDITION

#define INTERRUPTS_PENDING_CONDITION ( )    (unlikely(InterruptPending))

Definition at line 111 of file miscadmin.h.

Referenced by spgdoinsert().

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 252 of file miscadmin.h.

Referenced by EncodeInterval().

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 249 of file miscadmin.h.

Referenced by EncodeInterval(), and set_transmission_modes().

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 250 of file miscadmin.h.

Referenced by DecodeInterval(), EncodeInterval(), and PGTYPESinterval_to_asc().

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 251 of file miscadmin.h.

Referenced by DecodeInterval(), and EncodeInterval().

◆ InvalidPid

◆ IsBootstrapProcessingMode

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

◆ MAXTZLEN

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

Definition at line 256 of file miscadmin.h.

Referenced by abstime2tm(), and EncodeDateTime().

◆ RESUME_CANCEL_INTERRUPTS

#define RESUME_CANCEL_INTERRUPTS ( )
Value:
do { \
Assert(QueryCancelHoldoffCount > 0); \
QueryCancelHoldoffCount--; \
} while(0)
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:40

Definition at line 141 of file miscadmin.h.

Referenced by CopyGetData(), and SocketBackend().

◆ RESUME_INTERRUPTS

◆ SECURITY_LOCAL_USERID_CHANGE

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 313 of file miscadmin.h.

Referenced by InNoForceRLSOperation(), ri_PerformCheck(), and ri_PlanCheck().

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

◆ SetProcessingMode

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 147 of file miscadmin.h.

Referenced by _bt_dedup_pass(), _bt_delitems_delete(), _bt_delitems_vacuum(), _bt_getroot(), _bt_insertonpg(), _bt_mark_page_halfdead(), _bt_newroot(), _bt_set_cleanup_info(), _bt_split(), _bt_unlink_halfdead_page(), _hash_addovflpage(), _hash_doinsert(), _hash_expandtable(), _hash_freeovflpage(), _hash_splitbucket(), _hash_squeezebucket(), _hash_vacuum_one_page(), AbsorbSyncRequests(), addLeafTuple(), brin_doinsert(), brin_doupdate(), brin_initialize_empty_new_buffer(), brinbuildempty(), brinRevmapDesummarizeRange(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateOverwriteContrecordRecord(), createPostingTree(), CreateSlotOnDisk(), do_setval(), doPickSplit(), EndPrepare(), fill_seq_with_data(), FreeSpaceMapPrepareTruncateRel(), GenericXLogFinish(), GetNewMultiXactId(), ginbuild(), ginbuildempty(), ginbulkdelete(), ginDeletePage(), ginHeapTupleFastInsert(), ginPlaceToPage(), ginUpdateStats(), ginVacuumPostingTreeLeaf(), gistbuild(), gistbuildempty(), gistdeletepage(), gistplacetopage(), gistprunepage(), gistvacuumpage(), hashbucketcleanup(), hashbulkdelete(), heap_abort_speculative(), heap_delete(), heap_finish_speculative(), heap_force_common(), heap_inplace_update(), heap_insert(), heap_lock_tuple(), heap_lock_updated_tuple_rec(), heap_multi_insert(), heap_page_prune(), heap_update(), lazy_scan_heap(), lazy_scan_prune(), lazy_vacuum_heap_page(), log_newpage_range(), moveLeafs(), nextval_internal(), PostPrepare_Locks(), RecordTransactionAbort(), RecordTransactionAbortPrepared(), RecordTransactionCommit(), RecordTransactionCommitPrepared(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), revmap_physical_extend(), SaveSlotToPath(), shiftList(), SlruPhysicalWritePage(), spgAddNodeAction(), spgbuild(), spgSplitNodeAction(), TruncateMultiXact(), UpdateFullPageWrites(), vacuumLeafPage(), vacuumLeafRoot(), vacuumRedirectAndPlaceholder(), visibilitymap_prepare_truncate(), visibilitymap_set(), write_relmap_file(), writeListPage(), XLogBackgroundFlush(), XLogFlush(), and XLogInsertRecord().

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 231 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 228 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 230 of file miscadmin.h.

Referenced by check_datestyle(), EncodeDateOnly(), and EncodeDateTime().

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Typedef Documentation

◆ BackendType

typedef enum BackendType BackendType

◆ pg_stack_base_t

typedef char* pg_stack_base_t

Definition at line 288 of file miscadmin.h.

◆ ProcessingMode

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
StartupProcess 
BgWriterProcess 
ArchiverProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 429 of file miscadmin.h.

◆ BackendType

Enumerator
B_INVALID 
B_AUTOVAC_LAUNCHER 
B_AUTOVAC_WORKER 
B_BACKEND 
B_BG_WORKER 
B_BG_WRITER 
B_CHECKPOINTER 
B_STARTUP 
B_WAL_RECEIVER 
B_WAL_SENDER 
B_WAL_WRITER 
B_ARCHIVER 
B_STATS_COLLECTOR 
B_LOGGER 

Definition at line 323 of file miscadmin.h.

◆ ProcessingMode

Enumerator
BootstrapProcessing 
InitProcessing 
NormalProcessing 

Definition at line 397 of file miscadmin.h.

398 {
399  BootstrapProcessing, /* bootstrap creation of template database */
400  InitProcessing, /* initializing system */
401  NormalProcessing /* normal processing */
ProcessingMode
Definition: miscadmin.h:397

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1348 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pg_fsync(), pg_pwrite(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, and WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE.

Referenced by InternalIpcMemoryCreate(), pmdie(), PostmasterMain(), reaper(), and sigusr1_handler().

1349 {
1350  int fd;
1351  int len;
1352  int lineno;
1353  char *srcptr;
1354  char *destptr;
1355  char srcbuffer[BLCKSZ];
1356  char destbuffer[BLCKSZ];
1357 
1358  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1359  if (fd < 0)
1360  {
1361  ereport(LOG,
1363  errmsg("could not open file \"%s\": %m",
1365  return;
1366  }
1368  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1370  if (len < 0)
1371  {
1372  ereport(LOG,
1374  errmsg("could not read from file \"%s\": %m",
1376  close(fd);
1377  return;
1378  }
1379  srcbuffer[len] = '\0';
1380 
1381  /*
1382  * Advance over lines we are not supposed to rewrite, then copy them to
1383  * destbuffer.
1384  */
1385  srcptr = srcbuffer;
1386  for (lineno = 1; lineno < target_line; lineno++)
1387  {
1388  char *eol = strchr(srcptr, '\n');
1389 
1390  if (eol == NULL)
1391  break; /* not enough lines in file yet */
1392  srcptr = eol + 1;
1393  }
1394  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1395  destptr = destbuffer + (srcptr - srcbuffer);
1396 
1397  /*
1398  * Fill in any missing lines before the target line, in case lines are
1399  * added to the file out of order.
1400  */
1401  for (; lineno < target_line; lineno++)
1402  {
1403  if (destptr < destbuffer + sizeof(destbuffer))
1404  *destptr++ = '\n';
1405  }
1406 
1407  /*
1408  * Write or rewrite the target line.
1409  */
1410  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1411  destptr += strlen(destptr);
1412 
1413  /*
1414  * If there are more lines in the old file, append them to destbuffer.
1415  */
1416  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1417  {
1418  srcptr++;
1419  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1420  srcptr);
1421  }
1422 
1423  /*
1424  * And rewrite the data. Since we write in a single kernel call, this
1425  * update should appear atomic to onlookers.
1426  */
1427  len = strlen(destbuffer);
1428  errno = 0;
1430  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1431  {
1433  /* if write didn't set errno, assume problem is no disk space */
1434  if (errno == 0)
1435  errno = ENOSPC;
1436  ereport(LOG,
1438  errmsg("could not write to file \"%s\": %m",
1440  close(fd);
1441  return;
1442  }
1445  if (pg_fsync(fd) != 0)
1446  {
1447  ereport(LOG,
1449  errmsg("could not write to file \"%s\": %m",
1451  }
1453  if (close(fd) != 0)
1454  {
1455  ereport(LOG,
1457  errmsg("could not write to file \"%s\": %m",
1459  }
1460 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
Definition: pwrite.c:27
int errcode_for_file_access(void)
Definition: elog.c:721
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:258
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int pg_fsync(int fd)
Definition: fd.c:357
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:217
#define read(a, b, c)
Definition: win32.h:13

◆ BackupInProgress()

bool BackupInProgress ( void  )

Definition at line 12238 of file xlog.c.

References BACKUP_LABEL_FILE, and stat.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

12239 {
12240  struct stat stat_buf;
12241 
12242  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
12243 }
#define BACKUP_LABEL_FILE
Definition: xlog.h:363
#define stat
Definition: win32_port.h:283

◆ BaseInit()

void BaseInit ( void  )

Definition at line 511 of file postinit.c.

References Assert, DebugFileOpen(), InitBufferPoolAccess(), InitFileAccess(), InitSync(), InitTemporaryFileAccess(), MyProc, pgstat_initialize(), and smgrinit().

Referenced by AutoVacLauncherMain(), AutoVacWorkerMain(), AuxiliaryProcessMain(), BootstrapModeMain(), PostgresMain(), and StartBackgroundWorker().

512 {
513  Assert(MyProc != NULL);
514 
515  /*
516  * Initialize our input/output/debugging file descriptors.
517  */
518  DebugFileOpen();
519 
520  /*
521  * Initialize file access. Done early so other subsystems can access
522  * files.
523  */
524  InitFileAccess();
525 
526  /*
527  * Initialize statistics reporting. This needs to happen early to ensure
528  * that pgstat's shutdown callback runs after the shutdown callbacks of
529  * all subsystems that can produce stats (like e.g. transaction commits
530  * can).
531  */
533 
534  /* Do local initialization of storage and buffer managers */
535  InitSync();
536  smgrinit();
538 
539  /*
540  * Initialize temporary file access after pgstat, so that the temporary
541  * file shutdown hook can report temporary file statistics.
542  */
544 }
PGPROC * MyProc
Definition: proc.c:68
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2596
void pgstat_initialize(void)
Definition: pgstat.c:3026
void DebugFileOpen(void)
Definition: elog.c:1922
void smgrinit(void)
Definition: smgr.c:111
#define Assert(condition)
Definition: c.h:804
void InitSync(void)
Definition: sync.c:128
void InitTemporaryFileAccess(void)
Definition: fd.c:911
void InitFileAccess(void)
Definition: fd.c:881

◆ CancelBackup()

void CancelBackup ( void  )

Definition at line 12258 of file xlog.c.

References BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errdetail(), errmsg(), LOG, stat, TABLESPACE_MAP, TABLESPACE_MAP_OLD, and WARNING.

Referenced by PostmasterStateMachine().

12259 {
12260  struct stat stat_buf;
12261 
12262  /* if the backup_label file is not there, return */
12263  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
12264  return;
12265 
12266  /* remove leftover file from previously canceled backup if it exists */
12267  unlink(BACKUP_LABEL_OLD);
12268 
12270  {
12271  ereport(WARNING,
12273  errmsg("online backup mode was not canceled"),
12274  errdetail("File \"%s\" could not be renamed to \"%s\": %m.",
12276  return;
12277  }
12278 
12279  /* if the tablespace_map file is not there, return */
12280  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
12281  {
12282  ereport(LOG,
12283  (errmsg("online backup mode canceled"),
12284  errdetail("File \"%s\" was renamed to \"%s\".",
12286  return;
12287  }
12288 
12289  /* remove leftover file from previously canceled backup if it exists */
12290  unlink(TABLESPACE_MAP_OLD);
12291 
12293  {
12294  ereport(LOG,
12295  (errmsg("online backup mode canceled"),
12296  errdetail("Files \"%s\" and \"%s\" were renamed to "
12297  "\"%s\" and \"%s\", respectively.",
12300  }
12301  else
12302  {
12303  ereport(WARNING,
12305  errmsg("online backup mode canceled"),
12306  errdetail("File \"%s\" was renamed to \"%s\", but "
12307  "file \"%s\" could not be renamed to \"%s\": %m.",
12310  }
12311 }
#define DEBUG1
Definition: elog.h:25
#define LOG
Definition: elog.h:26
#define BACKUP_LABEL_OLD
Definition: xlog.h:364
#define TABLESPACE_MAP
Definition: xlog.h:366
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:697
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
#define TABLESPACE_MAP_OLD
Definition: xlog.h:367
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define BACKUP_LABEL_FILE
Definition: xlog.h:363
#define stat
Definition: win32_port.h:283

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 435 of file miscinit.c.

References AssertState, DataDir, ereport, errcode_for_file_access(), errmsg(), and FATAL.

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

436 {
438 
439  if (chdir(DataDir) < 0)
440  ereport(FATAL,
442  errmsg("could not change directory to \"%s\": %m",
443  DataDir)));
444 }
#define AssertState(condition)
Definition: c.h:807
#define FATAL
Definition: elog.h:49
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * DataDir
Definition: globals.c:65

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3469 of file postgres.c.

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

Referenced by AlterTypeRecurse(), apply_scanjoin_target_to_paths(), checkCond(), clean_NOT_intree(), clean_stopword_intree(), cntsize(), contains_required_value(), convertJsonbValue(), copyObjectImpl(), Cover(), create_plan_recurse(), datum_to_json(), datum_to_jsonb(), dofindsubquery(), emit_jsp_gin_entries(), equal(), EventTriggerInvoke(), ExecEndNode(), ExecEvalSubPlan(), ExecInitExprRec(), ExecInitNode(), ExecMakeFunctionResultSet(), ExecProcNodeFirst(), ExecShutdownNode(), execute(), executeAnyItem(), executeItemOptUnwrapTarget(), expand_partitioned_rtentry(), expression_tree_mutator(), expression_tree_walker(), extract_jsp_bool_expr(), fillQT(), find_composite_type_dependencies(), find_matching_subplans_recurse(), findoprnd(), findoprnd_recurse(), flatten_grouping_sets(), flattenJsonPathParseItem(), FreePageManagerDumpBtree(), freetree(), generate_partition_qual(), generate_partitionwise_join_paths(), 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(), inline_set_returning_function(), int_query_opr_selec(), JsonbDeepContains(), JumbleExpr(), ltree_execute(), makepol(), maketree(), MatchText(), MultiExecProcNode(), outNode(), parse_array(), parse_object(), parseNodeString(), plainnode(), planstate_tree_walker(), plperl_hash_from_tuple(), plperl_sv_to_datum(), PLy_input_setup_func(), PLy_output_setup_func(), populate_array_dim_jsonb(), populate_record_field(), printJsonPathItem(), QT2QTN(), QTNBinary(), QTNClearFlags(), QTNCopy(), QTNFree(), QTNodeCompare(), QTNSort(), QTNTernary(), range_cmp(), range_in(), range_out(), range_recv(), range_send(), raw_expression_tree_walker(), record_cmp(), record_eq(), record_in(), record_out(), record_recv(), record_send(), recurse_set_operations(), relation_is_updatable(), resolve_special_varno(), set_append_rel_size(), setPath(), split_array(), standard_ProcessUtility(), transformExprRecurse(), transformSetOperationTree(), traverse_lacons(), try_partitionwise_join(), TS_execute_recurse(), TS_phrase_execute(), tsquery_opr_selec(), and tsquery_requires_match().

3470 {
3471  if (stack_is_too_deep())
3472  {
3473  ereport(ERROR,
3474  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3475  errmsg("stack depth limit exceeded"),
3476  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3477  "after ensuring the platform's stack depth limit is adequate.",
3478  max_stack_depth)));
3479  }
3480 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
int max_stack_depth
Definition: postgres.c:100
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
bool stack_is_too_deep(void)
Definition: postgres.c:3483

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 321 of file miscinit.c.

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

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

322 {
323  struct stat stat_buf;
324 
325  Assert(DataDir);
326 
327  if (stat(DataDir, &stat_buf) != 0)
328  {
329  if (errno == ENOENT)
330  ereport(FATAL,
332  errmsg("data directory \"%s\" does not exist",
333  DataDir)));
334  else
335  ereport(FATAL,
337  errmsg("could not read permissions of directory \"%s\": %m",
338  DataDir)));
339  }
340 
341  /* eventual chdir would fail anyway, but let's test ... */
342  if (!S_ISDIR(stat_buf.st_mode))
343  ereport(FATAL,
344  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
345  errmsg("specified data directory \"%s\" is not a directory",
346  DataDir)));
347 
348  /*
349  * Check that the directory belongs to my userid; if not, reject.
350  *
351  * This check is an essential part of the interlock that prevents two
352  * postmasters from starting in the same directory (see CreateLockFile()).
353  * Do not remove or weaken it.
354  *
355  * XXX can we safely enable this check on Windows?
356  */
357 #if !defined(WIN32) && !defined(__CYGWIN__)
358  if (stat_buf.st_uid != geteuid())
359  ereport(FATAL,
360  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
361  errmsg("data directory \"%s\" has wrong ownership",
362  DataDir),
363  errhint("The server must be started by the user that owns the data directory.")));
364 #endif
365 
366  /*
367  * Check if the directory has correct permissions. If not, reject.
368  *
369  * Only two possible modes are allowed, 0700 and 0750. The latter mode
370  * indicates that group read/execute should be allowed on all newly
371  * created files and directories.
372  *
373  * XXX temporarily suppress check when on Windows, because there may not
374  * be proper support for Unix-y file permissions. Need to think of a
375  * reasonable check to apply on Windows.
376  */
377 #if !defined(WIN32) && !defined(__CYGWIN__)
378  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
379  ereport(FATAL,
380  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
381  errmsg("data directory \"%s\" has invalid permissions",
382  DataDir),
383  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
384 #endif
385 
386  /*
387  * Reset creation modes and mask based on the mode of the data directory.
388  *
389  * The mask was set earlier in startup to disallow group permissions on
390  * newly created files and directories. However, if group read/execute
391  * are present on the data directory then modify the create modes and mask
392  * to allow group read/execute on newly created files and directories and
393  * set the data_directory_mode GUC.
394  *
395  * Suppress when on Windows, because there may not be proper support for
396  * Unix-y file permissions.
397  */
398 #if !defined(WIN32) && !defined(__CYGWIN__)
399  SetDataDirectoryCreatePerm(stat_buf.st_mode);
400 
401  umask(pg_mode_mask);
403 #endif
404 
405  /* Check for PG_VERSION */
407 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1547
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
#define FATAL
Definition: elog.h:49
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
int pg_dir_create_mode
Definition: file_perm.c:18
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define S_ISDIR(m)
Definition: win32_port.h:324
int errmsg(const char *fmt,...)
Definition: elog.c:909
int data_directory_mode
Definition: globals.c:71
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
char * DataDir
Definition: globals.c:65
int pg_mode_mask
Definition: file_perm.c:25
#define stat
Definition: win32_port.h:283

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1292 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1293 {
1294  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1295 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:987
char * DataDir
Definition: globals.c:65

◆ CreateSocketLockFile()

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

Definition at line 1301 of file miscinit.c.

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by StreamServerPort().

1303 {
1304  char lockfile[MAXPGPATH];
1305 
1306  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1307  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1308 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:987
#define MAXPGPATH
#define snprintf
Definition: port.h:217

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )

Definition at line 3401 of file nodeHash.c.

References hash_mem_multiplier, Min, and work_mem.

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

3402 {
3403  double mem_limit;
3404 
3405  /* Do initial calculation in double arithmetic */
3406  mem_limit = (double) work_mem * hash_mem_multiplier * 1024.0;
3407 
3408  /* Clamp in case it doesn't fit in size_t */
3409  mem_limit = Min(mem_limit, (double) SIZE_MAX);
3410 
3411  return (size_t) mem_limit;
3412 }
double hash_mem_multiplier
Definition: globals.c:125
#define Min(x, y)
Definition: c.h:986
int work_mem
Definition: globals.c:124

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 554 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

555 {
557  return AuthenticatedUserId;
558 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 249 of file miscinit.c.

References B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_INVALID, B_LOGGER, B_STARTUP, B_STATS_COLLECTOR, B_WAL_RECEIVER, B_WAL_SENDER, and B_WAL_WRITER.

Referenced by BackendInitialize(), init_ps_display(), log_line_prefix(), pg_stat_get_activity(), and write_csvlog().

250 {
251  const char *backendDesc = "unknown process type";
252 
253  switch (backendType)
254  {
255  case B_INVALID:
256  backendDesc = "not initialized";
257  break;
258  case B_AUTOVAC_LAUNCHER:
259  backendDesc = "autovacuum launcher";
260  break;
261  case B_AUTOVAC_WORKER:
262  backendDesc = "autovacuum worker";
263  break;
264  case B_BACKEND:
265  backendDesc = "client backend";
266  break;
267  case B_BG_WORKER:
268  backendDesc = "background worker";
269  break;
270  case B_BG_WRITER:
271  backendDesc = "background writer";
272  break;
273  case B_CHECKPOINTER:
274  backendDesc = "checkpointer";
275  break;
276  case B_STARTUP:
277  backendDesc = "startup";
278  break;
279  case B_WAL_RECEIVER:
280  backendDesc = "walreceiver";
281  break;
282  case B_WAL_SENDER:
283  backendDesc = "walsender";
284  break;
285  case B_WAL_WRITER:
286  backendDesc = "walwriter";
287  break;
288  case B_ARCHIVER:
289  backendDesc = "archiver";
290  break;
291  case B_STATS_COLLECTOR:
292  backendDesc = "stats collector";
293  break;
294  case B_LOGGER:
295  backendDesc = "logger";
296  break;
297  }
298 
299  return backendDesc;
300 }

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 854 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

855 {
856  if (SetRoleIsActive)
857  return OuterUserId;
858  else
859  return InvalidOid;
860 }
static Oid OuterUserId
Definition: miscinit.c:477
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:487

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 506 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

507 {
509  return OuterUserId;
510 }
#define AssertState(condition)
Definition: c.h:807
static Oid OuterUserId
Definition: miscinit.c:477
#define OidIsValid(objectId)
Definition: c.h:710

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 529 of file miscinit.c.

References AssertState, OidIsValid, and SessionUserId.

Referenced by check_role(), DropRole(), get_rolespec_oid(), get_rolespec_tuple(), InitPostgres(), is_admin_of_role(), pgstat_bestart(), RenameRole(), and session_user().

530 {
532  return SessionUserId;
533 }
#define AssertState(condition)
Definition: c.h:807
static Oid SessionUserId
Definition: miscinit.c:476
#define OidIsValid(objectId)
Definition: c.h:710

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 495 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), 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(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), brin_summarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), convert_and_check_filename(), create_foreign_modify(), 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(), DelRoleMems(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildParamSetEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteGrantStmt(), ExecuteTruncateGuts(), extension_is_trusted(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_explain_guc_options(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), 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_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_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), 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_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(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_foreign_rel_properties(), ShowAllGUCConfig(), statext_is_compatible_clause(), superuser(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_relation_owner(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

496 {
498  return CurrentUserId;
499 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
static Oid CurrentUserId
Definition: miscinit.c:478

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 649 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

650 {
651  *userid = CurrentUserId;
652  *sec_def_context = InLocalUserIdChange();
653 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:618
static Oid CurrentUserId
Definition: miscinit.c:478

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 910 of file miscinit.c.

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

Referenced by check_is_member_of_role(), current_user(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), insert_username(), regroleout(), and session_user().

911 {
912  HeapTuple tuple;
913  char *result;
914 
915  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
916  if (!HeapTupleIsValid(tuple))
917  {
918  if (!noerr)
919  ereport(ERROR,
920  (errcode(ERRCODE_UNDEFINED_OBJECT),
921  errmsg("invalid role OID: %u", roleid)));
922  result = NULL;
923  }
924  else
925  {
926  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
927  ReleaseSysCache(tuple);
928  }
929  return result;
930 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
NameData rolname
Definition: pg_authid.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1299
int errcode(int sqlerrcode)
Definition: elog.c:698
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 676 of file miscinit.c.

References AUTHOID, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum, ReleaseSysCache(), rolreplication, and SearchSysCache1().

Referenced by CheckSlotPermissions(), and InitPostgres().

677 {
678  bool result = false;
679  HeapTuple utup;
680 
681  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
682  if (HeapTupleIsValid(utup))
683  {
684  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
685  ReleaseSysCache(utup);
686  }
687  return result;
688 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
bool rolreplication
Definition: pg_authid.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 489 of file postinit.c.

References Assert, autovacuum_max_workers, elog, ERROR, MAX_BACKENDS, max_wal_senders, max_worker_processes, MaxBackends, and MaxConnections.

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

490 {
491  Assert(MaxBackends == 0);
492 
493  /* the extra unit accounts for the autovacuum launcher */
496 
497  /* internal error because the values were all checked previously */
499  elog(ERROR, "too many backends configured");
500 }
#define ERROR
Definition: elog.h:46
#define MAX_BACKENDS
Definition: postmaster.h:76
int MaxBackends
Definition: globals.c:139
int max_wal_senders
Definition: walsender.c:121
int MaxConnections
Definition: globals.c:136
int autovacuum_max_workers
Definition: autovacuum.c:115
#define Assert(condition)
Definition: c.h:804
#define elog(elevel,...)
Definition: elog.h:232
int max_worker_processes
Definition: globals.c:137

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 694 of file miscinit.c.

References AcceptInvalidationMessages(), AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, HeapTupleIsValid, IsBootstrapProcessingMode, IsUnderPostmaster, MyProc, NameStr, ObjectIdGetDatum, OidIsValid, PGC_BACKEND, PGC_INTERNAL, PGC_S_OVERRIDE, PointerGetDatum, ReleaseSysCache(), PGPROC::roleId, SearchSysCache1(), SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

695 {
696  HeapTuple roleTup;
697  Form_pg_authid rform;
698  char *rname;
699 
700  /*
701  * Don't do scans if we're bootstrapping, none of the system catalogs
702  * exist yet, and they should be owned by postgres anyway.
703  */
705 
706  /* call only once */
708 
709  /*
710  * Make sure syscache entries are flushed for recent catalog changes. This
711  * allows us to find roles that were created on-the-fly during
712  * authentication.
713  */
715 
716  if (rolename != NULL)
717  {
718  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
719  if (!HeapTupleIsValid(roleTup))
720  ereport(FATAL,
721  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
722  errmsg("role \"%s\" does not exist", rolename)));
723  }
724  else
725  {
726  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
727  if (!HeapTupleIsValid(roleTup))
728  ereport(FATAL,
729  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
730  errmsg("role with OID %u does not exist", roleid)));
731  }
732 
733  rform = (Form_pg_authid) GETSTRUCT(roleTup);
734  roleid = rform->oid;
735  rname = NameStr(rform->rolname);
736 
737  AuthenticatedUserId = roleid;
738  AuthenticatedUserIsSuperuser = rform->rolsuper;
739 
740  /* This sets OuterUserId/CurrentUserId too */
742 
743  /* Also mark our PGPROC entry with the authenticated user id */
744  /* (We assume this is an atomic store so no lock is needed) */
745  MyProc->roleId = roleid;
746 
747  /*
748  * These next checks are not enforced when in standalone mode, so that
749  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
750  * rolcanlogin = false;".
751  */
752  if (IsUnderPostmaster)
753  {
754  /*
755  * Is role allowed to login at all?
756  */
757  if (!rform->rolcanlogin)
758  ereport(FATAL,
759  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
760  errmsg("role \"%s\" is not permitted to log in",
761  rname)));
762 
763  /*
764  * Check connection limit for this role.
765  *
766  * There is a race condition here --- we create our PGPROC before
767  * checking for other PGPROCs. If two backends did this at about the
768  * same time, they might both think they were over the limit, while
769  * ideally one should succeed and one fail. Getting that to work
770  * exactly seems more trouble than it is worth, however; instead we
771  * just document that the connection limit is approximate.
772  */
773  if (rform->rolconnlimit >= 0 &&
775  CountUserBackends(roleid) > rform->rolconnlimit)
776  ereport(FATAL,
777  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
778  errmsg("too many connections for role \"%s\"",
779  rname)));
780  }
781 
782  /* Record username and superuser status as GUC settings too */
783  SetConfigOption("session_authorization", rname,
785  SetConfigOption("is_superuser",
786  AuthenticatedUserIsSuperuser ? "on" : "off",
788 
789  ReleaseSysCache(roleTup);
790 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define AssertState(condition)
Definition: c.h:807
void AcceptInvalidationMessages(void)
Definition: inval.c:725
PGPROC * MyProc
Definition: proc.c:68
#define PointerGetDatum(X)
Definition: postgres.h:600
Oid roleId
Definition: proc.h:155
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define FATAL
Definition: elog.h:49
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8110
bool IsUnderPostmaster
Definition: globals.c:112
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:481
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int CountUserBackends(Oid roleid)
Definition: procarray.c:3632
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:537
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 797 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsUnderPostmaster, OidIsValid, and SetSessionUserId().

Referenced by InitPostgres().

798 {
799  /*
800  * This function should only be called in single-user mode, in autovacuum
801  * workers, and in background workers.
802  */
804 
805  /* call only once */
807 
808  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
810 
811  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
812 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
bool IsBackgroundWorker
Definition: globals.c:114
bool IsUnderPostmaster
Definition: globals.c:112
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:481
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3410
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:537
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ InitPostgres()

void InitPostgres ( const char *  in_dbname,
Oid  dboid,
const char *  username,
Oid  useroid,
char *  out_dbname,
bool  override_allow_connections 
)

Definition at line 572 of file postinit.c.

References am_db_walsender, am_walsender, Assert, before_shmem_exit(), CAC_SUPERUSER, Port::canAcceptConnections, CheckDeadLockAlert(), CheckMyDatabase(), CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler(), CommitTransactionCommand(), CreateAuxProcessResourceOwner(), CurrentResourceOwner, PGPROC::databaseId, dbname, DEADLOCK_TIMEOUT, DEBUG3, elog, EnablePortalManager(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, GetDatabasePath(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetSessionUserId(), GETSTRUCT, GetTransactionSnapshot(), GetUserId(), has_rolreplication(), HaveNFreeProcs(), HeapTupleIsValid, IDLE_IN_TRANSACTION_SESSION_TIMEOUT, IDLE_SESSION_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), InitCatalogCache(), initialize_acl(), InitializeClientEncoding(), InitializeSearchPath(), InitializeSession(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPlanCache(), InitProcessPhase2(), InvalidateCatalogSnapshot(), InvalidBackendId, IsAutoVacuumLauncherProcess(), IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsBinaryUpgrade, IsBootstrapProcessingMode, IsUnderPostmaster, LOCK_TIMEOUT, LockSharedObject(), LockTimeoutHandler(), MaxBackends, MyBackendId, MyDatabaseId, MyDatabaseTableSpace, MyProc, MyProcPort, NAMEDATALEN, NameStr, OidIsValid, PerformAuthentication(), pg_usleep(), pgstat_beinit(), pgstat_bestart(), PostAuthDelay, process_settings(), process_startup_options(), ProcSignalInit(), RecoveryInProgress(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), ThereIsAtLeastOneRole(), ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

574 {
575  bool bootstrap = IsBootstrapProcessingMode();
576  bool am_superuser;
577  char *fullpath;
578  char dbname[NAMEDATALEN];
579 
580  elog(DEBUG3, "InitPostgres");
581 
582  /*
583  * Add my PGPROC struct to the ProcArray.
584  *
585  * Once I have done this, I am visible to other backends!
586  */
588 
589  /*
590  * Initialize my entry in the shared-invalidation manager's array of
591  * per-backend data.
592  *
593  * Sets up MyBackendId, a unique backend identifier.
594  */
596 
597  SharedInvalBackendInit(false);
598 
599  if (MyBackendId > MaxBackends || MyBackendId <= 0)
600  elog(FATAL, "bad backend ID: %d", MyBackendId);
601 
602  /* Now that we have a BackendId, we can participate in ProcSignal */
604 
605  /*
606  * Also set up timeout handlers needed for backend operation. We need
607  * these in every case except bootstrap.
608  */
609  if (!bootstrap)
610  {
618  }
619 
620  /*
621  * Initialize local process's access to XLOG.
622  */
623  if (IsUnderPostmaster)
624  {
625  /*
626  * The postmaster already started the XLOG machinery, but we need to
627  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
628  * This is handled by calling RecoveryInProgress and ignoring the
629  * result.
630  */
631  (void) RecoveryInProgress();
632  }
633  else
634  {
635  /*
636  * We are either a bootstrap process or a standalone backend. Either
637  * way, start up the XLOG machinery, and register to have it closed
638  * down at exit.
639  *
640  * We don't yet have an aux-process resource owner, but StartupXLOG
641  * and ShutdownXLOG will need one. Hence, create said resource owner
642  * (and register a callback to clean it up after ShutdownXLOG runs).
643  */
645 
646  StartupXLOG();
647  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
649  /* Reset CurrentResourceOwner to nothing for the moment */
650  CurrentResourceOwner = NULL;
651 
652  /*
653  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
654  * segments etc to work (which in turn is required for pgstats).
655  */
657  }
658 
659  /*
660  * Initialize the relation cache and the system catalog caches. Note that
661  * no catalog access happens here; we only set up the hashtable structure.
662  * We must do this before starting a transaction because transaction abort
663  * would try to touch these hashtables.
664  */
667  InitPlanCache();
668 
669  /* Initialize portal manager */
671 
672  /* Initialize status reporting */
673  if (!bootstrap)
674  pgstat_beinit();
675 
676  /*
677  * Load relcache entries for the shared system catalogs. This must create
678  * at least entries for pg_database and catalogs used for authentication.
679  */
681 
682  /*
683  * Set up process-exit callback to do pre-shutdown cleanup. This is the
684  * one of the first before_shmem_exit callbacks we register; thus, this
685  * will be one the last things we do before low-level modules like the
686  * buffer manager begin to close down. We need to have this in place
687  * before we begin our first transaction --- if we fail during the
688  * initialization transaction, as is entirely possible, we need the
689  * AbortTransaction call to clean up.
690  */
692 
693  /* The autovacuum launcher is done here */
695  {
696  /* report this backend in the PgBackendStatus array */
697  pgstat_bestart();
698 
699  return;
700  }
701 
702  /*
703  * Start a new transaction here before first access to db, and get a
704  * snapshot. We don't have a use for the snapshot itself, but we're
705  * interested in the secondary effect that it sets RecentGlobalXmin. (This
706  * is critical for anything that reads heap pages, because HOT may decide
707  * to prune them even if the process doesn't attempt to modify any
708  * tuples.)
709  *
710  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
711  * not pushed/active does not reliably prevent HOT pruning (->xmin could
712  * e.g. be cleared when cache invalidations are processed).
713  */
714  if (!bootstrap)
715  {
716  /* statement_timestamp must be set for timeouts to work correctly */
719 
720  /*
721  * transaction_isolation will have been set to the default by the
722  * above. If the default is "serializable", and we are in hot
723  * standby, we will fail if we don't change it to something lower.
724  * Fortunately, "read committed" is plenty good enough.
725  */
727 
728  (void) GetTransactionSnapshot();
729  }
730 
731  /*
732  * Perform client authentication if necessary, then figure out our
733  * postgres user ID, and see if we are a superuser.
734  *
735  * In standalone mode and in autovacuum worker processes, we use a fixed
736  * ID, otherwise we figure it out from the authenticated user name.
737  */
738  if (bootstrap || IsAutoVacuumWorkerProcess())
739  {
741  am_superuser = true;
742  }
743  else if (!IsUnderPostmaster)
744  {
746  am_superuser = true;
747  if (!ThereIsAtLeastOneRole())
749  (errcode(ERRCODE_UNDEFINED_OBJECT),
750  errmsg("no roles are defined in this database system"),
751  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
752  username != NULL ? username : "postgres")));
753  }
754  else if (IsBackgroundWorker)
755  {
756  if (username == NULL && !OidIsValid(useroid))
757  {
759  am_superuser = true;
760  }
761  else
762  {
764  am_superuser = superuser();
765  }
766  }
767  else
768  {
769  /* normal multiuser case */
770  Assert(MyProcPort != NULL);
773  am_superuser = superuser();
774  }
775 
776  /*
777  * If we're trying to shut down, only superusers can connect, and new
778  * replication connections are not allowed.
779  */
780  if ((!am_superuser || am_walsender) &&
781  MyProcPort != NULL &&
783  {
784  if (am_walsender)
785  ereport(FATAL,
786  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
787  errmsg("new replication connections are not allowed during database shutdown")));
788  else
789  ereport(FATAL,
790  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
791  errmsg("must be superuser to connect during database shutdown")));
792  }
793 
794  /*
795  * Binary upgrades only allowed super-user connections
796  */
797  if (IsBinaryUpgrade && !am_superuser)
798  {
799  ereport(FATAL,
800  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
801  errmsg("must be superuser to connect in binary upgrade mode")));
802  }
803 
804  /*
805  * The last few connection slots are reserved for superusers. Replication
806  * connections are drawn from slots reserved with max_wal_senders and not
807  * limited by max_connections or superuser_reserved_connections.
808  */
809  if (!am_superuser && !am_walsender &&
810  ReservedBackends > 0 &&
812  ereport(FATAL,
813  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
814  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
815 
816  /* Check replication permissions needed for walsender processes. */
817  if (am_walsender)
818  {
819  Assert(!bootstrap);
820 
821  if (!superuser() && !has_rolreplication(GetUserId()))
822  ereport(FATAL,
823  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
824  errmsg("must be superuser or replication role to start walsender")));
825  }
826 
827  /*
828  * If this is a plain walsender only supporting physical replication, we
829  * don't want to connect to any particular database. Just finish the
830  * backend startup by processing any options from the startup packet, and
831  * we're done.
832  */
834  {
835  /* process any options passed in the startup packet */
836  if (MyProcPort != NULL)
837  process_startup_options(MyProcPort, am_superuser);
838 
839  /* Apply PostAuthDelay as soon as we've read all options */
840  if (PostAuthDelay > 0)
841  pg_usleep(PostAuthDelay * 1000000L);
842 
843  /* initialize client encoding */
845 
846  /* report this backend in the PgBackendStatus array */
847  pgstat_bestart();
848 
849  /* close the transaction we started above */
851 
852  return;
853  }
854 
855  /*
856  * Set up the global variables holding database id and default tablespace.
857  * But note we won't actually try to touch the database just yet.
858  *
859  * We take a shortcut in the bootstrap case, otherwise we have to look up
860  * the db's entry in pg_database.
861  */
862  if (bootstrap)
863  {
864  MyDatabaseId = TemplateDbOid;
865  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
866  }
867  else if (in_dbname != NULL)
868  {
869  HeapTuple tuple;
870  Form_pg_database dbform;
871 
872  tuple = GetDatabaseTuple(in_dbname);
873  if (!HeapTupleIsValid(tuple))
874  ereport(FATAL,
875  (errcode(ERRCODE_UNDEFINED_DATABASE),
876  errmsg("database \"%s\" does not exist", in_dbname)));
877  dbform = (Form_pg_database) GETSTRUCT(tuple);
878  MyDatabaseId = dbform->oid;
879  MyDatabaseTableSpace = dbform->dattablespace;
880  /* take database name from the caller, just for paranoia */
881  strlcpy(dbname, in_dbname, sizeof(dbname));
882  }
883  else if (OidIsValid(dboid))
884  {
885  /* caller specified database by OID */
886  HeapTuple tuple;
887  Form_pg_database dbform;
888 
889  tuple = GetDatabaseTupleByOid(dboid);
890  if (!HeapTupleIsValid(tuple))
891  ereport(FATAL,
892  (errcode(ERRCODE_UNDEFINED_DATABASE),
893  errmsg("database %u does not exist", dboid)));
894  dbform = (Form_pg_database) GETSTRUCT(tuple);
895  MyDatabaseId = dbform->oid;
896  MyDatabaseTableSpace = dbform->dattablespace;
897  Assert(MyDatabaseId == dboid);
898  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
899  /* pass the database name back to the caller */
900  if (out_dbname)
901  strcpy(out_dbname, dbname);
902  }
903  else
904  {
905  /*
906  * If this is a background worker not bound to any particular
907  * database, we're done now. Everything that follows only makes sense
908  * if we are bound to a specific database. We do need to close the
909  * transaction we started before returning.
910  */
911  if (!bootstrap)
912  {
913  pgstat_bestart();
915  }
916  return;
917  }
918 
919  /*
920  * Now, take a writer's lock on the database we are trying to connect to.
921  * If there is a concurrently running DROP DATABASE on that database, this
922  * will block us until it finishes (and has committed its update of
923  * pg_database).
924  *
925  * Note that the lock is not held long, only until the end of this startup
926  * transaction. This is OK since we will advertise our use of the
927  * database in the ProcArray before dropping the lock (in fact, that's the
928  * next thing to do). Anyone trying a DROP DATABASE after this point will
929  * see us in the array once they have the lock. Ordering is important for
930  * this because we don't want to advertise ourselves as being in this
931  * database until we have the lock; otherwise we create what amounts to a
932  * deadlock with CountOtherDBBackends().
933  *
934  * Note: use of RowExclusiveLock here is reasonable because we envision
935  * our session as being a concurrent writer of the database. If we had a
936  * way of declaring a session as being guaranteed-read-only, we could use
937  * AccessShareLock for such sessions and thereby not conflict against
938  * CREATE DATABASE.
939  */
940  if (!bootstrap)
941  LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
943 
944  /*
945  * Now we can mark our PGPROC entry with the database ID.
946  *
947  * We assume this is an atomic store so no lock is needed; though actually
948  * things would work fine even if it weren't atomic. Anyone searching the
949  * ProcArray for this database's ID should hold the database lock, so they
950  * would not be executing concurrently with this store. A process looking
951  * for another database's ID could in theory see a chance match if it read
952  * a partially-updated databaseId value; but as long as all such searches
953  * wait and retry, as in CountOtherDBBackends(), they will certainly see
954  * the correct value on their next try.
955  */
957 
958  /*
959  * We established a catalog snapshot while reading pg_authid and/or
960  * pg_database; but until we have set up MyDatabaseId, we won't react to
961  * incoming sinval messages for unshared catalogs, so we won't realize it
962  * if the snapshot has been invalidated. Assume it's no good anymore.
963  */
965 
966  /*
967  * Recheck pg_database to make sure the target database hasn't gone away.
968  * If there was a concurrent DROP DATABASE, this ensures we will die
969  * cleanly without creating a mess.
970  */
971  if (!bootstrap)
972  {
973  HeapTuple tuple;
974 
975  tuple = GetDatabaseTuple(dbname);
976  if (!HeapTupleIsValid(tuple) ||
977  MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
978  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
979  ereport(FATAL,
980  (errcode(ERRCODE_UNDEFINED_DATABASE),
981  errmsg("database \"%s\" does not exist", dbname),
982  errdetail("It seems to have just been dropped or renamed.")));
983  }
984 
985  /*
986  * Now we should be able to access the database directory safely. Verify
987  * it's there and looks reasonable.
988  */
990 
991  if (!bootstrap)
992  {
993  if (access(fullpath, F_OK) == -1)
994  {
995  if (errno == ENOENT)
996  ereport(FATAL,
997  (errcode(ERRCODE_UNDEFINED_DATABASE),
998  errmsg("database \"%s\" does not exist",
999  dbname),
1000  errdetail("The database subdirectory \"%s\" is missing.",
1001  fullpath)));
1002  else
1003  ereport(FATAL,
1005  errmsg("could not access directory \"%s\": %m",
1006  fullpath)));
1007  }
1008 
1009  ValidatePgVersion(fullpath);
1010  }
1011 
1012  SetDatabasePath(fullpath);
1013 
1014  /*
1015  * It's now possible to do real access to the system catalogs.
1016  *
1017  * Load relcache entries for the system catalogs. This must create at
1018  * least the minimum set of "nailed-in" cache entries.
1019  */
1021 
1022  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1023  initialize_acl();
1024 
1025  /*
1026  * Re-read the pg_database row for our database, check permissions and set
1027  * up database-specific GUC settings. We can't do this until all the
1028  * database-access infrastructure is up. (Also, it wants to know if the
1029  * user is a superuser, so the above stuff has to happen first.)
1030  */
1031  if (!bootstrap)
1032  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1033 
1034  /*
1035  * Now process any command-line switches and any additional GUC variable
1036  * settings passed in the startup packet. We couldn't do this before
1037  * because we didn't know if client is a superuser.
1038  */
1039  if (MyProcPort != NULL)
1040  process_startup_options(MyProcPort, am_superuser);
1041 
1042  /* Process pg_db_role_setting options */
1044 
1045  /* Apply PostAuthDelay as soon as we've read all options */
1046  if (PostAuthDelay > 0)
1047  pg_usleep(PostAuthDelay * 1000000L);
1048 
1049  /*
1050  * Initialize various default states that can't be set up until we've
1051  * selected the active user and gotten the right GUC settings.
1052  */
1053 
1054  /* set default namespace search path */
1056 
1057  /* initialize client encoding */
1059 
1060  /* Initialize this backend's session state. */
1062 
1063  /* report this backend in the PgBackendStatus array */
1064  if (!bootstrap)
1065  pgstat_bestart();
1066 
1067  /* close the transaction we started above */
1068  if (!bootstrap)
1070 }
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1241
int errhint(const char *fmt,...)
Definition: elog.c:1156
BackendId MyBackendId
Definition: globals.c:84
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
struct Port * MyProcPort
Definition: globals.c:46
CAC_state canAcceptConnections
Definition: libpq-be.h:138
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:257
#define DEBUG3
Definition: elog.h:23
Oid GetUserId(void)
Definition: miscinit.c:495
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
PGPROC * MyProc
Definition: proc.c:68
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:96
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void CommitTransactionCommand(void)
Definition: xact.c:2953
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:908
void InitializeSession(void)
Definition: session.c:54
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1547
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3811
static void PerformAuthentication(Port *port)
Definition: postinit.c:185
static void LockTimeoutHandler(void)
Definition: postinit.c:1215
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
void initialize_acl(void)
Definition: acl.c:4648
void pgstat_bestart(void)
bool RecoveryInProgress(void)
Definition: xlog.c:8328
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
Oid GetSessionUserId(void)
Definition: miscinit.c:529
bool HaveNFreeProcs(int n)
Definition: proc.c:676
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:305
bool IsBinaryUpgrade
Definition: globals.c:113
Oid MyDatabaseTableSpace
Definition: globals.c:90
bool IsBackgroundWorker
Definition: globals.c:114
void RelationCacheInitializePhase3(void)
Definition: relcache.c:3870
#define NAMEDATALEN
bool am_walsender
Definition: walsender.c:115
void pg_usleep(long microsec)
Definition: signal.c:53
int ReservedBackends
Definition: postmaster.c:217
#define FATAL
Definition: elog.h:49
void InitializeSearchPath(void)
Definition: namespace.c:4369
int MaxBackends
Definition: globals.c:139
bool IsUnderPostmaster
Definition: globals.c:112
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
void pgstat_beinit(void)
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1225
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
Oid databaseId
Definition: proc.h:154
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1252
void StartupXLOG(void)
Definition: xlog.c:6617
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3410
const char * username
Definition: pgbench.c:282
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
void SetDatabasePath(const char *path)
Definition: miscinit.c:308
#define WARNING
Definition: elog.h:40
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:8744
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:139
#define InvalidBackendId
Definition: backendid.h:23
bool am_db_walsender
Definition: walsender.c:118
Oid MyDatabaseId
Definition: globals.c:88
int PostAuthDelay
Definition: postgres.c:103
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
void EnablePortalManager(void)
Definition: portalmem.c:104
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1176
#define ereport(elevel,...)
Definition: elog.h:157
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:469
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3404
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:797
void StartTransactionCommand(void)
Definition: xact.c:2852
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:887
#define XACT_READ_COMMITTED
Definition: xact.h:37
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1233
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:694
char * dbname
Definition: streamutil.c:51
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1077
int XactIsoLevel
Definition: xact.c:76
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:676
void InitializeClientEncoding(void)
Definition: mbutils.c:281
void InitPlanCache(void)
Definition: plancache.c:127
void InitProcessPhase2(void)
Definition: proc.c:482
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406
void RelationCacheInitialize(void)
Definition: relcache.c:3775
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:161
void InitCatalogCache(void)
Definition: syscache.c:1021
static void StatementTimeoutHandler(void)
Definition: postinit.c:1193
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:834
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1142
void CheckDeadLockAlert(void)
Definition: proc.c:1871

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 94 of file miscinit.c.

References BlockSig, elog, FATAL, InitializeLatchSupport(), InitializeLatchWaitSet(), InitLatch(), InitProcessGlobals(), IsUnderPostmaster, LocalLatchData, MyLatch, on_exit_reset(), PG_SETMASK, pgwin32_signal_initialize(), PostmasterDeathSignalInit(), pqinitmask(), pqsignal(), set_stack_base(), SignalHandlerForCrashExit(), and SIGQUIT.

Referenced by BackendRun(), BackendStartup(), do_start_bgworker(), pgstat_start(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

95 {
96  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
97 
98  /*
99  * Start our win32 signal implementation. This has to be done after we
100  * read the backend variables, because we need to pick up the signal pipe
101  * from the parent process.
102  */
103 #ifdef WIN32
105 #endif
106 
107  /*
108  * Set reference point for stack-depth checking. We re-do that even in the
109  * !EXEC_BACKEND case, because there are some edge cases where processes
110  * are started with an alternative stack (e.g. starting bgworkers when
111  * running postgres using the rr debugger, as bgworkers are launched from
112  * signal handlers).
113  */
114  set_stack_base();
115 
117 
118  /*
119  * make sure stderr is in binary mode before anything can possibly be
120  * written to it, in case it's actually the syslogger pipe, so the pipe
121  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
122  * redirection (e.g. via pg_ctl -l) anyway.
123  */
124 #ifdef WIN32
125  _setmode(fileno(stderr), _O_BINARY);
126 #endif
127 
128  /* We don't want the postmaster's proc_exit() handlers */
129  on_exit_reset();
130 
131  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
132 #ifdef EXEC_BACKEND
133  pqinitmask();
134 #endif
135 
136  /* Initialize process-local latch support */
141 
142  /*
143  * If possible, make this process a group leader, so that the postmaster
144  * can signal any child processes too. Not all processes will have
145  * children, but for consistency we make all postmaster child processes do
146  * this.
147  */
148 #ifdef HAVE_SETSID
149  if (setsid() < 0)
150  elog(FATAL, "setsid() failed: %m");
151 #endif
152 
153  /*
154  * Every postmaster child process is expected to respond promptly to
155  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
156  * BlockSig and install a suitable signal handler. (Client-facing
157  * processes may choose to replace this default choice of handler with
158  * quickdie().) All other blockable signals remain blocked for now.
159  */
161 
162  sigdelset(&BlockSig, SIGQUIT);
164 
165  /* Request a signal if the postmaster dies, if possible. */
167 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3416
#define SIGQUIT
Definition: win32_port.h:168
void pgwin32_signal_initialize(void)
Definition: signal.c:69
void InitLatch(Latch *latch)
Definition: latch.c:338
void InitProcessGlobals(void)
Definition: postmaster.c:2676
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pqinitmask(void)
Definition: pqsignal.c:41
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:72
void on_exit_reset(void)
Definition: ipc.c:412
static Latch LocalLatchData
Definition: miscinit.c:67
#define FATAL
Definition: elog.h:49
bool IsUnderPostmaster
Definition: globals.c:112
sigset_t BlockSig
Definition: pqsignal.c:22
void InitializeLatchSupport(void)
Definition: latch.c:192
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
void InitializeLatchWaitSet(void)
Definition: latch.c:290
#define elog(elevel,...)
Definition: elog.h:232
struct Latch * MyLatch
Definition: globals.c:57
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:405

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 175 of file miscinit.c.

References Assert, BlockSig, elog, FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitLatch(), InitProcessGlobals(), IsPostmasterEnvironment, LocalLatchData, my_exec_path, MyLatch, PG_SETMASK, pgwin32_signal_initialize(), pkglib_path, and pqinitmask().

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

176 {
178 
179  /*
180  * Start our win32 signal implementation
181  */
182 #ifdef WIN32
184 #endif
185 
187 
188  /* Initialize process-local latch support */
193 
194  /*
195  * For consistency with InitPostmasterChild, initialize signal mask here.
196  * But we don't unblock SIGQUIT or provide a default handler for it.
197  */
198  pqinitmask();
200 
201  /* Compute paths, no postmaster to inherit from */
202  if (my_exec_path[0] == '\0')
203  {
204  if (find_my_exec(argv0, my_exec_path) < 0)
205  elog(FATAL, "%s: could not locate my own executable path",
206  argv0);
207  }
208 
209  if (pkglib_path[0] == '\0')
211 }
bool IsPostmasterEnvironment
Definition: globals.c:111
static char * argv0
Definition: pg_ctl.c:97
void pgwin32_signal_initialize(void)
Definition: signal.c:69
void InitLatch(Latch *latch)
Definition: latch.c:338
void InitProcessGlobals(void)
Definition: postmaster.c:2676
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pqinitmask(void)
Definition: pqsignal.c:41
static Latch LocalLatchData
Definition: miscinit.c:67
#define FATAL
Definition: elog.h:49
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:127
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
sigset_t BlockSig
Definition: pqsignal.c:22
void InitializeLatchSupport(void)
Definition: latch.c:192
#define Assert(condition)
Definition: c.h:804
void InitializeLatchWaitSet(void)
Definition: latch.c:290
#define elog(elevel,...)
Definition: elog.h:232
struct Latch * MyLatch
Definition: globals.c:57
char pkglib_path[MAXPGPATH]
Definition: globals.c:76

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 618 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), is_admin_of_role(), and set_config_option().

619 {
621 }
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 636 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

637 {
639 }
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:313

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1700 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1701 {
1702 #ifdef ENABLE_NLS
1703  if (my_exec_path[0] != '\0')
1704  {
1705  char locale_path[MAXPGPATH];
1706 
1707  get_locale_path(my_exec_path, locale_path);
1708  bindtextdomain(domain, locale_path);
1709  pg_bind_textdomain_codeset(domain);
1710  }
1711 #endif
1712 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767

◆ pg_split_opts()

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

Definition at line 430 of file postinit.c.

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

Referenced by process_startup_options().

431 {
432  StringInfoData s;
433 
434  initStringInfo(&s);
435 
436  while (*optstr)
437  {
438  bool last_was_escape = false;
439 
440  resetStringInfo(&s);
441 
442  /* skip over leading space */
443  while (isspace((unsigned char) *optstr))
444  optstr++;
445 
446  if (*optstr == '\0')
447  break;
448 
449  /*
450  * Parse a single option, stopping at the first space, unless it's
451  * escaped.
452  */
453  while (*optstr)
454  {
455  if (isspace((unsigned char) *optstr) && !last_was_escape)
456  break;
457 
458  if (!last_was_escape && *optstr == '\\')
459  last_was_escape = true;
460  else
461  {
462  last_was_escape = false;
463  appendStringInfoChar(&s, *optstr);
464  }
465 
466  optstr++;
467  }
468 
469  /* now store the option in the next argv[] position */
470  argv[(*argcp)++] = pstrdup(s.data);
471  }
472 
473  pfree(s.data);
474 }
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void pfree(void *pointer)
Definition: mcxt.c:1169
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 445 of file utility.c.

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

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

446 {
447  if (RecoveryInProgress())
448  ereport(ERROR,
449  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
450  /* translator: %s is name of a SQL command, eg CREATE */
451  errmsg("cannot execute %s during recovery",
452  cmdname)));
453 }
int errcode(int sqlerrcode)
Definition: elog.c:698
bool RecoveryInProgress(void)
Definition: xlog.c:8328
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 426 of file utility.c.

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

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

427 {
428  if (IsInParallelMode())
429  ereport(ERROR,
430  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
431  /* translator: %s is name of a SQL command, eg CREATE */
432  errmsg("cannot execute %s during a parallel operation",
433  cmdname)));
434 }
int errcode(int sqlerrcode)
Definition: elog.c:698
bool IsInParallelMode(void)
Definition: xact.c:1013
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 408 of file utility.c.

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

Referenced by do_setval(), DoCopy(), ExecCheckXactReadOnly(), nextval_internal(), and standard_ProcessUtility().

409 {
410  if (XactReadOnly)
411  ereport(ERROR,
412  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
413  /* translator: %s is name of a SQL command, eg CREATE */
414  errmsg("cannot execute %s in a read-only transaction",
415  cmdname)));
416 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
bool XactReadOnly
Definition: xact.c:79
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1689 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1690 {
1692  "session_preload_libraries",
1693  false);
1695  "local_preload_libraries",
1696  true);
1697 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1624
char * local_preload_libraries_string
Definition: miscinit.c:1612
char * session_preload_libraries_string
Definition: miscinit.c:1610

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1676 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1677 {
1680  "shared_preload_libraries",
1681  false);
1683 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1615
char * shared_preload_libraries_string
Definition: miscinit.c:1611
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1624

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3129 of file postgres.c.

References Assert, 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_recovery_conflict(), errhint(), errmsg(), errmsg_internal(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsLogicalLauncher(), IsLogicalWorker(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, ParallelMessagePending, pgstat_report_recovery_conflict(), pq_check_connection(), proc_exit(), ProcDiePending, ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), PROCSIG_RECOVERY_CONFLICT_DATABASE, ProcSignalBarrierPending, QueryCancelHoldoffCount, QueryCancelPending, RecoveryConflictPending, RecoveryConflictReason, RecoveryConflictRetryable, STATEMENT_TIMEOUT, and whereToSendOutput.

Referenced by die().

3130 {
3131  /* OK to accept any interrupts now? */
3132  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3133  return;
3134  InterruptPending = false;
3135 
3136  if (ProcDiePending)
3137  {
3138  ProcDiePending = false;
3139  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3140  LockErrorCleanup();
3141  /* As in quickdie, don't risk sending to client during auth */
3145  ereport(FATAL,
3146  (errcode(ERRCODE_QUERY_CANCELED),
3147  errmsg("canceling authentication due to timeout")));
3148  else if (IsAutoVacuumWorkerProcess())
3149  ereport(FATAL,
3150  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3151  errmsg("terminating autovacuum process due to administrator command")));
3152  else if (IsLogicalWorker())
3153  ereport(FATAL,
3154  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3155  errmsg("terminating logical replication worker due to administrator command")));
3156  else if (IsLogicalLauncher())
3157  {
3158  ereport(DEBUG1,
3159  (errmsg_internal("logical replication launcher shutting down")));
3160 
3161  /*
3162  * The logical replication launcher can be stopped at any time.
3163  * Use exit status 1 so the background worker is restarted.
3164  */
3165  proc_exit(1);
3166  }
3168  {
3170  ereport(FATAL,
3171  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3172  errmsg("terminating connection due to conflict with recovery"),
3174  }
3175  else if (RecoveryConflictPending)
3176  {
3177  /* Currently there is only one non-retryable recovery conflict */
3180  ereport(FATAL,
3181  (errcode(ERRCODE_DATABASE_DROPPED),
3182  errmsg("terminating connection due to conflict with recovery"),
3184  }
3185  else if (IsBackgroundWorker)
3186  ereport(FATAL,
3187  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3188  errmsg("terminating background worker \"%s\" due to administrator command",
3190  else
3191  ereport(FATAL,
3192  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3193  errmsg("terminating connection due to administrator command")));
3194  }
3195 
3197  {
3199 
3200  /*
3201  * Check for lost connection and re-arm, if still configured, but not
3202  * if we've arrived back at DoingCommandRead state. We don't want to
3203  * wake up idle sessions, and they already know how to detect lost
3204  * connections.
3205  */
3207  {
3208  if (!pq_check_connection())
3209  ClientConnectionLost = true;
3210  else
3213  }
3214  }
3215 
3217  {
3218  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3219  LockErrorCleanup();
3220  /* don't send to client, we already know the connection to be dead. */
3222  ereport(FATAL,
3223  (errcode(ERRCODE_CONNECTION_FAILURE),
3224  errmsg("connection to client lost")));
3225  }
3226 
3227  /*
3228  * If a recovery conflict happens while we are waiting for input from the
3229  * client, the client is presumably just sitting idle in a transaction,
3230  * preventing recovery from making progress. Terminate the connection to
3231  * dislodge it.
3232  */
3234  {
3235  QueryCancelPending = false; /* this trumps QueryCancel */
3236  RecoveryConflictPending = false;
3237  LockErrorCleanup();
3239  ereport(FATAL,
3240  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3241  errmsg("terminating connection due to conflict with recovery"),
3243  errhint("In a moment you should be able to reconnect to the"
3244  " database and repeat your command.")));
3245  }
3246 
3247  /*
3248  * Don't allow query cancel interrupts while reading input from the
3249  * client, because we might lose sync in the FE/BE protocol. (Die
3250  * interrupts are OK, because we won't read any further messages from the
3251  * client in that case.)
3252  */
3254  {
3255  /*
3256  * Re-arm InterruptPending so that we process the cancel request as
3257  * soon as we're done reading the message. (XXX this is seriously
3258  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3259  * can't use that macro directly as the initial test in this function,
3260  * meaning that this code also creates opportunities for other bugs to
3261  * appear.)
3262  */
3263  InterruptPending = true;
3264  }
3265  else if (QueryCancelPending)
3266  {
3267  bool lock_timeout_occurred;
3268  bool stmt_timeout_occurred;
3269 
3270  QueryCancelPending = false;
3271 
3272  /*
3273  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3274  * need to clear both, so always fetch both.
3275  */
3276  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3277  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3278 
3279  /*
3280  * If both were set, we want to report whichever timeout completed
3281  * earlier; this ensures consistent behavior if the machine is slow
3282  * enough that the second timeout triggers before we get here. A tie
3283  * is arbitrarily broken in favor of reporting a lock timeout.
3284  */
3285  if (lock_timeout_occurred && stmt_timeout_occurred &&
3287  lock_timeout_occurred = false; /* report stmt timeout */
3288 
3289  if (lock_timeout_occurred)
3290  {
3291  LockErrorCleanup();
3292  ereport(ERROR,
3293  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3294  errmsg("canceling statement due to lock timeout")));
3295  }
3296  if (stmt_timeout_occurred)
3297  {
3298  LockErrorCleanup();
3299  ereport(ERROR,
3300  (errcode(ERRCODE_QUERY_CANCELED),
3301  errmsg("canceling statement due to statement timeout")));
3302  }
3304  {
3305  LockErrorCleanup();
3306  ereport(ERROR,
3307  (errcode(ERRCODE_QUERY_CANCELED),
3308  errmsg("canceling autovacuum task")));
3309  }
3311  {
3312  RecoveryConflictPending = false;
3313  LockErrorCleanup();
3315  ereport(ERROR,
3316  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3317  errmsg("canceling statement due to conflict with recovery"),
3319  }
3320 
3321  /*
3322  * If we are reading a command from the client, just ignore the cancel
3323  * request --- sending an extra error message won't accomplish
3324  * anything. Otherwise, go ahead and throw the error.
3325  */
3326  if (!DoingCommandRead)
3327  {
3328  LockErrorCleanup();
3329  ereport(ERROR,
3330  (errcode(ERRCODE_QUERY_CANCELED),
3331  errmsg("canceling statement due to user request")));
3332  }
3333  }
3334 
3336  {
3337  /*
3338  * If the GUC has been reset to zero, ignore the signal. This is
3339  * important because the GUC update itself won't disable any pending
3340  * interrupt.
3341  */
3343  ereport(FATAL,
3344  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3345  errmsg("terminating connection due to idle-in-transaction timeout")));
3346  else
3348  }
3349 
3351  {
3352  /* As above, ignore the signal if the GUC has been reset to zero. */
3353  if (IdleSessionTimeout > 0)
3354  ereport(FATAL,
3355  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3356  errmsg("terminating connection due to idle-session timeout")));
3357  else
3358  IdleSessionTimeoutPending = false;
3359  }
3360 
3363 
3366 
3369 }
volatile uint32 InterruptHoldoffCount
Definition: globals.c:39
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:763
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1156
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1041
void pgstat_report_recovery_conflict(int reason)
Definition: pgstat.c:1662
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:36
int client_connection_check_interval
Definition: postgres.c:106
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:40
void proc_exit(int code)
Definition: ipc.c:104
int errcode(int sqlerrcode)
Definition: elog.c:698
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:195
bool IsLogicalWorker(void)
Definition: worker.c:3560
bool IsBackgroundWorker
Definition: globals.c:114
int IdleSessionTimeout
Definition: proc.c:64
volatile bool ParallelMessagePending
Definition: parallel.c:115
bool ClientAuthInProgress
Definition: postmaster.c:364
bool pq_check_connection(void)
Definition: pqcomm.c:1933
#define ERROR
Definition: elog.h:46
int IdleInTransactionSessionTimeout
Definition: proc.c:63
#define FATAL
Definition: elog.h:49
void HandleParallelMessages(void)
Definition: parallel.c:1014
Definition: dest.h:89
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
volatile uint32 CritSectionCount
Definition: globals.c:41
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3410
void LockErrorCleanup(void)
Definition: proc.c:716
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:179
static bool RecoveryConflictPending
Definition: postgres.c:177
static bool RecoveryConflictRetryable
Definition: postgres.c:178
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:729
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2454
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:524
#define Assert(condition)
Definition: c.h:804
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
static bool DoingCommandRead
Definition: postgres.c:155
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
int errmsg(const char *fmt,...)
Definition: elog.c:909
bool IsLogicalLauncher(void)
Definition: launcher.c:918
CommandDest whereToSendOutput
Definition: postgres.c:92
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1475 of file miscinit.c.

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

Referenced by ServerLoop().

1476 {
1477  int fd;
1478  int len;
1479  long file_pid;
1480  char buffer[BLCKSZ];
1481 
1482  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1483  if (fd < 0)
1484  {
1485  /*
1486  * There are many foreseeable false-positive error conditions. For
1487  * safety, fail only on enumerated clearly-something-is-wrong
1488  * conditions.
1489  */
1490  switch (errno)
1491  {
1492  case ENOENT:
1493  case ENOTDIR:
1494  /* disaster */
1495  ereport(LOG,
1497  errmsg("could not open file \"%s\": %m",
1499  return false;
1500  default:
1501  /* non-fatal, at least for now */
1502  ereport(LOG,
1504  errmsg("could not open file \"%s\": %m; continuing anyway",
1506  return true;
1507  }
1508  }
1510  len = read(fd, buffer, sizeof(buffer) - 1);
1512  if (len < 0)
1513  {
1514  ereport(LOG,
1516  errmsg("could not read from file \"%s\": %m",
1518  close(fd);
1519  return true; /* treat read failure as nonfatal */
1520  }
1521  buffer[len] = '\0';
1522  close(fd);
1523  file_pid = atol(buffer);
1524  if (file_pid == getpid())
1525  return true; /* all is well */
1526 
1527  /* Trouble: someone's overwritten the lock file */
1528  ereport(LOG,
1529  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1530  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1531  return false;
1532 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
int errcode_for_file_access(void)
Definition: elog.c:721
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:258
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3447 of file postgres.c.

References stack_base_ptr.

3448 {
3449 #if defined(__ia64__) || defined(__ia64)
3450  stack_base_ptr = base.stack_base_ptr;
3451  register_stack_base_ptr = base.register_stack_base_ptr;
3452 #else
3453  stack_base_ptr = base;
3454 #endif
3455 }
char * stack_base_ptr
Definition: postgres.c:135

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )

Definition at line 3416 of file postgres.c.

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

3417 {
3418  char stack_base;
3419  pg_stack_base_t old;
3420 
3421 #if defined(__ia64__) || defined(__ia64)
3422  old.stack_base_ptr = stack_base_ptr;
3423  old.register_stack_base_ptr = register_stack_base_ptr;
3424 #else
3425  old = stack_base_ptr;
3426 #endif
3427 
3428  /* Set up reference point for stack depth checking */
3429  stack_base_ptr = &stack_base;
3430 #if defined(__ia64__) || defined(__ia64)
3431  register_stack_base_ptr = ia64_get_bsp();
3432 #endif
3433 
3434  return old;
3435 }
char * stack_base_ptr
Definition: postgres.c:135
char * pg_stack_base_t
Definition: miscadmin.h:288

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 875 of file miscinit.c.

References OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SessionUserId, SessionUserIsSuperuser, SetConfigOption(), SetOuterUserId(), and SetRoleIsActive.

Referenced by assign_role(), and ParallelWorkerMain().

876 {
877  /*
878  * Get correct info if it's SET ROLE NONE
879  *
880  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
881  * SetSessionUserId call will fix everything. This is needed since we
882  * will get called during GUC initialization.
883  */
884  if (!OidIsValid(roleid))
885  {
887  return;
888 
889  roleid = SessionUserId;
891 
892  SetRoleIsActive = false;
893  }
894  else
895  SetRoleIsActive = true;
896 
897  SetOuterUserId(roleid);
898 
899  SetConfigOption("is_superuser",
900  is_superuser ? "on" : "off",
902 }
static Oid SessionUserId
Definition: miscinit.c:476
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:514
#define OidIsValid(objectId)
Definition: c.h:710
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8110
static bool SetRoleIsActive
Definition: miscinit.c:487
static bool SessionUserIsSuperuser
Definition: miscinit.c:482
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4263

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 308 of file miscinit.c.

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

Referenced by InitPostgres().

309 {
310  /* This should happen only once per process */
313 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
char * DatabasePath
Definition: globals.c:96
#define Assert(condition)
Definition: c.h:804
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1286

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 414 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

415 {
416  char *new;
417 
418  AssertArg(dir);
419 
420  /* If presented path is relative, convert to absolute */
421  new = make_absolute_path(dir);
422 
423  if (DataDir)
424  free(DataDir);
425  DataDir = new;
426 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:806
#define free(a)
Definition: header.h:65
char * DataDir
Definition: globals.c:65

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 829 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), errmsg(), ERROR, OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

830 {
831  /* Must have authenticated already, else can't make permission check */
833 
834  if (userid != AuthenticatedUserId &&
836  ereport(ERROR,
837  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
838  errmsg("permission denied to set session authorization")));
839 
841 
842  SetConfigOption("is_superuser",
843  is_superuser ? "on" : "off",
845 }
#define AssertState(condition)
Definition: c.h:807
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8110
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:481
#define ereport(elevel,...)
Definition: elog.h:157
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4263
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:537
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 656 of file miscinit.c.

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

657 {
658  /* We throw the same error SET ROLE would. */
660  ereport(ERROR,
661  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
662  errmsg("cannot set parameter \"%s\" within security-restricted operation",
663  "role")));
664  CurrentUserId = userid;
665  if (sec_def_context)
667  else
669 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311
#define ereport(elevel,...)
Definition: elog.h:157
static Oid CurrentUserId
Definition: miscinit.c:478
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:627
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )

Definition at line 3483 of file postgres.c.

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

3484 {
3485  char stack_top_loc;
3486  long stack_depth;
3487 
3488  /*
3489  * Compute distance from reference point to my local variables
3490  */
3491  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3492 
3493  /*
3494  * Take abs value, since stacks grow up on some machines, down on others
3495  */
3496  if (stack_depth < 0)
3497  stack_depth = -stack_depth;
3498 
3499  /*
3500  * Trouble?
3501  *
3502  * The test on stack_base_ptr prevents us from erroring out if called
3503  * during process setup or in a non-backend process. Logically it should
3504  * be done first, but putting it here avoids wasting cycles during normal
3505  * cases.
3506  */
3507  if (stack_depth > max_stack_depth_bytes &&
3508  stack_base_ptr != NULL)
3509  return true;
3510 
3511  /*
3512  * On IA64 there is a separate "register" stack that requires its own
3513  * independent check. For this, we have to measure the change in the
3514  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3515  * except that we know IA64's register stack grows up.
3516  *
3517  * Note we assume that the same max_stack_depth applies to both stacks.
3518  */
3519 #if defined(__ia64__) || defined(__ia64)
3520  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3521 
3522  if (stack_depth > max_stack_depth_bytes &&
3523  register_stack_base_ptr != NULL)
3524  return true;
3525 #endif /* IA64 */
3526 
3527  return false;
3528 }
static long max_stack_depth_bytes
Definition: postgres.c:127
char * stack_base_ptr
Definition: postgres.c:135

◆ superuser()

bool superuser ( void  )

Definition at line 46 of file superuser.c.

References GetUserId(), and superuser_arg().

Referenced by AddRoleMems(), AlterForeignDataWrapper(), AlterForeignDataWrapperOwner_internal(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOpFamily(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSystemSetConfigFile(), AlterType(), AlterTypeOwner(), ATExecChangeOwner(), brin_metapage_info(), brin_page_items(), brin_page_type(), brin_revmap_data(), bt_metap(), bt_page_items_bytea(), bt_page_items_internal(), bt_page_stats_internal(), check_encoding_locale_matches(), CheckSlotPermissions(), CreateAccessMethod(), CreateCast(), CreateEventTrigger(), CreateForeignDataWrapper(), CreateFunction(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateSubscription(), CreateTableSpace(), dblink_connstr_check(), dblink_security_check(), DefineAggregate(), DefineOpClass(), DefineOpFamily(), DefineTSParser(), DefineTSTemplate(), DefineType(), DelRoleMems(), DropRole(), dummy_object_relabel(), EnableDisableTrigger(), ExecSetVariableStmt(), ExecuteDoStmt(), fmgr_security_definer(), fsm_page_contents(), 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_import_system_collations(), pg_log_backend_memory_contexts(), pg_logdir_ls(), pg_nextoid(), pg_read_file(), pg_relpages(), pg_relpagesbyid(), pg_rotate_logfile(), 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(), requireSuperuser(), sepgsql_restorecon(), set_config_by_name(), SetPGVariable(), standard_ProcessUtility(), TerminateOtherDBBackends(), tuple_data_split(), validate_option_array_item(), and wait_pid().

47 {
48  return superuser_arg(GetUserId());
49 }
Oid GetUserId(void)
Definition: miscinit.c:495
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)

Definition at line 56 of file superuser.c.

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

Referenced by AddRoleMems(), AlterEventTriggerOwner_internal(), AlterForeignDataWrapperOwner_internal(), AlterPublicationOwner_internal(), AlterSubscriptionOwner_internal(), check_conn_params(), check_object_ownership(), connect_pg_server(), DelRoleMems(), has_bypassrls_privilege(), has_createrole_privilege(), has_privs_of_role(), is_admin_of_role(), is_member_of_role(), LockGXact(), pg_class_aclmask_ext(), pg_class_ownercheck(), pg_collation_ownercheck(), pg_conversion_ownercheck(), pg_database_aclmask(), pg_database_ownercheck(), pg_event_trigger_ownercheck(), pg_extension_ownercheck(), pg_foreign_data_wrapper_aclmask(), pg_foreign_data_wrapper_ownercheck(), pg_foreign_server_aclmask(), pg_foreign_server_ownercheck(), pg_language_aclmask(), pg_language_ownercheck(), pg_largeobject_aclmask_snapshot(), pg_largeobject_ownercheck(), pg_namespace_aclmask(), pg_namespace_ownercheck(), pg_opclass_ownercheck(), pg_oper_ownercheck(), pg_opfamily_ownercheck(), pg_proc_aclmask(), pg_proc_ownercheck(), pg_publication_ownercheck(), pg_signal_backend(), pg_statistics_object_ownercheck(), pg_subscription_ownercheck(), pg_tablespace_aclmask(), pg_tablespace_ownercheck(), pg_ts_config_ownercheck(), pg_ts_dict_ownercheck(), pg_type_aclmask(), pg_type_ownercheck(), select_best_grantor(), superuser(), and TerminateOtherDBBackends().

57 {
58  bool result;
59  HeapTuple rtup;
60 
61  /* Quick out for cache hit */
62  if (OidIsValid(last_roleid) && last_roleid == roleid)
63  return last_roleid_is_super;
64 
65  /* Special escape path in case you deleted all your users. */
66  if (!IsUnderPostmaster && roleid == BOOTSTRAP_SUPERUSERID)
67  return true;
68 
69  /* OK, look up the information in pg_authid */
70  rtup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
71  if (HeapTupleIsValid(rtup))
72  {
73  result = ((Form_pg_authid) GETSTRUCT(rtup))->rolsuper;
74  ReleaseSysCache(rtup);
75  }
76  else
77  {
78  /* Report "not superuser" for invalid roleids */
79  result = false;
80  }
81 
82  /* If first time through, set up callback for cache flushes */
84  {
87  (Datum) 0);
89  }
90 
91  /* Cache the result for next time */
92  last_roleid = roleid;
93  last_roleid_is_super = result;
94 
95  return result;
96 }
static Oid last_roleid
Definition: superuser.c:35
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define OidIsValid(objectId)
Definition: c.h:710
static void RoleidCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: superuser.c:103
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
static bool last_roleid_is_super
Definition: superuser.c:36
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
bool IsUnderPostmaster
Definition: globals.c:112
bool rolsuper
Definition: pg_authid.h:35
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1498
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static bool roleid_callback_registered
Definition: superuser.c:37

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 234 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

235 {
237  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
238 
240 
241  if (FeBeWaitSet)
243  MyLatch);
244 
245  SetLatch(MyLatch);
246 }
PGPROC * MyProc
Definition: proc.c:68
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:948
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
void SetLatch(Latch *latch)
Definition: latch.c:567
Latch procLatch
Definition: proc.h:130
static Latch LocalLatchData
Definition: miscinit.c:67
#define Assert(condition)
Definition: c.h:804
struct Latch * MyLatch
Definition: globals.c:57
#define WL_LATCH_SET
Definition: latch.h:125

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 214 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

215 {
217  Assert(MyProc != NULL);
218 
220 
221  if (FeBeWaitSet)
223  MyLatch);
224 
225  /*
226  * Set the shared latch as the local one might have been set. This
227  * shouldn't normally be necessary as code is supposed to check the
228  * condition before waiting for the latch, but a bit care can't hurt.
229  */
230  SetLatch(MyLatch);
231 }
PGPROC * MyProc
Definition: proc.c:68
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:948
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
void SetLatch(Latch *latch)
Definition: latch.c:567
Latch procLatch
Definition: proc.h:130
static Latch LocalLatchData
Definition: miscinit.c:67
#define Assert(condition)
Definition: c.h:804
struct Latch * MyLatch
Definition: globals.c:57
#define WL_LATCH_SET
Definition: latch.h:125

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1319 of file miscinit.c.

References DIRECTORY_LOCK_FILE, and lfirst.

Referenced by ServerLoop().

1320 {
1321  ListCell *l;
1322 
1323  foreach(l, lock_files)
1324  {
1325  char *socketLockFile = (char *) lfirst(l);
1326 
1327  /* No need to touch the data directory lock file, we trust */
1328  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1329  continue;
1330 
1331  /* we just ignore any error here */
1332  (void) utime(socketLockFile, NULL);
1333  }
1334 }
static List * lock_files
Definition: miscinit.c:65
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define lfirst(lc)
Definition: pg_list.h:169

◆ trace_recovery()

int trace_recovery ( int  trace_level)

Definition at line 3597 of file elog.c.

References LOG, and trace_recovery_messages.

Referenced by KnownAssignedXidsRemove(), KnownAssignedXidsRemovePreceding(), LogCurrentRunningXacts(), ProcArrayApplyRecoveryInfo(), ProcessCommittedInvalidationMessages(), RecordKnownAssignedTransactionIds(), RecoveryRestartPoint(), StandbyAcquireAccessExclusiveLock(), StandbyReleaseAllLocks(), and StandbyReleaseLockList().

3598 {
3599  if (trace_level < LOG &&
3600  trace_level >= trace_recovery_messages)
3601  return LOG;
3602 
3603  return trace_level;
3604 }
#define LOG
Definition: elog.h:26
int trace_recovery_messages
Definition: guc.c:605

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1547 of file miscinit.c.

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

Referenced by checkDataDir(), and InitPostgres().

1548 {
1549  char full_path[MAXPGPATH];
1550  FILE *file;
1551  int ret;
1552  long file_major;
1553  long my_major;
1554  char *endptr;
1555  char file_version_string[64];
1556  const char *my_version_string = PG_VERSION;
1557 
1558  my_major = strtol(my_version_string, &endptr, 10);
1559 
1560  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1561 
1562  file = AllocateFile(full_path, "r");
1563  if (!file)
1564  {
1565  if (errno == ENOENT)
1566  ereport(FATAL,
1567  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1568  errmsg("\"%s\" is not a valid data directory",
1569  path),
1570  errdetail("File \"%s\" is missing.", full_path)));
1571  else
1572  ereport(FATAL,
1574  errmsg("could not open file \"%s\": %m", full_path)));
1575  }
1576 
1577  file_version_string[0] = '\0';
1578  ret = fscanf(file, "%63s", file_version_string);
1579  file_major = strtol(file_version_string, &endptr, 10);
1580 
1581  if (ret != 1 || endptr == file_version_string)
1582  ereport(FATAL,
1583  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1584  errmsg("\"%s\" is not a valid data directory",
1585  path),
1586  errdetail("File \"%s\" does not contain valid data.",
1587  full_path),
1588  errhint("You might need to initdb.")));
1589 
1590  FreeFile(file);
1591 
1592  if (my_major != file_major)
1593  ereport(FATAL,
1594  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1595  errmsg("database files are incompatible with server"),
1596  errdetail("The data directory was initialized by PostgreSQL version %s, "
1597  "which is not compatible with this version %s.",
1598  file_version_string, my_version_string)));
1599 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
#define FATAL
Definition: elog.h:49
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2459
#define ereport(elevel,...)
Definition: elog.h:157
int FreeFile(FILE *file)
Definition: fd.c:2658
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define snprintf
Definition: port.h:217

Variable Documentation

◆ allowSystemTableMods

◆ CheckClientConnectionPending

PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending

Definition at line 33 of file globals.c.

Referenced by ClientCheckTimeoutHandler(), and ProcessInterrupts().

◆ ClientConnectionLost

PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost

Definition at line 34 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode

Definition at line 71 of file globals.c.

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

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError

Definition at line 116 of file globals.c.

Referenced by errstart(), and HandleCheckpointerInterrupts().

◆ hash_mem_multiplier

PGDLLIMPORT double hash_mem_multiplier

Definition at line 125 of file globals.c.

Referenced by get_hash_memory_limit().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending

Definition at line 35 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending

Definition at line 36 of file globals.c.

Referenced by IdleSessionTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

◆ InterruptHoldoffCount

PGDLLIMPORT volatile uint32 InterruptHoldoffCount

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle

◆ IsBackgroundWorker

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster

Definition at line 112 of file globals.c.

Referenced by _PG_init(), AdvanceNextFullTransactionIdPastXid(), AutoVacuumShmemInit(), AuxiliaryProcessMain(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), compute_parallel_vacuum_workers(), createdb(), CreateLWLocks(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), dsm_attach(), dsm_create(), dsm_postmaster_startup(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForwardSyncRequest(), GetNewMultiXactId(), GetNewTransactionId(), GetQuitSignalReason(), HandleStartupProcInterrupts(), init_ps_display(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitPredicateLocks(), InitProcess(), InitSync(), LWLockAcquire(), MaintainLatestCompletedXidRecovery(), MultiXactShmemInit(), PerformRecoveryXLogAction(), PGSemaphoreCreate(), PGSharedMemoryCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_startup(), plan_create_index_workers(), PostgresMain(), PostgresSingleUserMain(), process_postgres_switches(), process_settings(), ProcKill(), readRecoverySignalFile(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), ReplicationSlotAcquire(), RequestAddinShmemSpace(), RequestNamedLWLockTranche(), SendPostmasterSignal(), SerialInit(), set_config_option(), set_config_sourcefile(), set_ps_display(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), slru_entry(), standard_planner(), start_xact_command(), StartupXLOG(), superuser_arg(), SyncScanShmemInit(), TwoPhaseShmemInit(), verify_dictoptions(), WaitLatch(), WaitLatchOrSocket(), XLogArchiveNotify(), XLogPageRead(), XLogRecGetFullXid(), and XLogWrite().

◆ local_preload_libraries_string

char* local_preload_libraries_string

Definition at line 1612 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LogMemoryContextPending

PGDLLIMPORT volatile sig_atomic_t LogMemoryContextPending

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers

Definition at line 127 of file globals.c.

Referenced by compute_parallel_vacuum_workers(), and plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers

Definition at line 138 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 60 of file miscinit.c.

◆ my_exec_path

◆ MyAuxProcType

AuxProcType MyAuxProcType

Definition at line 45 of file auxprocess.c.

Referenced by AuxiliaryProcessMain(), and pgstat_beinit().

◆ MyBackendType

◆ MyCancelKey

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId

Definition at line 88 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), ATExecDetachPartition(), AutoVacuumRequestWork(), backend_read_statsfile(), CacheInvalidateCatalog(), CacheInvalidateHeapTuple(), CacheInvalidateRelcache(), CacheInvalidateRelcacheByTuple(), check_default_table_access_method(), check_default_tablespace(), check_temp_tablespaces(), check_TSCurrentConfig(), CheckLogicalDecodingRequirements(), CheckMyDatabase(), checkSharedDependencies(), checkTempNamespaceStatus(), classIdGetDbId(), ComputeXidHorizons(), CreateDecodingContext(), CreateInitDecodingContext(), CreatePublication(), CreateSchemaCommand(), CreateSubscription(), current_database(), database_to_xml_internal(), DeconstructQualifiedName(), do_analyze_rel(), do_autovacuum(), dropdb(), DropSubscription(), Exec_ListenPreCommit(), exec_object_restorecon(), exec_replication_command(), ExecuteTruncateGuts(), ExpandColumnRefStar(), ExportSnapshot(), extension_is_trusted(), get_subscription_oid(), GetCurrentVirtualXIDs(), GetNewRelFileNode(), heap_vacuum_rel(), IdentifySystem(), ImportSnapshot(), initialize_acl(), InitializeParallelDSM(), InitPostgres(), InitTempTableNamespace(), lazy_check_wraparound_failsafe(), libpqrcv_exec(), LocalExecuteInvalidationMessage(), 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(), movedb(), perform_relmap_update(), perform_work_item(), pg_namespace_aclmask(), pg_relation_filepath(), pgss_store(), pgstat_bestart(), pgstat_drop_database(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry(), pgstat_report_analyze(), pgstat_report_checksum_failure(), pgstat_report_connect(), pgstat_report_deadlock(), pgstat_report_disconnect(), pgstat_report_recovery_conflict(), pgstat_report_stat(), pgstat_report_tempfile(), pgstat_report_vacuum(), pgstat_reset_counters(), pgstat_reset_single_counter(), pgstat_send_funcstats(), pgstat_shutdown_hook(), pgstat_vacuum_stat(), PostgresMain(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), recheck_relation_needs_vacanalyze(), ReindexMultipleTables(), RelationInitLockInfo(), RelationInitPhysicalAddr(), RelationMapFinishBootstrap(), RenameDatabase(), RenameSchema(), ReplicationSlotCreate(), roles_is_member_of(), ScanPgRelation(), sepgsql_schema_post_create(), SetLocktagRelationOid(), shdepDropOwned(), shdepReassignOwned(), SignalBackends(), transformColumnRef(), UnlockDatabaseObject(), UpdateLogicalMappings(), vac_truncate_clog(), vac_update_datfrozenxid(), vacuum_is_relation_owner(), XactLogAbortRecord(), and XactLogCommitRecord().

◆ MyDatabaseTableSpace

◆ MyLatch

PGDLLIMPORT struct Latch* MyLatch

Definition at line 57 of file globals.c.

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), avl_sigusr2_handler(), BackgroundWriterMain(), be_tls_open_server(), CheckDeadLockAlert(), CheckpointerMain(), ClientCheckTimeoutHandler(), ConditionVariableTimedSleep(), copy_read_data(), die(), do_pg_stop_backup(), gather_readnext(), handle_sig_alarm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), initialize_worker_spi(), InitializeLatchWaitSet(), InitPostmasterChild(), InitStandaloneProcess(), lazy_truncate_heap(), libpqrcv_connect(), libpqrcv_PQgetResult(), logicalrep_worker_stop(), LogicalRepApplyLoop(), mq_putmessage(), pg_promote(), pg_sleep(), pg_wait_until_termination(), pgarch_MainLoop(), pgarch_waken_stop(), pgfdw_get_cleanup_result(), pgfdw_get_result(), PgstatCollectorMain(), pq_init(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), procsignal_sigusr1_handler(), ProcSleep(), ProcWaitForSignal(), read_or_wait(), RecoveryConflictInterrupt(), ReqCheckpointHandler(), secure_open_gssapi(), secure_read(), secure_write(), shm_mq_receive_bytes(), shm_mq_send_bytes(), shm_mq_wait_internal(), SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), sigUsr1Handler(), StatementCancelHandler(), SwitchBackToLocalLatch(), SwitchToSharedLatch(), SyncRepWaitForLSN(), SysLoggerMain(), test_shm_mq_pipelined(), throttle(), vacuum_delay_point(), wait_for_relation_state_change(), wait_for_worker_state_change(), wait_for_workers_to_become_ready(), WaitForBackgroundWorkerShutdown(), WaitForBackgroundWorkerStartup(), WaitForParallelWorkersToAttach(), WaitForParallelWorkersToFinish(), WaitForReplicationWorkerAttach(), WalRcvWaitForStartPosition(), WalReceiverMain(), WalSndLastCycleHandler(), WalSndLoop(), WalSndWaitForWal(), WalSndWriteData(), WalWriterMain(), and write_syslogger_file().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid

Definition at line 43 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(), autoprewarm_main(), AutoVacLauncherMain(), BackendRun(), CheckpointerMain(), CleanupProcSignalState(), DisownLatch(), drandom(), Exec_ListenPreCommit(), Exec_UnlistenAllCommit(), Exec_UnlistenCommit(), ExportSnapshot(), FileSetInit(), GetSerializableTransactionSnapshotInt(), HandleWalSndInitStopping(), InitAuxiliaryProcess(), InitializeLatchSupport(), InitializeParallelDSM(), InitLatch(), InitPostmasterDeathWatchHandle(), InitProcess(), InitProcessGlobals(), InitWalSenderSlot(), InvalidatePossiblyObsoleteSlot(), IsLogicalLauncher(), LaunchParallelWorkers(), llvm_compile_module(), LockBufferForCleanup(), LockTimeoutHandler(), log_line_prefix(), logicalrep_worker_launch(), ModifyWaitEvent(), OpenTemporaryFileInTablespace(), OwnLatch(), ParallelWorkerMain(), pg_backend_pid(), pgstat_bestart(), PostgresMain(), PostmasterMain(), ProcessLogMemoryContextInterrupt(), ProcSignalInit(), ProcSleep(), PublishStartupProcessInformation(), ReplicationOriginExitCleanup(), ReplicationSlotAcquire(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotsDropDBSlots(), replorigin_session_setup(), ResetLatch(), ServerLoop(), set_ps_display(), SetLatch(), setup_background_workers(), SharedInvalBackendInit(), SignalBackends(), SnapBuildSerialize(), StatementTimeoutHandler(), UnlockBuffers(), WalRcvDie(), WalReceiverMain(), worker_spi_launch(), write_csvlog(), write_pipe_chunks(), and write_relcache_init_file().

◆ MyProcPort

◆ MyStartTime

◆ MyStartTimestamp

PGDLLIMPORT TimestampTz MyStartTimestamp

◆ NBuffers

PGDLLIMPORT int NBuffers

Definition at line 135 of file globals.c.

◆ OutputFileName

char OutputFileName[]

Definition at line 73 of file globals.c.

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

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ process_shared_preload_libraries_in_progress

PGDLLIMPORT bool process_shared_preload_libraries_in_progress

◆ ProcSignalBarrierPending

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount

Definition at line 40 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

◆ QueryCancelPending

◆ session_preload_libraries_string

char* session_preload_libraries_string

Definition at line 1610 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

char* shared_preload_libraries_string

Definition at line 1611 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ trace_recovery_messages

int trace_recovery_messages

Definition at line 605 of file guc.c.

Referenced by StartupXLOG(), and trace_recovery().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

◆ VacuumCostLimit

◆ VacuumCostPageDirty

int VacuumCostPageDirty

Definition at line 143 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

int VacuumCostPageHit

Definition at line 141 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

int VacuumCostPageMiss

Definition at line 142 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumPageDirty

int64 VacuumPageDirty

◆ VacuumPageHit

int64 VacuumPageHit

◆ VacuumPageMiss

int64 VacuumPageMiss

◆ work_mem

PGDLLIMPORT int work_mem

Definition at line 124 of file globals.c.

Referenced by _bt_parallel_scan_and_sort(), _bt_pendingfsm_init(), _bt_spools_heapscan(), adjust_foreign_grouping_path_cost(), begin_partition(), brin_page_items(), choose_hashed_setop(), collectMatchBitmap(), compute_bitmap_pages(), connectby(), cost_append(), cost_material(), cost_rescan(), create_gather_merge_path(), create_groupingsets_path(), create_incremental_sort_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), CreateWorkExprContext(), crosstab(), dblink_get_notify(), deflist_to_tuplestore(), each_worker(), each_worker_jsonb(), elements_worker(), elements_worker_jsonb(), exec_init_tuple_store(), ExecIncrementalSort(), ExecInitCteScan(), ExecInitRecursiveUnion(), ExecMakeTableFunctionResult(), ExecMaterial(), ExecRecursiveUnion(), ExecSort(), final_cost_mergejoin(), fmgr_sql(), get_crosstab_tuplestore(), get_hash_memory_limit(), GetCurrentFDWTuplestore(), ginInsertCleanup(), gist_page_items(), gist_page_items_bytea(), initial_cost_mergejoin(), initialize_aggregate(), initialize_phase(), label_sort_with_costsize(), libpqrcv_processTuples(), MakeTransitionCaptureState(), materializeResult(), MultiExecBitmapIndexScan(), MultiExecBitmapOr(), ordered_set_startup(), pg_available_extension_versions(), pg_available_extensions(), pg_config(), pg_cursor(), pg_event_trigger_ddl_commands(), pg_event_trigger_dropped_objects(), pg_extension_update_paths(), pg_get_backend_memory_contexts(), pg_get_replication_slots(), pg_get_shmem_allocations(), pg_hba_file_rules(), pg_logdir_ls_internal(), pg_logical_slot_get_changes_guts(), pg_ls_dir(), pg_ls_dir_files(), pg_prepared_statement(), pg_show_replication_origin_status(), pg_stat_get_activity(), pg_stat_get_progress_info(), pg_stat_get_slru(), pg_stat_get_subscription(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pg_stop_backup_v2(), pg_tablespace_databases(), pg_timezone_names(), pgrowlocks(), plperl_return_next_internal(), pltcl_init_tuple_store(), populate_recordset_worker(), PortalCreateHoldStore(), postgres_fdw_get_connections(), show_all_file_settings(), storeRow(), switchToPresortedPrefixMode(), text_to_table(), tfuncFetchRows(), verify_heapam(), and xpath_table().