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
 
typedef void(* shmem_request_hook_type) (void)
 

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_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 process_shmem_requests (void)
 
void pg_bindtextdomain (const char *domain)
 
bool has_rolreplication (Oid roleid)
 
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 IdleStatsUpdateTimeoutPending
 
PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
 
PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
 
PGDLLIMPORT volatile uint32 InterruptHoldoffCount
 
PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
 
PGDLLIMPORT volatile uint32 CritSectionCount
 
PGDLLIMPORT pid_t PostmasterPid
 
PGDLLIMPORT bool IsPostmasterEnvironment
 
PGDLLIMPORT bool IsUnderPostmaster
 
PGDLLIMPORT bool 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
 
PGDLLIMPORT int32 MyCancelKey
 
PGDLLIMPORT int MyPMChildSlot
 
PGDLLIMPORT char OutputFileName []
 
PGDLLIMPORT char my_exec_path []
 
PGDLLIMPORT char pkglib_path []
 
PGDLLIMPORT Oid MyDatabaseId
 
PGDLLIMPORT Oid MyDatabaseTableSpace
 
PGDLLIMPORT int DateStyle
 
PGDLLIMPORT int DateOrder
 
PGDLLIMPORT int IntervalStyle
 
PGDLLIMPORT bool enableFsync
 
PGDLLIMPORT bool allowSystemTableMods
 
PGDLLIMPORT int work_mem
 
PGDLLIMPORT double hash_mem_multiplier
 
PGDLLIMPORT int maintenance_work_mem
 
PGDLLIMPORT int max_parallel_maintenance_workers
 
PGDLLIMPORT int VacuumCostPageHit
 
PGDLLIMPORT int VacuumCostPageMiss
 
PGDLLIMPORT int VacuumCostPageDirty
 
PGDLLIMPORT int VacuumCostLimit
 
PGDLLIMPORT double VacuumCostDelay
 
PGDLLIMPORT int64 VacuumPageHit
 
PGDLLIMPORT int64 VacuumPageMiss
 
PGDLLIMPORT int64 VacuumPageDirty
 
PGDLLIMPORT int VacuumCostBalance
 
PGDLLIMPORT bool VacuumCostActive
 
PGDLLIMPORT int trace_recovery_messages
 
PGDLLIMPORT char * DatabasePath
 
PGDLLIMPORT BackendType MyBackendType
 
PGDLLIMPORT ProcessingMode Mode
 
PGDLLIMPORT AuxProcType MyAuxProcType
 
PGDLLIMPORT bool IgnoreSystemIndexes
 
PGDLLIMPORT bool process_shared_preload_libraries_in_progress
 
PGDLLIMPORT bool process_shared_preload_libraries_done
 
PGDLLIMPORT bool process_shmem_requests_in_progress
 
PGDLLIMPORT char * session_preload_libraries_string
 
PGDLLIMPORT char * shared_preload_libraries_string
 
PGDLLIMPORT char * local_preload_libraries_string
 
PGDLLIMPORT shmem_request_hook_type shmem_request_hook
 

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.

◆ AmCheckpointerProcess

#define AmCheckpointerProcess ( )    (MyAuxProcType == CheckpointerProcess)

Definition at line 447 of file miscadmin.h.

◆ AmStartupProcess

#define AmStartupProcess ( )    (MyAuxProcType == StartupProcess)

Definition at line 444 of file miscadmin.h.

◆ AmWalReceiverProcess

#define AmWalReceiverProcess ( )    (MyAuxProcType == WalReceiverProcess)

Definition at line 449 of file miscadmin.h.

◆ 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:112

Definition at line 121 of file miscadmin.h.

◆ DATEORDER_DMY

#define DATEORDER_DMY   1

Definition at line 237 of file miscadmin.h.

◆ DATEORDER_MDY

#define DATEORDER_MDY   2

Definition at line 238 of file miscadmin.h.

◆ DATEORDER_YMD

#define DATEORDER_YMD   0

Definition at line 236 of file miscadmin.h.

◆ END_CRIT_SECTION

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

Definition at line 150 of file miscadmin.h.

◆ GetProcessingMode

#define GetProcessingMode ( )    Mode

Definition at line 410 of file miscadmin.h.

◆ HOLD_CANCEL_INTERRUPTS

#define HOLD_CANCEL_INTERRUPTS ( )    (QueryCancelHoldoffCount++)

Definition at line 140 of file miscadmin.h.

◆ HOLD_INTERRUPTS

#define HOLD_INTERRUPTS ( )    (InterruptHoldoffCount++)

Definition at line 132 of file miscadmin.h.

◆ INTERRUPTS_CAN_BE_PROCESSED

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

Definition at line 128 of file miscadmin.h.

◆ INTERRUPTS_PENDING_CONDITION

#define INTERRUPTS_PENDING_CONDITION ( )     (unlikely(InterruptPending))

Definition at line 112 of file miscadmin.h.

◆ INTSTYLE_ISO_8601

#define INTSTYLE_ISO_8601   3

Definition at line 253 of file miscadmin.h.

◆ INTSTYLE_POSTGRES

#define INTSTYLE_POSTGRES   0

Definition at line 250 of file miscadmin.h.

◆ INTSTYLE_POSTGRES_VERBOSE

#define INTSTYLE_POSTGRES_VERBOSE   1

Definition at line 251 of file miscadmin.h.

◆ INTSTYLE_SQL_STANDARD

#define INTSTYLE_SQL_STANDARD   2

Definition at line 252 of file miscadmin.h.

◆ InvalidPid

#define InvalidPid   (-1)

Definition at line 32 of file miscadmin.h.

◆ IsBootstrapProcessingMode

#define IsBootstrapProcessingMode ( )    (Mode == BootstrapProcessing)

Definition at line 406 of file miscadmin.h.

◆ IsInitProcessingMode

#define IsInitProcessingMode ( )    (Mode == InitProcessing)

Definition at line 407 of file miscadmin.h.

◆ IsNormalProcessingMode

#define IsNormalProcessingMode ( )    (Mode == NormalProcessing)

Definition at line 408 of file miscadmin.h.

◆ MAXTZLEN

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

Definition at line 257 of file miscadmin.h.

◆ RESUME_CANCEL_INTERRUPTS

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

Definition at line 142 of file miscadmin.h.

◆ RESUME_INTERRUPTS

#define RESUME_INTERRUPTS ( )
Value:
do { \
Assert(InterruptHoldoffCount > 0); \
InterruptHoldoffCount--; \
} while(0)

Definition at line 134 of file miscadmin.h.

◆ SECURITY_LOCAL_USERID_CHANGE

#define SECURITY_LOCAL_USERID_CHANGE   0x0001

Definition at line 312 of file miscadmin.h.

◆ SECURITY_NOFORCE_RLS

#define SECURITY_NOFORCE_RLS   0x0004

Definition at line 314 of file miscadmin.h.

◆ SECURITY_RESTRICTED_OPERATION

#define SECURITY_RESTRICTED_OPERATION   0x0002

Definition at line 313 of file miscadmin.h.

◆ SetProcessingMode

#define SetProcessingMode (   mode)
Value:
do { \
AssertArg((mode) == BootstrapProcessing || \
(mode) == InitProcessing || \
Mode = (mode); \
} while(0)
@ NormalProcessing
Definition: miscadmin.h:401
@ InitProcessing
Definition: miscadmin.h:400
@ BootstrapProcessing
Definition: miscadmin.h:399
static PgChecksumMode mode
Definition: pg_checksums.c:65

Definition at line 412 of file miscadmin.h.

◆ START_CRIT_SECTION

#define START_CRIT_SECTION ( )    (CritSectionCount++)

Definition at line 148 of file miscadmin.h.

◆ USE_GERMAN_DATES

#define USE_GERMAN_DATES   3

Definition at line 232 of file miscadmin.h.

◆ USE_ISO_DATES

#define USE_ISO_DATES   1

Definition at line 230 of file miscadmin.h.

◆ USE_POSTGRES_DATES

#define USE_POSTGRES_DATES   0

Definition at line 229 of file miscadmin.h.

◆ USE_SQL_DATES

#define USE_SQL_DATES   2

Definition at line 231 of file miscadmin.h.

◆ USE_XSD_DATES

#define USE_XSD_DATES   4

Definition at line 233 of file miscadmin.h.

Typedef Documentation

◆ BackendType

typedef enum BackendType BackendType

◆ pg_stack_base_t

typedef char* pg_stack_base_t

Definition at line 289 of file miscadmin.h.

◆ ProcessingMode

◆ shmem_request_hook_type

typedef void(* shmem_request_hook_type) (void)

Definition at line 486 of file miscadmin.h.

Enumeration Type Documentation

◆ AuxProcType

Enumerator
NotAnAuxProcess 
StartupProcess 
BgWriterProcess 
ArchiverProcess 
CheckpointerProcess 
WalWriterProcess 
WalReceiverProcess 
NUM_AUXPROCTYPES 

Definition at line 429 of file miscadmin.h.

430 {
431  NotAnAuxProcess = -1,
432  StartupProcess = 0,
438 
439  NUM_AUXPROCTYPES /* Must be last! */
440 } AuxProcType;
AuxProcType
Definition: miscadmin.h:430
@ BgWriterProcess
Definition: miscadmin.h:433
@ StartupProcess
Definition: miscadmin.h:432
@ NUM_AUXPROCTYPES
Definition: miscadmin.h:439
@ NotAnAuxProcess
Definition: miscadmin.h:431
@ ArchiverProcess
Definition: miscadmin.h:434
@ WalWriterProcess
Definition: miscadmin.h:436
@ WalReceiverProcess
Definition: miscadmin.h:437
@ CheckpointerProcess
Definition: miscadmin.h:435

◆ 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_LOGGER 

Definition at line 324 of file miscadmin.h.

325 {
326  B_INVALID = 0,
329  B_BACKEND,
330  B_BG_WORKER,
331  B_BG_WRITER,
333  B_STARTUP,
335  B_WAL_SENDER,
336  B_WAL_WRITER,
337  B_ARCHIVER,
338  B_LOGGER,
339 } BackendType;
BackendType
Definition: miscadmin.h:325
@ B_WAL_WRITER
Definition: miscadmin.h:336
@ B_WAL_RECEIVER
Definition: miscadmin.h:334
@ B_CHECKPOINTER
Definition: miscadmin.h:332
@ B_WAL_SENDER
Definition: miscadmin.h:335
@ B_LOGGER
Definition: miscadmin.h:338
@ B_STARTUP
Definition: miscadmin.h:333
@ B_BG_WORKER
Definition: miscadmin.h:330
@ B_INVALID
Definition: miscadmin.h:326
@ B_BG_WRITER
Definition: miscadmin.h:331
@ B_BACKEND
Definition: miscadmin.h:329
@ B_ARCHIVER
Definition: miscadmin.h:337
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:327
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:328

◆ 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:398

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1350 of file miscinit.c.

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

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), len, LOG, PG_BINARY, pg_fsync(), pg_pwrite(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf, generate_unaccent_rules::str, 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().

◆ BaseInit()

void BaseInit ( void  )

Definition at line 573 of file postinit.c.

574 {
575  Assert(MyProc != NULL);
576 
577  /*
578  * Initialize our input/output/debugging file descriptors.
579  */
580  DebugFileOpen();
581 
582  /*
583  * Initialize file access. Done early so other subsystems can access
584  * files.
585  */
586  InitFileAccess();
587 
588  /*
589  * Initialize statistics reporting. This needs to happen early to ensure
590  * that pgstat's shutdown callback runs after the shutdown callbacks of
591  * all subsystems that can produce stats (like e.g. transaction commits
592  * can).
593  */
595 
596  /* Do local initialization of storage and buffer managers */
597  InitSync();
598  smgrinit();
600 
601  /*
602  * Initialize temporary file access after pgstat, so that the temporary
603  * file shutdown hook can report temporary file statistics.
604  */
606 
607  /*
608  * Initialize local buffers for WAL record construction, in case we ever
609  * try to insert XLOG.
610  */
611  InitXLogInsert();
612 
613  /*
614  * Initialize replication slots after pgstat. The exit hook might need to
615  * drop ephemeral slots, which in turn triggers stats reporting.
616  */
618 }
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2604
void DebugFileOpen(void)
Definition: elog.c:1917
void InitFileAccess(void)
Definition: fd.c:883
void InitTemporaryFileAccess(void)
Definition: fd.c:913
Assert(fmt[strlen(fmt) - 1] !='\n')
void pgstat_initialize(void)
Definition: pgstat.c:523
void ReplicationSlotInitialize(void)
Definition: slot.c:169
void smgrinit(void)
Definition: smgr.c:111
PGPROC * MyProc
Definition: proc.c:68
void InitSync(void)
Definition: sync.c:131
void InitXLogInsert(void)
Definition: xloginsert.c:1284

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

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

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 431 of file miscinit.c.

432 {
434 
435  if (chdir(DataDir) < 0)
436  ereport(FATAL,
438  errmsg("could not change directory to \"%s\": %m",
439  DataDir)));
440 }
#define AssertState(condition)
Definition: c.h:818
#define FATAL
Definition: elog.h:35
char * DataDir
Definition: globals.c:66

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

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

◆ check_stack_depth()

void check_stack_depth ( void  )

Definition at line 3500 of file postgres.c.

3501 {
3502  if (stack_is_too_deep())
3503  {
3504  ereport(ERROR,
3505  (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3506  errmsg("stack depth limit exceeded"),
3507  errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3508  "after ensuring the platform's stack depth limit is adequate.",
3509  max_stack_depth)));
3510  }
3511 }
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
#define ERROR
Definition: elog.h:33
int max_stack_depth
Definition: postgres.c:100
bool stack_is_too_deep(void)
Definition: postgres.c:3514

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().

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 318 of file miscinit.c.

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

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 BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1294 of file miscinit.c.

1295 {
1296  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1297 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:989

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

◆ CreateSocketLockFile()

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

Definition at line 1303 of file miscinit.c.

1305 {
1306  char lockfile[MAXPGPATH];
1307 
1308  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1309  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1310 }
#define MAXPGPATH

References CreateLockFile(), MAXPGPATH, and snprintf.

◆ get_hash_memory_limit()

size_t get_hash_memory_limit ( void  )

Definition at line 3401 of file nodeHash.c.

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 }
#define Min(x, y)
Definition: c.h:997
double hash_mem_multiplier
Definition: globals.c:126
int work_mem
Definition: globals.c:125

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().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 550 of file miscinit.c.

551 {
553  return AuthenticatedUserId;
554 }
#define OidIsValid(objectId)
Definition: c.h:721
static Oid AuthenticatedUserId
Definition: miscinit.c:471

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 249 of file miscinit.c.

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_LOGGER:
292  backendDesc = "logger";
293  break;
294  }
295 
296  return backendDesc;
297 }

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_WAL_RECEIVER, B_WAL_SENDER, and B_WAL_WRITER.

Referenced by BackendInitialize(), get_backend_type_for_log(), init_ps_display(), and pg_stat_get_activity().

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 856 of file miscinit.c.

857 {
858  if (SetRoleIsActive)
859  return OuterUserId;
860  else
861  return InvalidOid;
862 }
static Oid OuterUserId
Definition: miscinit.c:473
static bool SetRoleIsActive
Definition: miscinit.c:483
#define InvalidOid
Definition: postgres_ext.h:36

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 502 of file miscinit.c.

503 {
505  return OuterUserId;
506 }

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 525 of file miscinit.c.

526 {
528  return SessionUserId;
529 }
static Oid SessionUserId
Definition: miscinit.c:472

References AssertState, OidIsValid, and SessionUserId.

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

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 491 of file miscinit.c.

492 {
494  return CurrentUserId;
495 }
static Oid CurrentUserId
Definition: miscinit.c:474

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), 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(), emit_audit_message(), 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_Parameter(), 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(), get_tables_to_cluster_partitioned(), 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_parameter_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), heap_force_common(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockViewRecurse(), LogicalRepSyncTableStart(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_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(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), ShowAllGUCConfig(), standard_ProcessUtility(), statext_is_compatible_clause(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_relation_owner(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 651 of file miscinit.c.

652 {
653  *userid = CurrentUserId;
654  *sec_def_context = InLocalUserIdChange();
655 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:620

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 912 of file miscinit.c.

913 {
914  HeapTuple tuple;
915  char *result;
916 
917  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
918  if (!HeapTupleIsValid(tuple))
919  {
920  if (!noerr)
921  ereport(ERROR,
922  (errcode(ERRCODE_UNDEFINED_OBJECT),
923  errmsg("invalid role OID: %u", roleid)));
924  result = NULL;
925  }
926  else
927  {
928  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
929  ReleaseSysCache(tuple);
930  }
931  return result;
932 }
#define NameStr(name)
Definition: c.h:692
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
char * pstrdup(const char *in)
Definition: mcxt.c:1305
NameData rolname
Definition: pg_authid.h:34
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ AUTHOID
Definition: syscache.h:45

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(), LogicalRepSyncTableStart(), regroleout(), session_user(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 678 of file miscinit.c.

679 {
680  bool result = false;
681  HeapTuple utup;
682 
683  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
684  if (HeapTupleIsValid(utup))
685  {
686  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
687  ReleaseSysCache(utup);
688  }
689  return result;
690 }
bool rolreplication
Definition: pg_authid.h:40

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

Referenced by CheckSlotPermissions(), and InitPostgres().

◆ InitializeMaxBackends()

void InitializeMaxBackends ( void  )

Definition at line 551 of file postinit.c.

552 {
553  Assert(MaxBackends == 0);
554 
555  /* the extra unit accounts for the autovacuum launcher */
558 
559  /* internal error because the values were all checked previously */
561  elog(ERROR, "too many backends configured");
562 }
int autovacuum_max_workers
Definition: autovacuum.c:116
int MaxConnections
Definition: globals.c:137
int MaxBackends
Definition: globals.c:140
int max_worker_processes
Definition: globals.c:138
#define MAX_BACKENDS
Definition: postmaster.h:75
int max_wal_senders
Definition: walsender.c:122

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

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

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  useroid 
)

Definition at line 696 of file miscinit.c.

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

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_DYNAMIC_DEFAULT, PGC_S_OVERRIDE, PointerGetDatum, ReleaseSysCache(), PGPROC::roleId, SearchSysCache1(), SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 799 of file miscinit.c.

800 {
801  /*
802  * This function should only be called in single-user mode, in autovacuum
803  * workers, and in background workers.
804  */
806 
807  /* call only once */
809 
810  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
812 
813  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
814 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3309
bool IsBackgroundWorker
Definition: globals.c:115

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

Referenced by InitPostgres().

◆ InitPostgres()

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

Definition at line 646 of file postinit.c.

648 {
649  bool bootstrap = IsBootstrapProcessingMode();
650  bool am_superuser;
651  char *fullpath;
652  char dbname[NAMEDATALEN];
653 
654  elog(DEBUG3, "InitPostgres");
655 
656  /*
657  * Add my PGPROC struct to the ProcArray.
658  *
659  * Once I have done this, I am visible to other backends!
660  */
662 
663  /*
664  * Initialize my entry in the shared-invalidation manager's array of
665  * per-backend data.
666  *
667  * Sets up MyBackendId, a unique backend identifier.
668  */
670 
671  SharedInvalBackendInit(false);
672 
673  if (MyBackendId > MaxBackends || MyBackendId <= 0)
674  elog(FATAL, "bad backend ID: %d", MyBackendId);
675 
676  /* Now that we have a BackendId, we can participate in ProcSignal */
678 
679  /*
680  * Also set up timeout handlers needed for backend operation. We need
681  * these in every case except bootstrap.
682  */
683  if (!bootstrap)
684  {
694  }
695 
696  /*
697  * If this is either a bootstrap process or a standalone backend, start up
698  * the XLOG machinery, and register to have it closed down at exit. In
699  * other cases, the startup process is responsible for starting up the
700  * XLOG machinery, and the checkpointer for closing it down.
701  */
702  if (!IsUnderPostmaster)
703  {
704  /*
705  * We don't yet have an aux-process resource owner, but StartupXLOG
706  * and ShutdownXLOG will need one. Hence, create said resource owner
707  * (and register a callback to clean it up after ShutdownXLOG runs).
708  */
710 
711  StartupXLOG();
712  /* Release (and warn about) any buffer pins leaked in StartupXLOG */
714  /* Reset CurrentResourceOwner to nothing for the moment */
715  CurrentResourceOwner = NULL;
716 
717  /*
718  * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
719  * segments etc to work (which in turn is required for pgstats).
720  */
723  }
724 
725  /*
726  * Initialize the relation cache and the system catalog caches. Note that
727  * no catalog access happens here; we only set up the hashtable structure.
728  * We must do this before starting a transaction because transaction abort
729  * would try to touch these hashtables.
730  */
733  InitPlanCache();
734 
735  /* Initialize portal manager */
737 
738  /* Initialize status reporting */
739  pgstat_beinit();
740 
741  /*
742  * Load relcache entries for the shared system catalogs. This must create
743  * at least entries for pg_database and catalogs used for authentication.
744  */
746 
747  /*
748  * Set up process-exit callback to do pre-shutdown cleanup. This is the
749  * one of the first before_shmem_exit callbacks we register; thus, this
750  * will be one the last things we do before low-level modules like the
751  * buffer manager begin to close down. We need to have this in place
752  * before we begin our first transaction --- if we fail during the
753  * initialization transaction, as is entirely possible, we need the
754  * AbortTransaction call to clean up.
755  */
757 
758  /* The autovacuum launcher is done here */
760  {
761  /* report this backend in the PgBackendStatus array */
762  pgstat_bestart();
763 
764  return;
765  }
766 
767  /*
768  * Start a new transaction here before first access to db, and get a
769  * snapshot. We don't have a use for the snapshot itself, but we're
770  * interested in the secondary effect that it sets RecentGlobalXmin. (This
771  * is critical for anything that reads heap pages, because HOT may decide
772  * to prune them even if the process doesn't attempt to modify any
773  * tuples.)
774  *
775  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
776  * not pushed/active does not reliably prevent HOT pruning (->xmin could
777  * e.g. be cleared when cache invalidations are processed).
778  */
779  if (!bootstrap)
780  {
781  /* statement_timestamp must be set for timeouts to work correctly */
784 
785  /*
786  * transaction_isolation will have been set to the default by the
787  * above. If the default is "serializable", and we are in hot
788  * standby, we will fail if we don't change it to something lower.
789  * Fortunately, "read committed" is plenty good enough.
790  */
792 
793  (void) GetTransactionSnapshot();
794  }
795 
796  /*
797  * Perform client authentication if necessary, then figure out our
798  * postgres user ID, and see if we are a superuser.
799  *
800  * In standalone mode and in autovacuum worker processes, we use a fixed
801  * ID, otherwise we figure it out from the authenticated user name.
802  */
803  if (bootstrap || IsAutoVacuumWorkerProcess())
804  {
806  am_superuser = true;
807  }
808  else if (!IsUnderPostmaster)
809  {
811  am_superuser = true;
812  if (!ThereIsAtLeastOneRole())
814  (errcode(ERRCODE_UNDEFINED_OBJECT),
815  errmsg("no roles are defined in this database system"),
816  errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
817  username != NULL ? username : "postgres")));
818  }
819  else if (IsBackgroundWorker)
820  {
821  if (username == NULL && !OidIsValid(useroid))
822  {
824  am_superuser = true;
825  }
826  else
827  {
829  am_superuser = superuser();
830  }
831  }
832  else
833  {
834  /* normal multiuser case */
835  Assert(MyProcPort != NULL);
838  am_superuser = superuser();
839  }
840 
841  /*
842  * Binary upgrades only allowed super-user connections
843  */
844  if (IsBinaryUpgrade && !am_superuser)
845  {
846  ereport(FATAL,
847  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
848  errmsg("must be superuser to connect in binary upgrade mode")));
849  }
850 
851  /*
852  * The last few connection slots are reserved for superusers. Replication
853  * connections are drawn from slots reserved with max_wal_senders and not
854  * limited by max_connections or superuser_reserved_connections.
855  */
856  if (!am_superuser && !am_walsender &&
857  ReservedBackends > 0 &&
859  ereport(FATAL,
860  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
861  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
862 
863  /* Check replication permissions needed for walsender processes. */
864  if (am_walsender)
865  {
866  Assert(!bootstrap);
867 
868  if (!superuser() && !has_rolreplication(GetUserId()))
869  ereport(FATAL,
870  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
871  errmsg("must be superuser or replication role to start walsender")));
872  }
873 
874  /*
875  * If this is a plain walsender only supporting physical replication, we
876  * don't want to connect to any particular database. Just finish the
877  * backend startup by processing any options from the startup packet, and
878  * we're done.
879  */
881  {
882  /* process any options passed in the startup packet */
883  if (MyProcPort != NULL)
884  process_startup_options(MyProcPort, am_superuser);
885 
886  /* Apply PostAuthDelay as soon as we've read all options */
887  if (PostAuthDelay > 0)
888  pg_usleep(PostAuthDelay * 1000000L);
889 
890  /* initialize client encoding */
892 
893  /* report this backend in the PgBackendStatus array */
894  pgstat_bestart();
895 
896  /* close the transaction we started above */
898 
899  return;
900  }
901 
902  /*
903  * Set up the global variables holding database id and default tablespace.
904  * But note we won't actually try to touch the database just yet.
905  *
906  * We take a shortcut in the bootstrap case, otherwise we have to look up
907  * the db's entry in pg_database.
908  */
909  if (bootstrap)
910  {
911  MyDatabaseId = Template1DbOid;
912  MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
913  }
914  else if (in_dbname != NULL)
915  {
916  HeapTuple tuple;
917  Form_pg_database dbform;
918 
919  tuple = GetDatabaseTuple(in_dbname);
920  if (!HeapTupleIsValid(tuple))
921  ereport(FATAL,
922  (errcode(ERRCODE_UNDEFINED_DATABASE),
923  errmsg("database \"%s\" does not exist", in_dbname)));
924  dbform = (Form_pg_database) GETSTRUCT(tuple);
925  MyDatabaseId = dbform->oid;
926  MyDatabaseTableSpace = dbform->dattablespace;
927  /* take database name from the caller, just for paranoia */
928  strlcpy(dbname, in_dbname, sizeof(dbname));
929  }
930  else if (OidIsValid(dboid))
931  {
932  /* caller specified database by OID */
933  HeapTuple tuple;
934  Form_pg_database dbform;
935 
936  tuple = GetDatabaseTupleByOid(dboid);
937  if (!HeapTupleIsValid(tuple))
938  ereport(FATAL,
939  (errcode(ERRCODE_UNDEFINED_DATABASE),
940  errmsg("database %u does not exist", dboid)));
941  dbform = (Form_pg_database) GETSTRUCT(tuple);
942  MyDatabaseId = dbform->oid;
943  MyDatabaseTableSpace = dbform->dattablespace;
944  Assert(MyDatabaseId == dboid);
945  strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
946  /* pass the database name back to the caller */
947  if (out_dbname)
948  strcpy(out_dbname, dbname);
949  }
950  else
951  {
952  /*
953  * If this is a background worker not bound to any particular
954  * database, we're done now. Everything that follows only makes sense
955  * if we are bound to a specific database. We do need to close the
956  * transaction we started before returning.
957  */
958  if (!bootstrap)
959  {
960  pgstat_bestart();
962  }
963  return;
964  }
965 
966  /*
967  * Now, take a writer's lock on the database we are trying to connect to.
968  * If there is a concurrently running DROP DATABASE on that database, this
969  * will block us until it finishes (and has committed its update of
970  * pg_database).
971  *
972  * Note that the lock is not held long, only until the end of this startup
973  * transaction. This is OK since we will advertise our use of the
974  * database in the ProcArray before dropping the lock (in fact, that's the
975  * next thing to do). Anyone trying a DROP DATABASE after this point will
976  * see us in the array once they have the lock. Ordering is important for
977  * this because we don't want to advertise ourselves as being in this
978  * database until we have the lock; otherwise we create what amounts to a
979  * deadlock with CountOtherDBBackends().
980  *
981  * Note: use of RowExclusiveLock here is reasonable because we envision
982  * our session as being a concurrent writer of the database. If we had a
983  * way of declaring a session as being guaranteed-read-only, we could use
984  * AccessShareLock for such sessions and thereby not conflict against
985  * CREATE DATABASE.
986  */
987  if (!bootstrap)
988  LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
990 
991  /*
992  * Now we can mark our PGPROC entry with the database ID.
993  *
994  * We assume this is an atomic store so no lock is needed; though actually
995  * things would work fine even if it weren't atomic. Anyone searching the
996  * ProcArray for this database's ID should hold the database lock, so they
997  * would not be executing concurrently with this store. A process looking
998  * for another database's ID could in theory see a chance match if it read
999  * a partially-updated databaseId value; but as long as all such searches
1000  * wait and retry, as in CountOtherDBBackends(), they will certainly see
1001  * the correct value on their next try.
1002  */
1004 
1005  /*
1006  * We established a catalog snapshot while reading pg_authid and/or
1007  * pg_database; but until we have set up MyDatabaseId, we won't react to
1008  * incoming sinval messages for unshared catalogs, so we won't realize it
1009  * if the snapshot has been invalidated. Assume it's no good anymore.
1010  */
1012 
1013  /*
1014  * Recheck pg_database to make sure the target database hasn't gone away.
1015  * If there was a concurrent DROP DATABASE, this ensures we will die
1016  * cleanly without creating a mess.
1017  */
1018  if (!bootstrap)
1019  {
1020  HeapTuple tuple;
1021 
1022  tuple = GetDatabaseTuple(dbname);
1023  if (!HeapTupleIsValid(tuple) ||
1024  MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
1025  MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
1026  ereport(FATAL,
1027  (errcode(ERRCODE_UNDEFINED_DATABASE),
1028  errmsg("database \"%s\" does not exist", dbname),
1029  errdetail("It seems to have just been dropped or renamed.")));
1030  }
1031 
1032  /*
1033  * Now we should be able to access the database directory safely. Verify
1034  * it's there and looks reasonable.
1035  */
1037 
1038  if (!bootstrap)
1039  {
1040  if (access(fullpath, F_OK) == -1)
1041  {
1042  if (errno == ENOENT)
1043  ereport(FATAL,
1044  (errcode(ERRCODE_UNDEFINED_DATABASE),
1045  errmsg("database \"%s\" does not exist",
1046  dbname),
1047  errdetail("The database subdirectory \"%s\" is missing.",
1048  fullpath)));
1049  else
1050  ereport(FATAL,
1052  errmsg("could not access directory \"%s\": %m",
1053  fullpath)));
1054  }
1055 
1056  ValidatePgVersion(fullpath);
1057  }
1058 
1059  SetDatabasePath(fullpath);
1060  pfree(fullpath);
1061 
1062  /*
1063  * It's now possible to do real access to the system catalogs.
1064  *
1065  * Load relcache entries for the system catalogs. This must create at
1066  * least the minimum set of "nailed-in" cache entries.
1067  */
1069 
1070  /* set up ACL framework (so CheckMyDatabase can check permissions) */
1071  initialize_acl();
1072 
1073  /*
1074  * Re-read the pg_database row for our database, check permissions and set
1075  * up database-specific GUC settings. We can't do this until all the
1076  * database-access infrastructure is up. (Also, it wants to know if the
1077  * user is a superuser, so the above stuff has to happen first.)
1078  */
1079  if (!bootstrap)
1080  CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1081 
1082  /*
1083  * Now process any command-line switches and any additional GUC variable
1084  * settings passed in the startup packet. We couldn't do this before
1085  * because we didn't know if client is a superuser.
1086  */
1087  if (MyProcPort != NULL)
1088  process_startup_options(MyProcPort, am_superuser);
1089 
1090  /* Process pg_db_role_setting options */
1092 
1093  /* Apply PostAuthDelay as soon as we've read all options */
1094  if (PostAuthDelay > 0)
1095  pg_usleep(PostAuthDelay * 1000000L);
1096 
1097  /*
1098  * Initialize various default states that can't be set up until we've
1099  * selected the active user and gotten the right GUC settings.
1100  */
1101 
1102  /* set default namespace search path */
1104 
1105  /* initialize client encoding */
1107 
1108  /* Initialize this backend's session state. */
1110 
1111  /* report this backend in the PgBackendStatus array */
1112  if (!bootstrap)
1113  pgstat_bestart();
1114 
1115  /* close the transaction we started above */
1116  if (!bootstrap)
1118 }
void initialize_acl(void)
Definition: acl.c:4730
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3303
void pgstat_beinit(void)
void pgstat_bestart(void)
#define InvalidBackendId
Definition: backendid.h:23
#define DEBUG3
Definition: elog.h:22
#define WARNING
Definition: elog.h:30
bool IsBinaryUpgrade
Definition: globals.c:114
BackendId MyBackendId
Definition: globals.c:85
Oid MyDatabaseTableSpace
Definition: globals.c:91
struct Port * MyProcPort
Definition: globals.c:47
Oid MyDatabaseId
Definition: globals.c:89
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define RowExclusiveLock
Definition: lockdefs.h:38
void InitializeClientEncoding(void)
Definition: mbutils.c:281
void pfree(void *pointer)
Definition: mcxt.c:1175
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:799
Oid GetUserId(void)
Definition: miscinit.c:491
Oid GetSessionUserId(void)
Definition: miscinit.c:525
void SetDatabasePath(const char *path)
Definition: miscinit.c:305
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:696
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:678
void InitializeSearchPath(void)
Definition: namespace.c:4372
#define NAMEDATALEN
FormData_pg_database * Form_pg_database
Definition: pg_database.h:87
const char * username
Definition: pgbench.c:309
void pgstat_before_server_shutdown(int code, Datum arg)
Definition: pgstat.c:448
void InitPlanCache(void)
Definition: plancache.c:127
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void EnablePortalManager(void)
Definition: portalmem.c:105
int PostAuthDelay
Definition: postgres.c:103
static void ShutdownPostgres(int code, Datum arg)
Definition: postinit.c:1224
static void IdleInTransactionSessionTimeoutHandler(void)
Definition: postinit.c:1291
static void LockTimeoutHandler(void)
Definition: postinit.c:1281
static void IdleStatsUpdateTimeoutHandler(void)
Definition: postinit.c:1307
static void process_settings(Oid databaseid, Oid roleid)
Definition: postinit.c:1190
static void IdleSessionTimeoutHandler(void)
Definition: postinit.c:1299
static void process_startup_options(Port *port, bool am_superuser)
Definition: postinit.c:1125
static void StatementTimeoutHandler(void)
Definition: postinit.c:1259
static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
Definition: postinit.c:310
static bool ThereIsAtLeastOneRole(void)
Definition: postinit.c:1326
static void PerformAuthentication(Port *port)
Definition: postinit.c:190
static void ClientCheckTimeoutHandler(void)
Definition: postinit.c:1315
static HeapTuple GetDatabaseTuple(const char *dbname)
Definition: postinit.c:101
static HeapTuple GetDatabaseTupleByOid(Oid dboid)
Definition: postinit.c:144
int ReservedBackends
Definition: postmaster.c:219
void ProcSignalInit(int pss_idx)
Definition: procsignal.c:161
void RelationCacheInitializePhase3(void)
Definition: relcache.c:3975
void RelationCacheInitialize(void)
Definition: relcache.c:3870
void RelationCacheInitializePhase2(void)
Definition: relcache.c:3916
char * GetDatabasePath(Oid dbNode, Oid spcNode)
Definition: relpath.c:110
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:907
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
void CreateAuxProcessResourceOwner(void)
Definition: resowner.c:887
void InitializeSession(void)
Definition: session.c:54
void pg_usleep(long microsec)
Definition: signal.c:53
void SharedInvalBackendInit(bool sendOnly)
Definition: sinvaladt.c:266
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
void CheckDeadLockAlert(void)
Definition: proc.c:1847
void InitProcessPhase2(void)
Definition: proc.c:480
bool HaveNFreeProcs(int n)
Definition: proc.c:659
char * dbname
Definition: streamutil.c:51
Oid databaseId
Definition: proc.h:192
bool superuser(void)
Definition: superuser.c:46
void InitCatalogCache(void)
Definition: syscache.c:1067
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:509
@ IDLE_SESSION_TIMEOUT
Definition: timeout.h:34
@ IDLE_IN_TRANSACTION_SESSION_TIMEOUT
Definition: timeout.h:33
@ LOCK_TIMEOUT
Definition: timeout.h:28
@ STATEMENT_TIMEOUT
Definition: timeout.h:29
@ DEADLOCK_TIMEOUT
Definition: timeout.h:27
@ IDLE_STATS_UPDATE_TIMEOUT
Definition: timeout.h:35
@ CLIENT_CONNECTION_CHECK_TIMEOUT
Definition: timeout.h:36
bool am_walsender
Definition: walsender.c:116
bool am_db_walsender
Definition: walsender.c:119
void StartTransactionCommand(void)
Definition: xact.c:2925
int XactIsoLevel
Definition: xact.c:78
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:886
void CommitTransactionCommand(void)
Definition: xact.c:3022
#define XACT_READ_COMMITTED
Definition: xact.h:37
void StartupXLOG(void)
Definition: xlog.c:4886
void ShutdownXLOG(int code, Datum arg)
Definition: xlog.c:6013

References am_db_walsender, am_walsender, Assert(), before_shmem_exit(), 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, IDLE_STATS_UPDATE_TIMEOUT, IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), 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(), pfree(), pg_usleep(), pgstat_before_server_shutdown(), pgstat_beinit(), pgstat_bestart(), PostAuthDelay, process_settings(), process_startup_options(), ProcSignalInit(), RegisterTimeout(), RelationCacheInitialize(), RelationCacheInitializePhase2(), RelationCacheInitializePhase3(), ReleaseAuxProcessResources(), ReservedBackends, RowExclusiveLock, SetCurrentStatementStartTimestamp(), SetDatabasePath(), SharedInvalBackendInit(), ShutdownPostgres(), ShutdownXLOG(), StartTransactionCommand(), StartupXLOG(), STATEMENT_TIMEOUT, StatementTimeoutHandler(), strlcpy(), superuser(), ThereIsAtLeastOneRole(), username, ValidatePgVersion(), WARNING, XACT_READ_COMMITTED, and XactIsoLevel.

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

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 95 of file miscinit.c.

96 {
97  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
98 
99  /*
100  * Start our win32 signal implementation. This has to be done after we
101  * read the backend variables, because we need to pick up the signal pipe
102  * from the parent process.
103  */
104 #ifdef WIN32
106 #endif
107 
108  /*
109  * Set reference point for stack-depth checking. This might seem
110  * redundant in !EXEC_BACKEND builds; but it's not because the postmaster
111  * launches its children from signal handlers, so we might be running on
112  * an alternative stack.
113  */
114  (void) 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 }
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
struct Latch * MyLatch
Definition: globals.c:58
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:77
void on_exit_reset(void)
Definition: ipc.c:412
void InitializeLatchWaitSet(void)
Definition: latch.c:305
void InitializeLatchSupport(void)
Definition: latch.c:207
void InitLatch(Latch *latch)
Definition: latch.c:353
static Latch LocalLatchData
Definition: miscinit.c:68
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:405
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3437
void InitProcessGlobals(void)
Definition: postmaster.c:2687
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pgwin32_signal_initialize(void)
Definition: signal.c:79
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
#define SIGQUIT
Definition: win32_port.h:168

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 BackendStartup(), do_start_bgworker(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 175 of file miscinit.c.

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 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:140
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
bool IsPostmasterEnvironment
Definition: globals.c:112
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
static char * argv0
Definition: pg_ctl.c:97
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879

References argv0, 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().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 620 of file miscinit.c.

621 {
623 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:312

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 638 of file miscinit.c.

639 {
641 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:314

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1719 of file miscinit.c.

1720 {
1721 #ifdef ENABLE_NLS
1722  if (my_exec_path[0] != '\0')
1723  {
1724  char locale_path[MAXPGPATH];
1725 
1726  get_locale_path(my_exec_path, locale_path);
1727  bindtextdomain(domain, locale_path);
1728  pg_bind_textdomain_codeset(domain);
1729  }
1730 #endif
1731 }
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:888

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

◆ pg_split_opts()

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

Definition at line 493 of file postinit.c.

494 {
495  StringInfoData s;
496 
497  initStringInfo(&s);
498 
499  while (*optstr)
500  {
501  bool last_was_escape = false;
502 
503  resetStringInfo(&s);
504 
505  /* skip over leading space */
506  while (isspace((unsigned char) *optstr))
507  optstr++;
508 
509  if (*optstr == '\0')
510  break;
511 
512  /*
513  * Parse a single option, stopping at the first space, unless it's
514  * escaped.
515  */
516  while (*optstr)
517  {
518  if (isspace((unsigned char) *optstr) && !last_was_escape)
519  break;
520 
521  if (!last_was_escape && *optstr == '\\')
522  last_was_escape = true;
523  else
524  {
525  last_was_escape = false;
526  appendStringInfoChar(&s, *optstr);
527  }
528 
529  optstr++;
530  }
531 
532  /* now store the option in the next argv[] position */
533  argv[(*argcp)++] = pstrdup(s.data);
534  }
535 
536  pfree(s.data);
537 }
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

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

Referenced by process_startup_options().

◆ PreventCommandDuringRecovery()

void PreventCommandDuringRecovery ( const char *  cmdname)

Definition at line 448 of file utility.c.

449 {
450  if (RecoveryInProgress())
451  ereport(ERROR,
452  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
453  /* translator: %s is name of a SQL command, eg CREATE */
454  errmsg("cannot execute %s during recovery",
455  cmdname)));
456 }
bool RecoveryInProgress(void)
Definition: xlog.c:5762

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

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

◆ PreventCommandIfParallelMode()

void PreventCommandIfParallelMode ( const char *  cmdname)

Definition at line 429 of file utility.c.

430 {
431  if (IsInParallelMode())
432  ereport(ERROR,
433  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
434  /* translator: %s is name of a SQL command, eg CREATE */
435  errmsg("cannot execute %s during a parallel operation",
436  cmdname)));
437 }
bool IsInParallelMode(void)
Definition: xact.c:1065

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

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

◆ PreventCommandIfReadOnly()

void PreventCommandIfReadOnly ( const char *  cmdname)

Definition at line 411 of file utility.c.

412 {
413  if (XactReadOnly)
414  ereport(ERROR,
415  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
416  /* translator: %s is name of a SQL command, eg CREATE */
417  errmsg("cannot execute %s in a read-only transaction",
418  cmdname)));
419 }
bool XactReadOnly
Definition: xact.c:81

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

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

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1696 of file miscinit.c.

1697 {
1699  "session_preload_libraries",
1700  false);
1702  "local_preload_libraries",
1703  true);
1704 }
char * session_preload_libraries_string
Definition: miscinit.c:1612
char * local_preload_libraries_string
Definition: miscinit.c:1614
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1630

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1682 of file miscinit.c.

1683 {
1686  "shared_preload_libraries",
1687  false);
1690 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1618
char * shared_preload_libraries_string
Definition: miscinit.c:1613
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1617

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

Referenced by PostmasterMain().

◆ process_shmem_requests()

void process_shmem_requests ( void  )

Definition at line 1710 of file miscinit.c.

1711 {
1713  if (shmem_request_hook)
1716 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1621
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1620

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostmasterMain().

◆ ProcessInterrupts()

void ProcessInterrupts ( void  )

Definition at line 3142 of file postgres.c.

3143 {
3144  /* OK to accept any interrupts now? */
3145  if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3146  return;
3147  InterruptPending = false;
3148 
3149  if (ProcDiePending)
3150  {
3151  ProcDiePending = false;
3152  QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3153  LockErrorCleanup();
3154  /* As in quickdie, don't risk sending to client during auth */
3158  ereport(FATAL,
3159  (errcode(ERRCODE_QUERY_CANCELED),
3160  errmsg("canceling authentication due to timeout")));
3161  else if (IsAutoVacuumWorkerProcess())
3162  ereport(FATAL,
3163  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3164  errmsg("terminating autovacuum process due to administrator command")));
3165  else if (IsLogicalWorker())
3166  ereport(FATAL,
3167  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3168  errmsg("terminating logical replication worker due to administrator command")));
3169  else if (IsLogicalLauncher())
3170  {
3171  ereport(DEBUG1,
3172  (errmsg_internal("logical replication launcher shutting down")));
3173 
3174  /*
3175  * The logical replication launcher can be stopped at any time.
3176  * Use exit status 1 so the background worker is restarted.
3177  */
3178  proc_exit(1);
3179  }
3181  {
3183  ereport(FATAL,
3185  errmsg("terminating connection due to conflict with recovery"),
3187  }
3188  else if (RecoveryConflictPending)
3189  {
3190  /* Currently there is only one non-retryable recovery conflict */
3193  ereport(FATAL,
3194  (errcode(ERRCODE_DATABASE_DROPPED),
3195  errmsg("terminating connection due to conflict with recovery"),
3197  }
3198  else if (IsBackgroundWorker)
3199  ereport(FATAL,
3200  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3201  errmsg("terminating background worker \"%s\" due to administrator command",
3203  else
3204  ereport(FATAL,
3205  (errcode(ERRCODE_ADMIN_SHUTDOWN),
3206  errmsg("terminating connection due to administrator command")));
3207  }
3208 
3210  {
3212 
3213  /*
3214  * Check for lost connection and re-arm, if still configured, but not
3215  * if we've arrived back at DoingCommandRead state. We don't want to
3216  * wake up idle sessions, and they already know how to detect lost
3217  * connections.
3218  */
3220  {
3221  if (!pq_check_connection())
3222  ClientConnectionLost = true;
3223  else
3226  }
3227  }
3228 
3230  {
3231  QueryCancelPending = false; /* lost connection trumps QueryCancel */
3232  LockErrorCleanup();
3233  /* don't send to client, we already know the connection to be dead. */
3235  ereport(FATAL,
3236  (errcode(ERRCODE_CONNECTION_FAILURE),
3237  errmsg("connection to client lost")));
3238  }
3239 
3240  /*
3241  * If a recovery conflict happens while we are waiting for input from the
3242  * client, the client is presumably just sitting idle in a transaction,
3243  * preventing recovery from making progress. Terminate the connection to
3244  * dislodge it.
3245  */
3247  {
3248  QueryCancelPending = false; /* this trumps QueryCancel */
3249  RecoveryConflictPending = false;
3250  LockErrorCleanup();
3252  ereport(FATAL,
3254  errmsg("terminating connection due to conflict with recovery"),
3256  errhint("In a moment you should be able to reconnect to the"
3257  " database and repeat your command.")));
3258  }
3259 
3260  /*
3261  * Don't allow query cancel interrupts while reading input from the
3262  * client, because we might lose sync in the FE/BE protocol. (Die
3263  * interrupts are OK, because we won't read any further messages from the
3264  * client in that case.)
3265  */
3267  {
3268  /*
3269  * Re-arm InterruptPending so that we process the cancel request as
3270  * soon as we're done reading the message. (XXX this is seriously
3271  * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3272  * can't use that macro directly as the initial test in this function,
3273  * meaning that this code also creates opportunities for other bugs to
3274  * appear.)
3275  */
3276  InterruptPending = true;
3277  }
3278  else if (QueryCancelPending)
3279  {
3280  bool lock_timeout_occurred;
3281  bool stmt_timeout_occurred;
3282 
3283  QueryCancelPending = false;
3284 
3285  /*
3286  * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3287  * need to clear both, so always fetch both.
3288  */
3289  lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3290  stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3291 
3292  /*
3293  * If both were set, we want to report whichever timeout completed
3294  * earlier; this ensures consistent behavior if the machine is slow
3295  * enough that the second timeout triggers before we get here. A tie
3296  * is arbitrarily broken in favor of reporting a lock timeout.
3297  */
3298  if (lock_timeout_occurred && stmt_timeout_occurred &&
3300  lock_timeout_occurred = false; /* report stmt timeout */
3301 
3302  if (lock_timeout_occurred)
3303  {
3304  LockErrorCleanup();
3305  ereport(ERROR,
3306  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3307  errmsg("canceling statement due to lock timeout")));
3308  }
3309  if (stmt_timeout_occurred)
3310  {
3311  LockErrorCleanup();
3312  ereport(ERROR,
3313  (errcode(ERRCODE_QUERY_CANCELED),
3314  errmsg("canceling statement due to statement timeout")));
3315  }
3317  {
3318  LockErrorCleanup();
3319  ereport(ERROR,
3320  (errcode(ERRCODE_QUERY_CANCELED),
3321  errmsg("canceling autovacuum task")));
3322  }
3324  {
3325  RecoveryConflictPending = false;
3326  LockErrorCleanup();
3328  ereport(ERROR,
3330  errmsg("canceling statement due to conflict with recovery"),
3332  }
3333 
3334  /*
3335  * If we are reading a command from the client, just ignore the cancel
3336  * request --- sending an extra error message won't accomplish
3337  * anything. Otherwise, go ahead and throw the error.
3338  */
3339  if (!DoingCommandRead)
3340  {
3341  LockErrorCleanup();
3342  ereport(ERROR,
3343  (errcode(ERRCODE_QUERY_CANCELED),
3344  errmsg("canceling statement due to user request")));
3345  }
3346  }
3347 
3349  {
3350  /*
3351  * If the GUC has been reset to zero, ignore the signal. This is
3352  * important because the GUC update itself won't disable any pending
3353  * interrupt.
3354  */
3356  ereport(FATAL,
3357  (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3358  errmsg("terminating connection due to idle-in-transaction timeout")));
3359  else
3361  }
3362 
3364  {
3365  /* As above, ignore the signal if the GUC has been reset to zero. */
3366  if (IdleSessionTimeout > 0)
3367  ereport(FATAL,
3368  (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3369  errmsg("terminating connection due to idle-session timeout")));
3370  else
3371  IdleSessionTimeoutPending = false;
3372  }
3373 
3375  {
3376  /* timer should have been disarmed */
3379  pgstat_report_stat(true);
3380  }
3381 
3384 
3387 
3390 }
void HandleParallelMessages(void)
Definition: parallel.c:1014
volatile bool ParallelMessagePending
Definition: parallel.c:115
bool IsLogicalWorker(void)
Definition: worker.c:3850
@ DestRemote
Definition: dest.h:91
@ DestNone
Definition: dest.h:89
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define DEBUG1
Definition: elog.h:24
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition: globals.c:39
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
volatile sig_atomic_t IdleSessionTimeoutPending
Definition: globals.c:36
volatile uint32 QueryCancelHoldoffCount
Definition: globals.c:41
volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
Definition: globals.c:35
volatile uint32 InterruptHoldoffCount
Definition: globals.c:40
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
volatile uint32 CritSectionCount
Definition: globals.c:42
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
volatile sig_atomic_t ProcDiePending
Definition: globals.c:32
volatile sig_atomic_t CheckClientConnectionPending
Definition: globals.c:33
void proc_exit(int code)
Definition: ipc.c:104
bool IsLogicalLauncher(void)
Definition: launcher.c:917
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1041
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:79
long pgstat_report_stat(bool force)
Definition: pgstat.c:565
void pgstat_report_recovery_conflict(int reason)
int client_connection_check_interval
Definition: postgres.c:106
static int errdetail_recovery_conflict(void)
Definition: postgres.c:2468
CommandDest whereToSendOutput
Definition: postgres.c:92
static bool RecoveryConflictRetryable
Definition: postgres.c:176
static bool DoingCommandRead
Definition: postgres.c:153
static ProcSignalReason RecoveryConflictReason
Definition: postgres.c:177
static bool RecoveryConflictPending
Definition: postgres.c:175
bool ClientAuthInProgress
Definition: postmaster.c:358
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:197
bool pq_check_connection(void)
Definition: pqcomm.c:1945
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:467
@ PROCSIG_RECOVERY_CONFLICT_DATABASE
Definition: procsignal.h:40
int IdleSessionTimeout
Definition: proc.c:64
int IdleInTransactionSessionTimeout
Definition: proc.c:63
void LockErrorCleanup(void)
Definition: proc.c:699
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:564
TimestampTz get_timeout_finish_time(TimeoutId id)
Definition: timeout.c:831
bool get_timeout_indicator(TimeoutId id, bool reset_indicator)
Definition: timeout.c:797
bool IsTransactionBlock(void)
Definition: xact.c:4766

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(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_recovery_conflict(), errhint(), errmsg(), errmsg_internal(), ERROR, FATAL, get_timeout_finish_time(), get_timeout_indicator(), HandleParallelMessages(), IdleInTransactionSessionTimeout, IdleInTransactionSessionTimeoutPending, IdleSessionTimeout, IdleSessionTimeoutPending, IdleStatsUpdateTimeoutPending, InterruptHoldoffCount, InterruptPending, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsLogicalLauncher(), IsLogicalWorker(), IsTransactionBlock(), LOCK_TIMEOUT, LockErrorCleanup(), LogMemoryContextPending, MyBgworkerEntry, ParallelMessagePending, pgstat_report_recovery_conflict(), pgstat_report_stat(), 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().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1477 of file miscinit.c.

1478 {
1479  int fd;
1480  int len;
1481  long file_pid;
1482  char buffer[BLCKSZ];
1483 
1484  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1485  if (fd < 0)
1486  {
1487  /*
1488  * There are many foreseeable false-positive error conditions. For
1489  * safety, fail only on enumerated clearly-something-is-wrong
1490  * conditions.
1491  */
1492  switch (errno)
1493  {
1494  case ENOENT:
1495  case ENOTDIR:
1496  /* disaster */
1497  ereport(LOG,
1499  errmsg("could not open file \"%s\": %m",
1501  return false;
1502  default:
1503  /* non-fatal, at least for now */
1504  ereport(LOG,
1506  errmsg("could not open file \"%s\": %m; continuing anyway",
1508  return true;
1509  }
1510  }
1512  len = read(fd, buffer, sizeof(buffer) - 1);
1514  if (len < 0)
1515  {
1516  ereport(LOG,
1518  errmsg("could not read from file \"%s\": %m",
1520  close(fd);
1521  return true; /* treat read failure as nonfatal */
1522  }
1523  buffer[len] = '\0';
1524  close(fd);
1525  file_pid = atol(buffer);
1526  if (file_pid == getpid())
1527  return true; /* all is well */
1528 
1529  /* Trouble: someone's overwritten the lock file */
1530  ereport(LOG,
1531  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1532  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1533  return false;
1534 }
@ WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ
Definition: wait_event.h:188

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

Referenced by ServerLoop().

◆ restore_stack_base()

void restore_stack_base ( pg_stack_base_t  base)

Definition at line 3478 of file postgres.c.

3479 {
3480 #if defined(__ia64__) || defined(__ia64)
3481  stack_base_ptr = base.stack_base_ptr;
3482  register_stack_base_ptr = base.register_stack_base_ptr;
3483 #else
3484  stack_base_ptr = base;
3485 #endif
3486 }
static char * stack_base_ptr
Definition: postgres.c:133

References stack_base_ptr.

◆ set_stack_base()

pg_stack_base_t set_stack_base ( void  )

Definition at line 3437 of file postgres.c.

3438 {
3439 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3440  char stack_base;
3441 #endif
3442  pg_stack_base_t old;
3443 
3444 #if defined(__ia64__) || defined(__ia64)
3445  old.stack_base_ptr = stack_base_ptr;
3446  old.register_stack_base_ptr = register_stack_base_ptr;
3447 #else
3448  old = stack_base_ptr;
3449 #endif
3450 
3451  /*
3452  * Set up reference point for stack depth checking. On recent gcc we use
3453  * __builtin_frame_address() to avoid a warning about storing a local
3454  * variable's address in a long-lived variable.
3455  */
3456 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3457  stack_base_ptr = __builtin_frame_address(0);
3458 #else
3459  stack_base_ptr = &stack_base;
3460 #endif
3461 #if defined(__ia64__) || defined(__ia64)
3462  register_stack_base_ptr = ia64_get_bsp();
3463 #endif
3464 
3465  return old;
3466 }
char * pg_stack_base_t
Definition: miscadmin.h:289

References stack_base_ptr.

Referenced by InitPostmasterChild(), and PostmasterMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 877 of file miscinit.c.

878 {
879  /*
880  * Get correct info if it's SET ROLE NONE
881  *
882  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
883  * SetSessionUserId call will fix everything. This is needed since we
884  * will get called during GUC initialization.
885  */
886  if (!OidIsValid(roleid))
887  {
889  return;
890 
891  roleid = SessionUserId;
893 
894  SetRoleIsActive = false;
895  }
896  else
897  SetRoleIsActive = true;
898 
899  SetOuterUserId(roleid);
900 
901  SetConfigOption("is_superuser",
902  is_superuser ? "on" : "off",
904 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:510
static bool SessionUserIsSuperuser
Definition: miscinit.c:478
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4377

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

Referenced by assign_role(), and ParallelWorkerMain().

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 305 of file miscinit.c.

306 {
307  /* This should happen only once per process */
310 }
char * DatabasePath
Definition: globals.c:97
MemoryContext TopMemoryContext
Definition: mcxt.c:48
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1292

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 411 of file miscinit.c.

412 {
413  char *new;
414 
415  AssertArg(dir);
416 
417  /* If presented path is relative, convert to absolute */
418  new = make_absolute_path(dir);
419 
420  free(DataDir);
421  DataDir = new;
422 }
#define AssertArg(condition)
Definition: c.h:817
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:729

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

Referenced by SelectConfigFiles().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 831 of file miscinit.c.

832 {
833  /* Must have authenticated already, else can't make permission check */
835 
836  if (userid != AuthenticatedUserId &&
838  ereport(ERROR,
839  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
840  errmsg("permission denied to set session authorization")));
841 
843 
844  SetConfigOption("is_superuser",
845  is_superuser ? "on" : "off",
847 }

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

Referenced by assign_session_authorization().

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 658 of file miscinit.c.

659 {
660  /* We throw the same error SET ROLE would. */
662  ereport(ERROR,
663  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
664  errmsg("cannot set parameter \"%s\" within security-restricted operation",
665  "role")));
666  CurrentUserId = userid;
667  if (sec_def_context)
669  else
671 }
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:629

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

◆ SetUserIdAndSecContext()

◆ stack_is_too_deep()

bool stack_is_too_deep ( void  )

Definition at line 3514 of file postgres.c.

3515 {
3516  char stack_top_loc;
3517  long stack_depth;
3518 
3519  /*
3520  * Compute distance from reference point to my local variables
3521  */
3522  stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3523 
3524  /*
3525  * Take abs value, since stacks grow up on some machines, down on others
3526  */
3527  if (stack_depth < 0)
3528  stack_depth = -stack_depth;
3529 
3530  /*
3531  * Trouble?
3532  *
3533  * The test on stack_base_ptr prevents us from erroring out if called
3534  * during process setup or in a non-backend process. Logically it should
3535  * be done first, but putting it here avoids wasting cycles during normal
3536  * cases.
3537  */
3538  if (stack_depth > max_stack_depth_bytes &&
3539  stack_base_ptr != NULL)
3540  return true;
3541 
3542  /*
3543  * On IA64 there is a separate "register" stack that requires its own
3544  * independent check. For this, we have to measure the change in the
3545  * "BSP" pointer from PostgresMain to here. Logic is just as above,
3546  * except that we know IA64's register stack grows up.
3547  *
3548  * Note we assume that the same max_stack_depth applies to both stacks.
3549  */
3550 #if defined(__ia64__) || defined(__ia64)
3551  stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3552 
3553  if (stack_depth > max_stack_depth_bytes &&
3554  register_stack_base_ptr != NULL)
3555  return true;
3556 #endif /* IA64 */
3557 
3558  return false;
3559 }
static long max_stack_depth_bytes
Definition: postgres.c:127

References max_stack_depth_bytes, and stack_base_ptr.

Referenced by check_stack_depth(), and rstacktoodeep().

◆ superuser()

bool superuser ( void  )

Definition at line 46 of file superuser.c.

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

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(), AlterSubscription(), 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(), CheckAlterPublication(), 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(), execute_extension_script(), 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_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().

◆ superuser_arg()

bool superuser_arg ( Oid  roleid)

Definition at line 56 of file superuser.c.

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 }
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1519
bool rolsuper
Definition: pg_authid.h:35
uintptr_t Datum
Definition: postgres.h:411
static Oid last_roleid
Definition: superuser.c:35
static bool roleid_callback_registered
Definition: superuser.c:37
static void RoleidCallback(Datum arg, int cacheid, uint32 hashvalue)
Definition: superuser.c:103
static bool last_roleid_is_super
Definition: superuser.c:36

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(), emit_audit_message(), 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_parameter_acl_aclmask(), pg_parameter_aclmask(), 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(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), select_best_grantor(), superuser(), and TerminateOtherDBBackends().

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 234 of file miscinit.c.

235 {
237  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
238 
240 
241  if (FeBeWaitSet)
243  MyLatch);
244 
245  SetLatch(MyLatch);
246 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:972
void SetLatch(Latch *latch)
Definition: latch.c:591
#define WL_LATCH_SET
Definition: latch.h:125
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
Latch procLatch
Definition: proc.h:168

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

Referenced by AuxiliaryProcKill(), and ProcKill().

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 214 of file miscinit.c.

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 }

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1321 of file miscinit.c.

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

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ trace_recovery()

int trace_recovery ( int  trace_level)

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1549 of file miscinit.c.

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

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

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ allowSystemTableMods

◆ CheckClientConnectionPending

PGDLLIMPORT volatile sig_atomic_t CheckClientConnectionPending
extern

Definition at line 33 of file globals.c.

Referenced by ClientCheckTimeoutHandler(), and ProcessInterrupts().

◆ ClientConnectionLost

PGDLLIMPORT volatile sig_atomic_t ClientConnectionLost
extern

Definition at line 34 of file globals.c.

Referenced by internal_flush(), and ProcessInterrupts().

◆ CritSectionCount

◆ data_directory_mode

PGDLLIMPORT int data_directory_mode
extern

Definition at line 72 of file globals.c.

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

◆ DatabasePath

◆ DataDir

◆ DateOrder

PGDLLIMPORT int DateOrder
extern

◆ DateStyle

◆ enableFsync

◆ ExitOnAnyError

PGDLLIMPORT bool ExitOnAnyError
extern

Definition at line 117 of file globals.c.

Referenced by errstart(), and HandleCheckpointerInterrupts().

◆ hash_mem_multiplier

PGDLLIMPORT double hash_mem_multiplier
extern

Definition at line 126 of file globals.c.

Referenced by get_hash_memory_limit().

◆ IdleInTransactionSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleInTransactionSessionTimeoutPending
extern

Definition at line 35 of file globals.c.

Referenced by IdleInTransactionSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleSessionTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleSessionTimeoutPending
extern

Definition at line 36 of file globals.c.

Referenced by IdleSessionTimeoutHandler(), and ProcessInterrupts().

◆ IdleStatsUpdateTimeoutPending

PGDLLIMPORT volatile sig_atomic_t IdleStatsUpdateTimeoutPending
extern

Definition at line 39 of file globals.c.

Referenced by IdleStatsUpdateTimeoutHandler(), and ProcessInterrupts().

◆ IgnoreSystemIndexes

◆ InterruptHoldoffCount

PGDLLIMPORT volatile uint32 InterruptHoldoffCount
extern

◆ InterruptPending

◆ IntervalStyle

PGDLLIMPORT int IntervalStyle
extern

◆ IsBackgroundWorker

◆ IsBinaryUpgrade

◆ IsPostmasterEnvironment

◆ IsUnderPostmaster

PGDLLIMPORT bool IsUnderPostmaster
extern

Definition at line 113 of file globals.c.

Referenced by _PG_init(), AdvanceNextFullTransactionIdPastXid(), AutoVacuumShmemInit(), AuxiliaryProcessMain(), BackgroundWorkerShmemInit(), bootstrap_signals(), BootstrapModeMain(), BTreeShmemInit(), CheckMyDatabase(), CheckRecoveryConsistency(), CommitTsShmemInit(), createdb(), CreateLWLocks(), CreateRestartPoint(), CreateSharedMemoryAndSemaphores(), DebugFileOpen(), dsm_attach(), dsm_backend_startup(), dsm_create(), dsm_impl_pin_segment(), dsm_impl_unpin_segment(), dsm_postmaster_startup(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), ForwardSyncRequest(), get_slru_entry(), GetNewMultiXactId(), GetNewTransactionId(), GetQuitSignalReason(), HandleStartupProcInterrupts(), init_ps_display(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitializeSessionUserId(), InitializeSessionUserIdStandalone(), InitPostgres(), InitPostmasterChild(), InitPredicateLocks(), InitProcess(), InitSync(), LWLockAcquire(), MaintainLatestCompletedXidRecovery(), MultiXactShmemInit(), parallel_vacuum_compute_workers(), PerformRecoveryXLogAction(), PerformWalRecovery(), PGSemaphoreCreate(), PGSharedMemoryNoReAttach(), PGSharedMemoryReAttach(), pgss_shmem_startup(), pgstat_fetch_entry(), pgstat_flush_wal(), pgstat_read_statsfile(), pgstat_report_autovac(), pgstat_report_recovery_conflict(), pgstat_shutdown_hook(), plan_create_index_workers(), PostgresMain(), PostgresSingleUserMain(), process_postgres_switches(), process_settings(), ProcKill(), readRecoverySignalFile(), RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), ReplicationSlotAcquire(), SendPostmasterSignal(), SerialInit(), set_config_option(), set_config_sourcefile(), set_ps_display(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemInitStruct(), SimpleLruInit(), standard_planner(), start_xact_command(), StatsShmemInit(), superuser_arg(), SyncScanShmemInit(), TwoPhaseShmemInit(), verify_dictoptions(), WaitLatch(), WaitLatchOrSocket(), XLogArchiveNotify(), XLogPageRead(), XLogPrefetchIncrement(), XLogRecGetFullXid(), and XLogWrite().

◆ local_preload_libraries_string

PGDLLIMPORT char* local_preload_libraries_string
extern

Definition at line 1614 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LogMemoryContextPending

◆ maintenance_work_mem

◆ max_parallel_maintenance_workers

PGDLLIMPORT int max_parallel_maintenance_workers
extern

Definition at line 128 of file globals.c.

Referenced by parallel_vacuum_compute_workers(), and plan_create_index_workers().

◆ max_parallel_workers

PGDLLIMPORT int max_parallel_workers
extern

Definition at line 139 of file globals.c.

Referenced by RegisterDynamicBackgroundWorker().

◆ max_worker_processes

◆ MaxBackends

◆ MaxConnections

◆ Mode

Definition at line 61 of file miscinit.c.

◆ my_exec_path

◆ MyAuxProcType

PGDLLIMPORT AuxProcType MyAuxProcType
extern

Definition at line 45 of file auxprocess.c.

Referenced by AuxiliaryProcessMain(), and pgstat_beinit().

◆ MyBackendType

◆ MyCancelKey

◆ MyDatabaseId

PGDLLIMPORT Oid MyDatabaseId
extern

Definition at line 89 of file globals.c.

Referenced by AfterTriggerSetState(), AlterDatabase(), AlterObjectRename_internal(), AlterPublicationOwner_internal(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner(), asyncQueueNotificationToEntry(), asyncQueueProcessPageEntries(), ATExecDetachPartition(), AutoVacuumRequestWork(), 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(), find_funcstat_entry(), find_tabstat_entry(), get_subscription_oid(), get_tables_to_cluster_partitioned(), 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(), match_db_entries(), movedb(), perform_relmap_update(), perform_work_item(), pg_namespace_aclmask(), pg_relation_filepath(), pg_stat_reset_single_function_counters(), pg_stat_reset_single_table_counters(), pgss_store(), pgstat_bestart(), pgstat_build_snapshot(), pgstat_copy_relation_stats(), pgstat_create_function(), pgstat_create_relation(), pgstat_drop_function(), pgstat_drop_relation(), pgstat_fetch_stat_funcentry(), pgstat_fetch_stat_tabentry_ext(), pgstat_init_function_usage(), pgstat_prep_relation_pending(), pgstat_report_analyze(), pgstat_report_checksum_failure(), pgstat_report_connect(), pgstat_report_deadlock(), pgstat_report_disconnect(), pgstat_report_recovery_conflict(), pgstat_report_tempfile(), pgstat_report_vacuum(), pgstat_reset_counters(), pgstat_reset_database_timestamp(), pgstat_shutdown_hook(), pgstat_update_dbstats(), PostgresMain(), PrepareToInvalidateCacheTuple(), PrepareTransaction(), ProcArrayInstallImportedXmin(), ProcArrayInstallRestoredXmin(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetCreationNamespace(), RangeVarGetRelidExtended(), 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
extern

Definition at line 58 of file globals.c.

Referenced by ApplyLauncherMain(), autoprewarm_main(), AutoVacLauncherMain(), avl_sigusr2_handler(), BackgroundWriterMain(), be_tls_open_server(), CheckDeadLockAlert(), CheckpointerMain(), CheckpointWriteDelay(), ClientCheckTimeoutHandler(), ConditionVariableTimedSleep(), copy_read_data(), die(), do_pg_backup_stop(), gather_readnext(), handle_sig_alarm(), HandleCatchupInterrupt(), HandleNotifyInterrupt(), HandleParallelMessageInterrupt(), IdleInTransactionSessionTimeoutHandler(), IdleSessionTimeoutHandler(), IdleStatsUpdateTimeoutHandler(), 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(), pq_check_connection(), pq_init(), ProcessClientReadInterrupt(), ProcessClientWriteInterrupt(), ProcessPendingWrites(), 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(), and WalWriterMain().

◆ MyPMChildSlot

◆ MyProcPid

PGDLLIMPORT int MyProcPid
extern

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

◆ MyProcPort

◆ MyStartTime

◆ MyStartTimestamp

PGDLLIMPORT TimestampTz MyStartTimestamp
extern

◆ NBuffers

PGDLLIMPORT int NBuffers
extern

Definition at line 136 of file globals.c.

◆ OutputFileName

PGDLLIMPORT char OutputFileName[]
extern

Definition at line 74 of file globals.c.

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

◆ pkglib_path

◆ PostmasterPid

◆ ProcDiePending

◆ process_shared_preload_libraries_done

PGDLLIMPORT bool process_shared_preload_libraries_done
extern

◆ process_shared_preload_libraries_in_progress

PGDLLIMPORT bool process_shared_preload_libraries_in_progress
extern

◆ process_shmem_requests_in_progress

PGDLLIMPORT bool process_shmem_requests_in_progress
extern

◆ ProcSignalBarrierPending

◆ QueryCancelHoldoffCount

PGDLLIMPORT volatile uint32 QueryCancelHoldoffCount
extern

Definition at line 41 of file globals.c.

Referenced by errfinish(), and ProcessInterrupts().

◆ QueryCancelPending

◆ session_preload_libraries_string

PGDLLIMPORT char* session_preload_libraries_string
extern

Definition at line 1612 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ shared_preload_libraries_string

PGDLLIMPORT char* shared_preload_libraries_string
extern

Definition at line 1613 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

PGDLLIMPORT shmem_request_hook_type shmem_request_hook
extern

Definition at line 1620 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ trace_recovery_messages

PGDLLIMPORT int trace_recovery_messages
extern

Definition at line 645 of file guc.c.

Referenced by PerformWalRecovery(), and trace_recovery().

◆ VacuumCostActive

◆ VacuumCostBalance

◆ VacuumCostDelay

◆ VacuumCostLimit

◆ VacuumCostPageDirty

PGDLLIMPORT int VacuumCostPageDirty
extern

Definition at line 144 of file globals.c.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ VacuumCostPageHit

PGDLLIMPORT int VacuumCostPageHit
extern

Definition at line 142 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumCostPageMiss

PGDLLIMPORT int VacuumCostPageMiss
extern

Definition at line 143 of file globals.c.

Referenced by ReadBuffer_common().

◆ VacuumPageDirty

PGDLLIMPORT int64 VacuumPageDirty
extern

◆ VacuumPageHit

PGDLLIMPORT int64 VacuumPageHit
extern

◆ VacuumPageMiss

PGDLLIMPORT int64 VacuumPageMiss
extern

◆ work_mem