LCOV - code coverage report
Current view: top level - src/backend/postmaster - postmaster.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 1047 1433 73.1 %
Date: 2019-09-19 02:07:14 Functions: 48 54 88.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * postmaster.c
       4             :  *    This program acts as a clearing house for requests to the
       5             :  *    POSTGRES system.  Frontend programs send a startup message
       6             :  *    to the Postmaster and the postmaster uses the info in the
       7             :  *    message to setup a backend process.
       8             :  *
       9             :  *    The postmaster also manages system-wide operations such as
      10             :  *    startup and shutdown. The postmaster itself doesn't do those
      11             :  *    operations, mind you --- it just forks off a subprocess to do them
      12             :  *    at the right times.  It also takes care of resetting the system
      13             :  *    if a backend crashes.
      14             :  *
      15             :  *    The postmaster process creates the shared memory and semaphore
      16             :  *    pools during startup, but as a rule does not touch them itself.
      17             :  *    In particular, it is not a member of the PGPROC array of backends
      18             :  *    and so it cannot participate in lock-manager operations.  Keeping
      19             :  *    the postmaster away from shared memory operations makes it simpler
      20             :  *    and more reliable.  The postmaster is almost always able to recover
      21             :  *    from crashes of individual backends by resetting shared memory;
      22             :  *    if it did much with shared memory then it would be prone to crashing
      23             :  *    along with the backends.
      24             :  *
      25             :  *    When a request message is received, we now fork() immediately.
      26             :  *    The child process performs authentication of the request, and
      27             :  *    then becomes a backend if successful.  This allows the auth code
      28             :  *    to be written in a simple single-threaded style (as opposed to the
      29             :  *    crufty "poor man's multitasking" code that used to be needed).
      30             :  *    More importantly, it ensures that blockages in non-multithreaded
      31             :  *    libraries like SSL or PAM cannot cause denial of service to other
      32             :  *    clients.
      33             :  *
      34             :  *
      35             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
      36             :  * Portions Copyright (c) 1994, Regents of the University of California
      37             :  *
      38             :  *
      39             :  * IDENTIFICATION
      40             :  *    src/backend/postmaster/postmaster.c
      41             :  *
      42             :  * NOTES
      43             :  *
      44             :  * Initialization:
      45             :  *      The Postmaster sets up shared memory data structures
      46             :  *      for the backends.
      47             :  *
      48             :  * Synchronization:
      49             :  *      The Postmaster shares memory with the backends but should avoid
      50             :  *      touching shared memory, so as not to become stuck if a crashing
      51             :  *      backend screws up locks or shared memory.  Likewise, the Postmaster
      52             :  *      should never block on messages from frontend clients.
      53             :  *
      54             :  * Garbage Collection:
      55             :  *      The Postmaster cleans up after backends if they have an emergency
      56             :  *      exit and/or core dump.
      57             :  *
      58             :  * Error Reporting:
      59             :  *      Use write_stderr() only for reporting "interactive" errors
      60             :  *      (essentially, bogus arguments on the command line).  Once the
      61             :  *      postmaster is launched, use ereport().
      62             :  *
      63             :  *-------------------------------------------------------------------------
      64             :  */
      65             : 
      66             : #include "postgres.h"
      67             : 
      68             : #include <unistd.h>
      69             : #include <signal.h>
      70             : #include <time.h>
      71             : #include <sys/wait.h>
      72             : #include <ctype.h>
      73             : #include <sys/stat.h>
      74             : #include <sys/socket.h>
      75             : #include <fcntl.h>
      76             : #include <sys/param.h>
      77             : #include <netdb.h>
      78             : #include <limits.h>
      79             : 
      80             : #ifdef HAVE_SYS_SELECT_H
      81             : #include <sys/select.h>
      82             : #endif
      83             : 
      84             : #ifdef USE_BONJOUR
      85             : #include <dns_sd.h>
      86             : #endif
      87             : 
      88             : #ifdef USE_SYSTEMD
      89             : #include <systemd/sd-daemon.h>
      90             : #endif
      91             : 
      92             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
      93             : #include <pthread.h>
      94             : #endif
      95             : 
      96             : #include "access/transam.h"
      97             : #include "access/xlog.h"
      98             : #include "bootstrap/bootstrap.h"
      99             : #include "catalog/pg_control.h"
     100             : #include "common/file_perm.h"
     101             : #include "common/ip.h"
     102             : #include "common/string.h"
     103             : #include "lib/ilist.h"
     104             : #include "libpq/auth.h"
     105             : #include "libpq/libpq.h"
     106             : #include "libpq/pqformat.h"
     107             : #include "libpq/pqsignal.h"
     108             : #include "miscadmin.h"
     109             : #include "pg_getopt.h"
     110             : #include "pgstat.h"
     111             : #include "port/pg_bswap.h"
     112             : #include "postmaster/autovacuum.h"
     113             : #include "postmaster/bgworker_internals.h"
     114             : #include "postmaster/fork_process.h"
     115             : #include "postmaster/pgarch.h"
     116             : #include "postmaster/postmaster.h"
     117             : #include "postmaster/syslogger.h"
     118             : #include "replication/logicallauncher.h"
     119             : #include "replication/walsender.h"
     120             : #include "storage/fd.h"
     121             : #include "storage/ipc.h"
     122             : #include "storage/pg_shmem.h"
     123             : #include "storage/pmsignal.h"
     124             : #include "storage/proc.h"
     125             : #include "tcop/tcopprot.h"
     126             : #include "utils/builtins.h"
     127             : #include "utils/datetime.h"
     128             : #include "utils/memutils.h"
     129             : #include "utils/pidfile.h"
     130             : #include "utils/ps_status.h"
     131             : #include "utils/timeout.h"
     132             : #include "utils/timestamp.h"
     133             : #include "utils/varlena.h"
     134             : 
     135             : #ifdef EXEC_BACKEND
     136             : #include "storage/spin.h"
     137             : #endif
     138             : 
     139             : 
     140             : /*
     141             :  * Possible types of a backend. Beyond being the possible bkend_type values in
     142             :  * struct bkend, these are OR-able request flag bits for SignalSomeChildren()
     143             :  * and CountChildren().
     144             :  */
     145             : #define BACKEND_TYPE_NORMAL     0x0001  /* normal backend */
     146             : #define BACKEND_TYPE_AUTOVAC    0x0002  /* autovacuum worker process */
     147             : #define BACKEND_TYPE_WALSND     0x0004  /* walsender process */
     148             : #define BACKEND_TYPE_BGWORKER   0x0008  /* bgworker process */
     149             : #define BACKEND_TYPE_ALL        0x000F  /* OR of all the above */
     150             : 
     151             : #define BACKEND_TYPE_WORKER     (BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER)
     152             : 
     153             : /*
     154             :  * List of active backends (or child processes anyway; we don't actually
     155             :  * know whether a given child has become a backend or is still in the
     156             :  * authorization phase).  This is used mainly to keep track of how many
     157             :  * children we have and send them appropriate signals when necessary.
     158             :  *
     159             :  * "Special" children such as the startup, bgwriter and autovacuum launcher
     160             :  * tasks are not in this list.  Autovacuum worker and walsender are in it.
     161             :  * Also, "dead_end" children are in it: these are children launched just for
     162             :  * the purpose of sending a friendly rejection message to a would-be client.
     163             :  * We must track them because they are attached to shared memory, but we know
     164             :  * they will never become live backends.  dead_end children are not assigned a
     165             :  * PMChildSlot.
     166             :  *
     167             :  * Background workers are in this list, too.
     168             :  */
     169             : typedef struct bkend
     170             : {
     171             :     pid_t       pid;            /* process id of backend */
     172             :     int32       cancel_key;     /* cancel key for cancels for this backend */
     173             :     int         child_slot;     /* PMChildSlot for this backend, if any */
     174             : 
     175             :     /*
     176             :      * Flavor of backend or auxiliary process.  Note that BACKEND_TYPE_WALSND
     177             :      * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if
     178             :      * bkend_type is normal, you should check for a recent transition.
     179             :      */
     180             :     int         bkend_type;
     181             :     bool        dead_end;       /* is it going to send an error and quit? */
     182             :     bool        bgworker_notify;    /* gets bgworker start/stop notifications */
     183             :     dlist_node  elem;           /* list link in BackendList */
     184             : } Backend;
     185             : 
     186             : static dlist_head BackendList = DLIST_STATIC_INIT(BackendList);
     187             : 
     188             : #ifdef EXEC_BACKEND
     189             : static Backend *ShmemBackendArray;
     190             : #endif
     191             : 
     192             : BackgroundWorker *MyBgworkerEntry = NULL;
     193             : 
     194             : 
     195             : 
     196             : /* The socket number we are listening for connections on */
     197             : int         PostPortNumber;
     198             : 
     199             : /* The directory names for Unix socket(s) */
     200             : char       *Unix_socket_directories;
     201             : 
     202             : /* The TCP listen address(es) */
     203             : char       *ListenAddresses;
     204             : 
     205             : /*
     206             :  * ReservedBackends is the number of backends reserved for superuser use.
     207             :  * This number is taken out of the pool size given by MaxConnections so
     208             :  * number of backend slots available to non-superusers is
     209             :  * (MaxConnections - ReservedBackends).  Note what this really means is
     210             :  * "if there are <= ReservedBackends connections available, only superusers
     211             :  * can make new connections" --- pre-existing superuser connections don't
     212             :  * count against the limit.
     213             :  */
     214             : int         ReservedBackends;
     215             : 
     216             : /* The socket(s) we're listening to. */
     217             : #define MAXLISTEN   64
     218             : static pgsocket ListenSocket[MAXLISTEN];
     219             : 
     220             : /*
     221             :  * Set by the -o option
     222             :  */
     223             : static char ExtraOptions[MAXPGPATH];
     224             : 
     225             : /*
     226             :  * These globals control the behavior of the postmaster in case some
     227             :  * backend dumps core.  Normally, it kills all peers of the dead backend
     228             :  * and reinitializes shared memory.  By specifying -s or -n, we can have
     229             :  * the postmaster stop (rather than kill) peers and not reinitialize
     230             :  * shared data structures.  (Reinit is currently dead code, though.)
     231             :  */
     232             : static bool Reinit = true;
     233             : static int  SendStop = false;
     234             : 
     235             : /* still more option variables */
     236             : bool        EnableSSL = false;
     237             : 
     238             : int         PreAuthDelay = 0;
     239             : int         AuthenticationTimeout = 60;
     240             : 
     241             : bool        log_hostname;       /* for ps display and logging */
     242             : bool        Log_connections = false;
     243             : bool        Db_user_namespace = false;
     244             : 
     245             : bool        enable_bonjour = false;
     246             : char       *bonjour_name;
     247             : bool        restart_after_crash = true;
     248             : 
     249             : /* PIDs of special child processes; 0 when not running */
     250             : static pid_t StartupPID = 0,
     251             :             BgWriterPID = 0,
     252             :             CheckpointerPID = 0,
     253             :             WalWriterPID = 0,
     254             :             WalReceiverPID = 0,
     255             :             AutoVacPID = 0,
     256             :             PgArchPID = 0,
     257             :             PgStatPID = 0,
     258             :             SysLoggerPID = 0;
     259             : 
     260             : /* Startup process's status */
     261             : typedef enum
     262             : {
     263             :     STARTUP_NOT_RUNNING,
     264             :     STARTUP_RUNNING,
     265             :     STARTUP_SIGNALED,           /* we sent it a SIGQUIT or SIGKILL */
     266             :     STARTUP_CRASHED
     267             : } StartupStatusEnum;
     268             : 
     269             : static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING;
     270             : 
     271             : /* Startup/shutdown state */
     272             : #define         NoShutdown      0
     273             : #define         SmartShutdown   1
     274             : #define         FastShutdown    2
     275             : #define         ImmediateShutdown   3
     276             : 
     277             : static int  Shutdown = NoShutdown;
     278             : 
     279             : static bool FatalError = false; /* T if recovering from backend crash */
     280             : 
     281             : /*
     282             :  * We use a simple state machine to control startup, shutdown, and
     283             :  * crash recovery (which is rather like shutdown followed by startup).
     284             :  *
     285             :  * After doing all the postmaster initialization work, we enter PM_STARTUP
     286             :  * state and the startup process is launched. The startup process begins by
     287             :  * reading the control file and other preliminary initialization steps.
     288             :  * In a normal startup, or after crash recovery, the startup process exits
     289             :  * with exit code 0 and we switch to PM_RUN state.  However, archive recovery
     290             :  * is handled specially since it takes much longer and we would like to support
     291             :  * hot standby during archive recovery.
     292             :  *
     293             :  * When the startup process is ready to start archive recovery, it signals the
     294             :  * postmaster, and we switch to PM_RECOVERY state. The background writer and
     295             :  * checkpointer are launched, while the startup process continues applying WAL.
     296             :  * If Hot Standby is enabled, then, after reaching a consistent point in WAL
     297             :  * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
     298             :  * state and begin accepting connections to perform read-only queries.  When
     299             :  * archive recovery is finished, the startup process exits with exit code 0
     300             :  * and we switch to PM_RUN state.
     301             :  *
     302             :  * Normal child backends can only be launched when we are in PM_RUN or
     303             :  * PM_HOT_STANDBY state.  (We also allow launch of normal
     304             :  * child backends in PM_WAIT_BACKUP state, but only for superusers.)
     305             :  * In other states we handle connection requests by launching "dead_end"
     306             :  * child processes, which will simply send the client an error message and
     307             :  * quit.  (We track these in the BackendList so that we can know when they
     308             :  * are all gone; this is important because they're still connected to shared
     309             :  * memory, and would interfere with an attempt to destroy the shmem segment,
     310             :  * possibly leading to SHMALL failure when we try to make a new one.)
     311             :  * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
     312             :  * to drain out of the system, and therefore stop accepting connection
     313             :  * requests at all until the last existing child has quit (which hopefully
     314             :  * will not be very long).
     315             :  *
     316             :  * Notice that this state variable does not distinguish *why* we entered
     317             :  * states later than PM_RUN --- Shutdown and FatalError must be consulted
     318             :  * to find that out.  FatalError is never true in PM_RECOVERY_* or PM_RUN
     319             :  * states, nor in PM_SHUTDOWN states (because we don't enter those states
     320             :  * when trying to recover from a crash).  It can be true in PM_STARTUP state,
     321             :  * because we don't clear it until we've successfully started WAL redo.
     322             :  */
     323             : typedef enum
     324             : {
     325             :     PM_INIT,                    /* postmaster starting */
     326             :     PM_STARTUP,                 /* waiting for startup subprocess */
     327             :     PM_RECOVERY,                /* in archive recovery mode */
     328             :     PM_HOT_STANDBY,             /* in hot standby mode */
     329             :     PM_RUN,                     /* normal "database is alive" state */
     330             :     PM_WAIT_BACKUP,             /* waiting for online backup mode to end */
     331             :     PM_WAIT_READONLY,           /* waiting for read only backends to exit */
     332             :     PM_WAIT_BACKENDS,           /* waiting for live backends to exit */
     333             :     PM_SHUTDOWN,                /* waiting for checkpointer to do shutdown
     334             :                                  * ckpt */
     335             :     PM_SHUTDOWN_2,              /* waiting for archiver and walsenders to
     336             :                                  * finish */
     337             :     PM_WAIT_DEAD_END,           /* waiting for dead_end children to exit */
     338             :     PM_NO_CHILDREN              /* all important children have exited */
     339             : } PMState;
     340             : 
     341             : static PMState pmState = PM_INIT;
     342             : 
     343             : /* Start time of SIGKILL timeout during immediate shutdown or child crash */
     344             : /* Zero means timeout is not running */
     345             : static time_t AbortStartTime = 0;
     346             : 
     347             : /* Length of said timeout */
     348             : #define SIGKILL_CHILDREN_AFTER_SECS     5
     349             : 
     350             : static bool ReachedNormalRunning = false;   /* T if we've reached PM_RUN */
     351             : 
     352             : bool        ClientAuthInProgress = false;   /* T during new-client
     353             :                                              * authentication */
     354             : 
     355             : bool        redirection_done = false;   /* stderr redirected for syslogger? */
     356             : 
     357             : /* received START_AUTOVAC_LAUNCHER signal */
     358             : static volatile sig_atomic_t start_autovac_launcher = false;
     359             : 
     360             : /* the launcher needs to be signalled to communicate some condition */
     361             : static volatile bool avlauncher_needs_signal = false;
     362             : 
     363             : /* received START_WALRECEIVER signal */
     364             : static volatile sig_atomic_t WalReceiverRequested = false;
     365             : 
     366             : /* set when there's a worker that needs to be started up */
     367             : static volatile bool StartWorkerNeeded = true;
     368             : static volatile bool HaveCrashedWorker = false;
     369             : 
     370             : #ifdef USE_SSL
     371             : /* Set when and if SSL has been initialized properly */
     372             : static bool LoadedSSL = false;
     373             : #endif
     374             : 
     375             : #ifdef USE_BONJOUR
     376             : static DNSServiceRef bonjour_sdref = NULL;
     377             : #endif
     378             : 
     379             : /*
     380             :  * postmaster.c - function prototypes
     381             :  */
     382             : static void CloseServerPorts(int status, Datum arg);
     383             : static void unlink_external_pid_file(int status, Datum arg);
     384             : static void getInstallationPaths(const char *argv0);
     385             : static void checkControlFile(void);
     386             : static Port *ConnCreate(int serverFd);
     387             : static void ConnFree(Port *port);
     388             : static void reset_shared(void);
     389             : static void SIGHUP_handler(SIGNAL_ARGS);
     390             : static void pmdie(SIGNAL_ARGS);
     391             : static void reaper(SIGNAL_ARGS);
     392             : static void sigusr1_handler(SIGNAL_ARGS);
     393             : static void startup_die(SIGNAL_ARGS);
     394             : static void dummy_handler(SIGNAL_ARGS);
     395             : static void StartupPacketTimeoutHandler(void);
     396             : static void CleanupBackend(int pid, int exitstatus);
     397             : static bool CleanupBackgroundWorker(int pid, int exitstatus);
     398             : static void HandleChildCrash(int pid, int exitstatus, const char *procname);
     399             : static void LogChildExit(int lev, const char *procname,
     400             :                          int pid, int exitstatus);
     401             : static void PostmasterStateMachine(void);
     402             : static void BackendInitialize(Port *port);
     403             : static void BackendRun(Port *port) pg_attribute_noreturn();
     404             : static void ExitPostmaster(int status) pg_attribute_noreturn();
     405             : static int  ServerLoop(void);
     406             : static int  BackendStartup(Port *port);
     407             : static int  ProcessStartupPacket(Port *port, bool secure_done);
     408             : static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options);
     409             : static void processCancelRequest(Port *port, void *pkt);
     410             : static int  initMasks(fd_set *rmask);
     411             : static void report_fork_failure_to_client(Port *port, int errnum);
     412             : static CAC_state canAcceptConnections(void);
     413             : static bool RandomCancelKey(int32 *cancel_key);
     414             : static void signal_child(pid_t pid, int signal);
     415             : static bool SignalSomeChildren(int signal, int targets);
     416             : static void TerminateChildren(int signal);
     417             : 
     418             : #define SignalChildren(sig)            SignalSomeChildren(sig, BACKEND_TYPE_ALL)
     419             : 
     420             : static int  CountChildren(int target);
     421             : static bool assign_backendlist_entry(RegisteredBgWorker *rw);
     422             : static void maybe_start_bgworkers(void);
     423             : static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
     424             : static pid_t StartChildProcess(AuxProcType type);
     425             : static void StartAutovacuumWorker(void);
     426             : static void MaybeStartWalReceiver(void);
     427             : static void InitPostmasterDeathWatchHandle(void);
     428             : 
     429             : /*
     430             :  * Archiver is allowed to start up at the current postmaster state?
     431             :  *
     432             :  * If WAL archiving is enabled always, we are allowed to start archiver
     433             :  * even during recovery.
     434             :  */
     435             : #define PgArchStartupAllowed()  \
     436             :     ((XLogArchivingActive() && pmState == PM_RUN) ||    \
     437             :      (XLogArchivingAlways() &&  \
     438             :       (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY)))
     439             : 
     440             : #ifdef EXEC_BACKEND
     441             : 
     442             : #ifdef WIN32
     443             : #define WNOHANG 0               /* ignored, so any integer value will do */
     444             : 
     445             : static pid_t waitpid(pid_t pid, int *exitstatus, int options);
     446             : static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
     447             : 
     448             : static HANDLE win32ChildQueue;
     449             : 
     450             : typedef struct
     451             : {
     452             :     HANDLE      waitHandle;
     453             :     HANDLE      procHandle;
     454             :     DWORD       procId;
     455             : } win32_deadchild_waitinfo;
     456             : #endif                          /* WIN32 */
     457             : 
     458             : static pid_t backend_forkexec(Port *port);
     459             : static pid_t internal_forkexec(int argc, char *argv[], Port *port);
     460             : 
     461             : /* Type for a socket that can be inherited to a client process */
     462             : #ifdef WIN32
     463             : typedef struct
     464             : {
     465             :     SOCKET      origsocket;     /* Original socket value, or PGINVALID_SOCKET
     466             :                                  * if not a socket */
     467             :     WSAPROTOCOL_INFO wsainfo;
     468             : } InheritableSocket;
     469             : #else
     470             : typedef int InheritableSocket;
     471             : #endif
     472             : 
     473             : /*
     474             :  * Structure contains all variables passed to exec:ed backends
     475             :  */
     476             : typedef struct
     477             : {
     478             :     Port        port;
     479             :     InheritableSocket portsocket;
     480             :     char        DataDir[MAXPGPATH];
     481             :     pgsocket    ListenSocket[MAXLISTEN];
     482             :     int32       MyCancelKey;
     483             :     int         MyPMChildSlot;
     484             : #ifndef WIN32
     485             :     unsigned long UsedShmemSegID;
     486             : #else
     487             :     void       *ShmemProtectiveRegion;
     488             :     HANDLE      UsedShmemSegID;
     489             : #endif
     490             :     void       *UsedShmemSegAddr;
     491             :     slock_t    *ShmemLock;
     492             :     VariableCache ShmemVariableCache;
     493             :     Backend    *ShmemBackendArray;
     494             : #ifndef HAVE_SPINLOCKS
     495             :     PGSemaphore *SpinlockSemaArray;
     496             : #endif
     497             :     int         NamedLWLockTrancheRequests;
     498             :     NamedLWLockTranche *NamedLWLockTrancheArray;
     499             :     LWLockPadded *MainLWLockArray;
     500             :     slock_t    *ProcStructLock;
     501             :     PROC_HDR   *ProcGlobal;
     502             :     PGPROC     *AuxiliaryProcs;
     503             :     PGPROC     *PreparedXactProcs;
     504             :     PMSignalData *PMSignalState;
     505             :     InheritableSocket pgStatSock;
     506             :     pid_t       PostmasterPid;
     507             :     TimestampTz PgStartTime;
     508             :     TimestampTz PgReloadTime;
     509             :     pg_time_t   first_syslogger_file_time;
     510             :     bool        redirection_done;
     511             :     bool        IsBinaryUpgrade;
     512             :     int         max_safe_fds;
     513             :     int         MaxBackends;
     514             : #ifdef WIN32
     515             :     HANDLE      PostmasterHandle;
     516             :     HANDLE      initial_signal_pipe;
     517             :     HANDLE      syslogPipe[2];
     518             : #else
     519             :     int         postmaster_alive_fds[2];
     520             :     int         syslogPipe[2];
     521             : #endif
     522             :     char        my_exec_path[MAXPGPATH];
     523             :     char        pkglib_path[MAXPGPATH];
     524             :     char        ExtraOptions[MAXPGPATH];
     525             : } BackendParameters;
     526             : 
     527             : static void read_backend_variables(char *id, Port *port);
     528             : static void restore_backend_variables(BackendParameters *param, Port *port);
     529             : 
     530             : #ifndef WIN32
     531             : static bool save_backend_variables(BackendParameters *param, Port *port);
     532             : #else
     533             : static bool save_backend_variables(BackendParameters *param, Port *port,
     534             :                                    HANDLE childProcess, pid_t childPid);
     535             : #endif
     536             : 
     537             : static void ShmemBackendArrayAdd(Backend *bn);
     538             : static void ShmemBackendArrayRemove(Backend *bn);
     539             : #endif                          /* EXEC_BACKEND */
     540             : 
     541             : #define StartupDataBase()       StartChildProcess(StartupProcess)
     542             : #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
     543             : #define StartCheckpointer()     StartChildProcess(CheckpointerProcess)
     544             : #define StartWalWriter()        StartChildProcess(WalWriterProcess)
     545             : #define StartWalReceiver()      StartChildProcess(WalReceiverProcess)
     546             : 
     547             : /* Macros to check exit status of a child process */
     548             : #define EXIT_STATUS_0(st)  ((st) == 0)
     549             : #define EXIT_STATUS_1(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 1)
     550             : #define EXIT_STATUS_3(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 3)
     551             : 
     552             : #ifndef WIN32
     553             : /*
     554             :  * File descriptors for pipe used to monitor if postmaster is alive.
     555             :  * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
     556             :  */
     557             : int         postmaster_alive_fds[2] = {-1, -1};
     558             : #else
     559             : /* Process handle of postmaster used for the same purpose on Windows */
     560             : HANDLE      PostmasterHandle;
     561             : #endif
     562             : 
     563             : /*
     564             :  * Postmaster main entry point
     565             :  */
     566             : void
     567         580 : PostmasterMain(int argc, char *argv[])
     568             : {
     569             :     int         opt;
     570             :     int         status;
     571         580 :     char       *userDoption = NULL;
     572         580 :     bool        listen_addr_saved = false;
     573             :     int         i;
     574         580 :     char       *output_config_variable = NULL;
     575             : 
     576         580 :     InitProcessGlobals();
     577             : 
     578         580 :     PostmasterPid = MyProcPid;
     579             : 
     580         580 :     IsPostmasterEnvironment = true;
     581             : 
     582             :     /*
     583             :      * We should not be creating any files or directories before we check the
     584             :      * data directory (see checkDataDir()), but just in case set the umask to
     585             :      * the most restrictive (owner-only) permissions.
     586             :      *
     587             :      * checkDataDir() will reset the umask based on the data directory
     588             :      * permissions.
     589             :      */
     590         580 :     umask(PG_MODE_MASK_OWNER);
     591             : 
     592             :     /*
     593             :      * By default, palloc() requests in the postmaster will be allocated in
     594             :      * the PostmasterContext, which is space that can be recycled by backends.
     595             :      * Allocated data that needs to be available to backends should be
     596             :      * allocated in TopMemoryContext.
     597             :      */
     598         580 :     PostmasterContext = AllocSetContextCreate(TopMemoryContext,
     599             :                                               "Postmaster",
     600             :                                               ALLOCSET_DEFAULT_SIZES);
     601         580 :     MemoryContextSwitchTo(PostmasterContext);
     602             : 
     603             :     /* Initialize paths to installation files */
     604         580 :     getInstallationPaths(argv[0]);
     605             : 
     606             :     /*
     607             :      * Set up signal handlers for the postmaster process.
     608             :      *
     609             :      * In the postmaster, we want to install non-ignored handlers *without*
     610             :      * SA_RESTART.  This is because they'll be blocked at all times except
     611             :      * when ServerLoop is waiting for something to happen, and during that
     612             :      * window, we want signals to exit the select(2) wait so that ServerLoop
     613             :      * can respond if anything interesting happened.  On some platforms,
     614             :      * signals marked SA_RESTART would not cause the select() wait to end.
     615             :      * Child processes will generally want SA_RESTART, but we expect them to
     616             :      * set up their own handlers before unblocking signals.
     617             :      *
     618             :      * CAUTION: when changing this list, check for side-effects on the signal
     619             :      * handling setup of child processes.  See tcop/postgres.c,
     620             :      * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
     621             :      * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/pgstat.c,
     622             :      * postmaster/syslogger.c, postmaster/bgworker.c and
     623             :      * postmaster/checkpointer.c.
     624             :      */
     625         580 :     pqinitmask();
     626         580 :     PG_SETMASK(&BlockSig);
     627             : 
     628         580 :     pqsignal_no_restart(SIGHUP, SIGHUP_handler);    /* reread config file and
     629             :                                                      * have children do same */
     630         580 :     pqsignal_no_restart(SIGINT, pmdie); /* send SIGTERM and shut down */
     631         580 :     pqsignal_no_restart(SIGQUIT, pmdie);    /* send SIGQUIT and die */
     632         580 :     pqsignal_no_restart(SIGTERM, pmdie);    /* wait for children and shut down */
     633         580 :     pqsignal(SIGALRM, SIG_IGN); /* ignored */
     634         580 :     pqsignal(SIGPIPE, SIG_IGN); /* ignored */
     635         580 :     pqsignal_no_restart(SIGUSR1, sigusr1_handler);  /* message from child
     636             :                                                      * process */
     637         580 :     pqsignal_no_restart(SIGUSR2, dummy_handler);    /* unused, reserve for
     638             :                                                      * children */
     639         580 :     pqsignal_no_restart(SIGCHLD, reaper);   /* handle child termination */
     640             : 
     641             :     /*
     642             :      * No other place in Postgres should touch SIGTTIN/SIGTTOU handling.  We
     643             :      * ignore those signals in a postmaster environment, so that there is no
     644             :      * risk of a child process freezing up due to writing to stderr.  But for
     645             :      * a standalone backend, their default handling is reasonable.  Hence, all
     646             :      * child processes should just allow the inherited settings to stand.
     647             :      */
     648             : #ifdef SIGTTIN
     649         580 :     pqsignal(SIGTTIN, SIG_IGN); /* ignored */
     650             : #endif
     651             : #ifdef SIGTTOU
     652         580 :     pqsignal(SIGTTOU, SIG_IGN); /* ignored */
     653             : #endif
     654             : 
     655             :     /* ignore SIGXFSZ, so that ulimit violations work like disk full */
     656             : #ifdef SIGXFSZ
     657         580 :     pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
     658             : #endif
     659             : 
     660             :     /*
     661             :      * Options setup
     662             :      */
     663         580 :     InitializeGUCOptions();
     664             : 
     665         580 :     opterr = 1;
     666             : 
     667             :     /*
     668             :      * Parse command-line options.  CAUTION: keep this in sync with
     669             :      * tcop/postgres.c (the option sets should not conflict) and with the
     670             :      * common help() function in main/main.c.
     671             :      */
     672        2610 :     while ((opt = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:W:-:")) != -1)
     673             :     {
     674        1450 :         switch (opt)
     675             :         {
     676             :             case 'B':
     677           0 :                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     678           0 :                 break;
     679             : 
     680             :             case 'b':
     681             :                 /* Undocumented flag used for binary upgrades */
     682           8 :                 IsBinaryUpgrade = true;
     683           8 :                 break;
     684             : 
     685             :             case 'C':
     686           0 :                 output_config_variable = strdup(optarg);
     687           0 :                 break;
     688             : 
     689             :             case 'D':
     690         576 :                 userDoption = strdup(optarg);
     691         576 :                 break;
     692             : 
     693             :             case 'd':
     694           0 :                 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
     695           0 :                 break;
     696             : 
     697             :             case 'E':
     698           0 :                 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
     699           0 :                 break;
     700             : 
     701             :             case 'e':
     702           0 :                 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
     703           0 :                 break;
     704             : 
     705             :             case 'F':
     706         132 :                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
     707         132 :                 break;
     708             : 
     709             :             case 'f':
     710           0 :                 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
     711             :                 {
     712           0 :                     write_stderr("%s: invalid argument for option -f: \"%s\"\n",
     713             :                                  progname, optarg);
     714           0 :                     ExitPostmaster(1);
     715             :                 }
     716           0 :                 break;
     717             : 
     718             :             case 'h':
     719           0 :                 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     720           0 :                 break;
     721             : 
     722             :             case 'i':
     723           0 :                 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
     724           0 :                 break;
     725             : 
     726             :             case 'j':
     727             :                 /* only used by interactive backend */
     728           0 :                 break;
     729             : 
     730             :             case 'k':
     731         132 :                 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     732         132 :                 break;
     733             : 
     734             :             case 'l':
     735           0 :                 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
     736           0 :                 break;
     737             : 
     738             :             case 'N':
     739           0 :                 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     740           0 :                 break;
     741             : 
     742             :             case 'n':
     743             :                 /* Don't reinit shared mem after abnormal exit */
     744           0 :                 Reinit = false;
     745           0 :                 break;
     746             : 
     747             :             case 'O':
     748           0 :                 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
     749           0 :                 break;
     750             : 
     751             :             case 'o':
     752             :                 /* Other options to pass to the backend on the command line */
     753           0 :                 snprintf(ExtraOptions + strlen(ExtraOptions),
     754           0 :                          sizeof(ExtraOptions) - strlen(ExtraOptions),
     755             :                          " %s", optarg);
     756           0 :                 break;
     757             : 
     758             :             case 'P':
     759           0 :                 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
     760           0 :                 break;
     761             : 
     762             :             case 'p':
     763           8 :                 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     764           8 :                 break;
     765             : 
     766             :             case 'r':
     767             :                 /* only used by single-user backend */
     768           0 :                 break;
     769             : 
     770             :             case 'S':
     771           0 :                 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     772           0 :                 break;
     773             : 
     774             :             case 's':
     775           0 :                 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
     776           0 :                 break;
     777             : 
     778             :             case 'T':
     779             : 
     780             :                 /*
     781             :                  * In the event that some backend dumps core, send SIGSTOP,
     782             :                  * rather than SIGQUIT, to all its peers.  This lets the wily
     783             :                  * post_hacker collect core dumps from everyone.
     784             :                  */
     785           0 :                 SendStop = true;
     786           0 :                 break;
     787             : 
     788             :             case 't':
     789             :                 {
     790           0 :                     const char *tmp = get_stats_option_name(optarg);
     791             : 
     792           0 :                     if (tmp)
     793             :                     {
     794           0 :                         SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
     795             :                     }
     796             :                     else
     797             :                     {
     798           0 :                         write_stderr("%s: invalid argument for option -t: \"%s\"\n",
     799             :                                      progname, optarg);
     800           0 :                         ExitPostmaster(1);
     801             :                     }
     802           0 :                     break;
     803             :                 }
     804             : 
     805             :             case 'W':
     806           0 :                 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     807           0 :                 break;
     808             : 
     809             :             case 'c':
     810             :             case '-':
     811             :                 {
     812             :                     char       *name,
     813             :                                *value;
     814             : 
     815         594 :                     ParseLongOption(optarg, &name, &value);
     816         594 :                     if (!value)
     817             :                     {
     818           0 :                         if (opt == '-')
     819           0 :                             ereport(ERROR,
     820             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
     821             :                                      errmsg("--%s requires a value",
     822             :                                             optarg)));
     823             :                         else
     824           0 :                             ereport(ERROR,
     825             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
     826             :                                      errmsg("-c %s requires a value",
     827             :                                             optarg)));
     828             :                     }
     829             : 
     830         594 :                     SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
     831         594 :                     free(name);
     832         594 :                     if (value)
     833         594 :                         free(value);
     834         594 :                     break;
     835             :                 }
     836             : 
     837             :             default:
     838           0 :                 write_stderr("Try \"%s --help\" for more information.\n",
     839             :                              progname);
     840           0 :                 ExitPostmaster(1);
     841             :         }
     842             :     }
     843             : 
     844             :     /*
     845             :      * Postmaster accepts no non-option switch arguments.
     846             :      */
     847         580 :     if (optind < argc)
     848             :     {
     849           0 :         write_stderr("%s: invalid argument: \"%s\"\n",
     850           0 :                      progname, argv[optind]);
     851           0 :         write_stderr("Try \"%s --help\" for more information.\n",
     852             :                      progname);
     853           0 :         ExitPostmaster(1);
     854             :     }
     855             : 
     856             :     /*
     857             :      * Locate the proper configuration files and data directory, and read
     858             :      * postgresql.conf for the first time.
     859             :      */
     860         580 :     if (!SelectConfigFiles(userDoption, progname))
     861           0 :         ExitPostmaster(2);
     862             : 
     863         578 :     if (output_config_variable != NULL)
     864             :     {
     865             :         /*
     866             :          * "-C guc" was specified, so print GUC's value and exit.  No extra
     867             :          * permission check is needed because the user is reading inside the
     868             :          * data dir.
     869             :          */
     870           0 :         const char *config_val = GetConfigOption(output_config_variable,
     871             :                                                  false, false);
     872             : 
     873           0 :         puts(config_val ? config_val : "");
     874           0 :         ExitPostmaster(0);
     875             :     }
     876             : 
     877             :     /* Verify that DataDir looks reasonable */
     878         578 :     checkDataDir();
     879             : 
     880             :     /* Check that pg_control exists */
     881         578 :     checkControlFile();
     882             : 
     883             :     /* And switch working directory into it */
     884         578 :     ChangeToDataDir();
     885             : 
     886             :     /*
     887             :      * Check for invalid combinations of GUC settings.
     888             :      */
     889         578 :     if (ReservedBackends >= MaxConnections)
     890             :     {
     891           0 :         write_stderr("%s: superuser_reserved_connections (%d) must be less than max_connections (%d)\n",
     892             :                      progname,
     893             :                      ReservedBackends, MaxConnections);
     894           0 :         ExitPostmaster(1);
     895             :     }
     896         578 :     if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL)
     897           0 :         ereport(ERROR,
     898             :                 (errmsg("WAL archival cannot be enabled when wal_level is \"minimal\"")));
     899         578 :     if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
     900           0 :         ereport(ERROR,
     901             :                 (errmsg("WAL streaming (max_wal_senders > 0) requires wal_level \"replica\" or \"logical\"")));
     902             : 
     903             :     /*
     904             :      * Other one-time internal sanity checks can go here, if they are fast.
     905             :      * (Put any slow processing further down, after postmaster.pid creation.)
     906             :      */
     907         578 :     if (!CheckDateTokenTables())
     908             :     {
     909           0 :         write_stderr("%s: invalid datetoken tables, please fix\n", progname);
     910           0 :         ExitPostmaster(1);
     911             :     }
     912             : 
     913             :     /*
     914             :      * Now that we are done processing the postmaster arguments, reset
     915             :      * getopt(3) library so that it will work correctly in subprocesses.
     916             :      */
     917         578 :     optind = 1;
     918             : #ifdef HAVE_INT_OPTRESET
     919             :     optreset = 1;               /* some systems need this too */
     920             : #endif
     921             : 
     922             :     /* For debugging: display postmaster environment */
     923             :     {
     924             :         extern char **environ;
     925             :         char      **p;
     926             : 
     927         578 :         ereport(DEBUG3,
     928             :                 (errmsg_internal("%s: PostmasterMain: initial environment dump:",
     929             :                                  progname)));
     930         578 :         ereport(DEBUG3,
     931             :                 (errmsg_internal("-----------------------------------------")));
     932       20368 :         for (p = environ; *p; ++p)
     933       19790 :             ereport(DEBUG3,
     934             :                     (errmsg_internal("\t%s", *p)));
     935         578 :         ereport(DEBUG3,
     936             :                 (errmsg_internal("-----------------------------------------")));
     937             :     }
     938             : 
     939             :     /*
     940             :      * Create lockfile for data directory.
     941             :      *
     942             :      * We want to do this before we try to grab the input sockets, because the
     943             :      * data directory interlock is more reliable than the socket-file
     944             :      * interlock (thanks to whoever decided to put socket files in /tmp :-().
     945             :      * For the same reason, it's best to grab the TCP socket(s) before the
     946             :      * Unix socket(s).
     947             :      *
     948             :      * Also note that this internally sets up the on_proc_exit function that
     949             :      * is responsible for removing both data directory and socket lockfiles;
     950             :      * so it must happen before opening sockets so that at exit, the socket
     951             :      * lockfiles go away after CloseServerPorts runs.
     952             :      */
     953         578 :     CreateDataDirLockFile(true);
     954             : 
     955             :     /*
     956             :      * Read the control file (for error checking and config info).
     957             :      *
     958             :      * Since we verify the control file's CRC, this has a useful side effect
     959             :      * on machines where we need a run-time test for CRC support instructions.
     960             :      * The postmaster will do the test once at startup, and then its child
     961             :      * processes will inherit the correct function pointer and not need to
     962             :      * repeat the test.
     963             :      */
     964         576 :     LocalProcessControlFile(false);
     965             : 
     966             :     /*
     967             :      * Initialize SSL library, if specified.
     968             :      */
     969             : #ifdef USE_SSL
     970         576 :     if (EnableSSL)
     971             :     {
     972          20 :         (void) secure_initialize(true);
     973          18 :         LoadedSSL = true;
     974             :     }
     975             : #endif
     976             : 
     977             :     /*
     978             :      * Register the apply launcher.  Since it registers a background worker,
     979             :      * it needs to be called before InitializeMaxBackends(), and it's probably
     980             :      * a good idea to call it before any modules had chance to take the
     981             :      * background worker slots.
     982             :      */
     983         574 :     ApplyLauncherRegister();
     984             : 
     985             :     /*
     986             :      * process any libraries that should be preloaded at postmaster start
     987             :      */
     988         574 :     process_shared_preload_libraries();
     989             : 
     990             :     /*
     991             :      * Now that loadable modules have had their chance to register background
     992             :      * workers, calculate MaxBackends.
     993             :      */
     994         574 :     InitializeMaxBackends();
     995             : 
     996             :     /*
     997             :      * Set up shared memory and semaphores.
     998             :      */
     999         574 :     reset_shared();
    1000             : 
    1001             :     /*
    1002             :      * Estimate number of openable files.  This must happen after setting up
    1003             :      * semaphores, because on some platforms semaphores count as open files.
    1004             :      */
    1005         572 :     set_max_safe_fds();
    1006             : 
    1007             :     /*
    1008             :      * Set reference point for stack-depth checking.
    1009             :      */
    1010         572 :     set_stack_base();
    1011             : 
    1012             :     /*
    1013             :      * Initialize pipe (or process handle on Windows) that allows children to
    1014             :      * wake up from sleep on postmaster death.
    1015             :      */
    1016         572 :     InitPostmasterDeathWatchHandle();
    1017             : 
    1018             : #ifdef WIN32
    1019             : 
    1020             :     /*
    1021             :      * Initialize I/O completion port used to deliver list of dead children.
    1022             :      */
    1023             :     win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
    1024             :     if (win32ChildQueue == NULL)
    1025             :         ereport(FATAL,
    1026             :                 (errmsg("could not create I/O completion port for child queue")));
    1027             : #endif
    1028             : 
    1029             : #ifdef EXEC_BACKEND
    1030             :     /* Write out nondefault GUC settings for child processes to use */
    1031             :     write_nondefault_variables(PGC_POSTMASTER);
    1032             : 
    1033             :     /*
    1034             :      * Clean out the temp directory used to transmit parameters to child
    1035             :      * processes (see internal_forkexec, below).  We must do this before
    1036             :      * launching any child processes, else we have a race condition: we could
    1037             :      * remove a parameter file before the child can read it.  It should be
    1038             :      * safe to do so now, because we verified earlier that there are no
    1039             :      * conflicting Postgres processes in this data directory.
    1040             :      */
    1041             :     RemovePgTempFilesInDir(PG_TEMP_FILES_DIR, true, false);
    1042             : #endif
    1043             : 
    1044             :     /*
    1045             :      * Forcibly remove the files signaling a standby promotion request.
    1046             :      * Otherwise, the existence of those files triggers a promotion too early,
    1047             :      * whether a user wants that or not.
    1048             :      *
    1049             :      * This removal of files is usually unnecessary because they can exist
    1050             :      * only during a few moments during a standby promotion. However there is
    1051             :      * a race condition: if pg_ctl promote is executed and creates the files
    1052             :      * during a promotion, the files can stay around even after the server is
    1053             :      * brought up to new master. Then, if new standby starts by using the
    1054             :      * backup taken from that master, the files can exist at the server
    1055             :      * startup and should be removed in order to avoid an unexpected
    1056             :      * promotion.
    1057             :      *
    1058             :      * Note that promotion signal files need to be removed before the startup
    1059             :      * process is invoked. Because, after that, they can be used by
    1060             :      * postmaster's SIGUSR1 signal handler.
    1061             :      */
    1062         572 :     RemovePromoteSignalFiles();
    1063             : 
    1064             :     /* Do the same for logrotate signal file */
    1065         572 :     RemoveLogrotateSignalFiles();
    1066             : 
    1067             :     /* Remove any outdated file holding the current log filenames. */
    1068         572 :     if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
    1069           0 :         ereport(LOG,
    1070             :                 (errcode_for_file_access(),
    1071             :                  errmsg("could not remove file \"%s\": %m",
    1072             :                         LOG_METAINFO_DATAFILE)));
    1073             : 
    1074             :     /*
    1075             :      * If enabled, start up syslogger collection subprocess
    1076             :      */
    1077         572 :     SysLoggerPID = SysLogger_Start();
    1078             : 
    1079             :     /*
    1080             :      * Reset whereToSendOutput from DestDebug (its starting state) to
    1081             :      * DestNone. This stops ereport from sending log messages to stderr unless
    1082             :      * Log_destination permits.  We don't do this until the postmaster is
    1083             :      * fully launched, since startup failures may as well be reported to
    1084             :      * stderr.
    1085             :      *
    1086             :      * If we are in fact disabling logging to stderr, first emit a log message
    1087             :      * saying so, to provide a breadcrumb trail for users who may not remember
    1088             :      * that their logging is configured to go somewhere else.
    1089             :      */
    1090         572 :     if (!(Log_destination & LOG_DESTINATION_STDERR))
    1091           0 :         ereport(LOG,
    1092             :                 (errmsg("ending log output to stderr"),
    1093             :                  errhint("Future log output will go to log destination \"%s\".",
    1094             :                          Log_destination_string)));
    1095             : 
    1096         572 :     whereToSendOutput = DestNone;
    1097             : 
    1098             :     /*
    1099             :      * Report server startup in log.  While we could emit this much earlier,
    1100             :      * it seems best to do so after starting the log collector, if we intend
    1101             :      * to use one.
    1102             :      */
    1103         572 :     ereport(LOG,
    1104             :             (errmsg("starting %s", PG_VERSION_STR)));
    1105             : 
    1106             :     /*
    1107             :      * Establish input sockets.
    1108             :      *
    1109             :      * First, mark them all closed, and set up an on_proc_exit function that's
    1110             :      * charged with closing the sockets again at postmaster shutdown.
    1111             :      */
    1112       37180 :     for (i = 0; i < MAXLISTEN; i++)
    1113       36608 :         ListenSocket[i] = PGINVALID_SOCKET;
    1114             : 
    1115         572 :     on_proc_exit(CloseServerPorts, 0);
    1116             : 
    1117         572 :     if (ListenAddresses)
    1118             :     {
    1119             :         char       *rawstring;
    1120             :         List       *elemlist;
    1121             :         ListCell   *l;
    1122         572 :         int         success = 0;
    1123             : 
    1124             :         /* Need a modifiable copy of ListenAddresses */
    1125         572 :         rawstring = pstrdup(ListenAddresses);
    1126             : 
    1127             :         /* Parse string into list of hostnames */
    1128         572 :         if (!SplitIdentifierString(rawstring, ',', &elemlist))
    1129             :         {
    1130             :             /* syntax error in list */
    1131           0 :             ereport(FATAL,
    1132             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1133             :                      errmsg("invalid list syntax in parameter \"%s\"",
    1134             :                             "listen_addresses")));
    1135             :         }
    1136             : 
    1137         596 :         foreach(l, elemlist)
    1138             :         {
    1139          24 :             char       *curhost = (char *) lfirst(l);
    1140             : 
    1141          24 :             if (strcmp(curhost, "*") == 0)
    1142           0 :                 status = StreamServerPort(AF_UNSPEC, NULL,
    1143           0 :                                           (unsigned short) PostPortNumber,
    1144             :                                           NULL,
    1145             :                                           ListenSocket, MAXLISTEN);
    1146             :             else
    1147          24 :                 status = StreamServerPort(AF_UNSPEC, curhost,
    1148          24 :                                           (unsigned short) PostPortNumber,
    1149             :                                           NULL,
    1150             :                                           ListenSocket, MAXLISTEN);
    1151             : 
    1152          24 :             if (status == STATUS_OK)
    1153             :             {
    1154          24 :                 success++;
    1155             :                 /* record the first successful host addr in lockfile */
    1156          24 :                 if (!listen_addr_saved)
    1157             :                 {
    1158          24 :                     AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
    1159          24 :                     listen_addr_saved = true;
    1160             :                 }
    1161             :             }
    1162             :             else
    1163           0 :                 ereport(WARNING,
    1164             :                         (errmsg("could not create listen socket for \"%s\"",
    1165             :                                 curhost)));
    1166             :         }
    1167             : 
    1168         572 :         if (!success && elemlist != NIL)
    1169           0 :             ereport(FATAL,
    1170             :                     (errmsg("could not create any TCP/IP sockets")));
    1171             : 
    1172         572 :         list_free(elemlist);
    1173         572 :         pfree(rawstring);
    1174             :     }
    1175             : 
    1176             : #ifdef USE_BONJOUR
    1177             :     /* Register for Bonjour only if we opened TCP socket(s) */
    1178             :     if (enable_bonjour && ListenSocket[0] != PGINVALID_SOCKET)
    1179             :     {
    1180             :         DNSServiceErrorType err;
    1181             : 
    1182             :         /*
    1183             :          * We pass 0 for interface_index, which will result in registering on
    1184             :          * all "applicable" interfaces.  It's not entirely clear from the
    1185             :          * DNS-SD docs whether this would be appropriate if we have bound to
    1186             :          * just a subset of the available network interfaces.
    1187             :          */
    1188             :         err = DNSServiceRegister(&bonjour_sdref,
    1189             :                                  0,
    1190             :                                  0,
    1191             :                                  bonjour_name,
    1192             :                                  "_postgresql._tcp.",
    1193             :                                  NULL,
    1194             :                                  NULL,
    1195             :                                  pg_hton16(PostPortNumber),
    1196             :                                  0,
    1197             :                                  NULL,
    1198             :                                  NULL,
    1199             :                                  NULL);
    1200             :         if (err != kDNSServiceErr_NoError)
    1201             :             elog(LOG, "DNSServiceRegister() failed: error code %ld",
    1202             :                  (long) err);
    1203             : 
    1204             :         /*
    1205             :          * We don't bother to read the mDNS daemon's reply, and we expect that
    1206             :          * it will automatically terminate our registration when the socket is
    1207             :          * closed at postmaster termination.  So there's nothing more to be
    1208             :          * done here.  However, the bonjour_sdref is kept around so that
    1209             :          * forked children can close their copies of the socket.
    1210             :          */
    1211             :     }
    1212             : #endif
    1213             : 
    1214             : #ifdef HAVE_UNIX_SOCKETS
    1215         572 :     if (Unix_socket_directories)
    1216             :     {
    1217             :         char       *rawstring;
    1218             :         List       *elemlist;
    1219             :         ListCell   *l;
    1220         572 :         int         success = 0;
    1221             : 
    1222             :         /* Need a modifiable copy of Unix_socket_directories */
    1223         572 :         rawstring = pstrdup(Unix_socket_directories);
    1224             : 
    1225             :         /* Parse string into list of directories */
    1226         572 :         if (!SplitDirectoriesString(rawstring, ',', &elemlist))
    1227             :         {
    1228             :             /* syntax error in list */
    1229           0 :             ereport(FATAL,
    1230             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1231             :                      errmsg("invalid list syntax in parameter \"%s\"",
    1232             :                             "unix_socket_directories")));
    1233             :         }
    1234             : 
    1235        1142 :         foreach(l, elemlist)
    1236             :         {
    1237         570 :             char       *socketdir = (char *) lfirst(l);
    1238             : 
    1239         570 :             status = StreamServerPort(AF_UNIX, NULL,
    1240         570 :                                       (unsigned short) PostPortNumber,
    1241             :                                       socketdir,
    1242             :                                       ListenSocket, MAXLISTEN);
    1243             : 
    1244         570 :             if (status == STATUS_OK)
    1245             :             {
    1246         570 :                 success++;
    1247             :                 /* record the first successful Unix socket in lockfile */
    1248         570 :                 if (success == 1)
    1249         570 :                     AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
    1250             :             }
    1251             :             else
    1252           0 :                 ereport(WARNING,
    1253             :                         (errmsg("could not create Unix-domain socket in directory \"%s\"",
    1254             :                                 socketdir)));
    1255             :         }
    1256             : 
    1257         572 :         if (!success && elemlist != NIL)
    1258           0 :             ereport(FATAL,
    1259             :                     (errmsg("could not create any Unix-domain sockets")));
    1260             : 
    1261         572 :         list_free_deep(elemlist);
    1262         572 :         pfree(rawstring);
    1263             :     }
    1264             : #endif
    1265             : 
    1266             :     /*
    1267             :      * check that we have some socket to listen on
    1268             :      */
    1269         572 :     if (ListenSocket[0] == PGINVALID_SOCKET)
    1270           0 :         ereport(FATAL,
    1271             :                 (errmsg("no socket created for listening")));
    1272             : 
    1273             :     /*
    1274             :      * If no valid TCP ports, write an empty line for listen address,
    1275             :      * indicating the Unix socket must be used.  Note that this line is not
    1276             :      * added to the lock file until there is a socket backing it.
    1277             :      */
    1278         572 :     if (!listen_addr_saved)
    1279         548 :         AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
    1280             : 
    1281             :     /*
    1282             :      * Record postmaster options.  We delay this till now to avoid recording
    1283             :      * bogus options (eg, unusable port number).
    1284             :      */
    1285         572 :     if (!CreateOptsFile(argc, argv, my_exec_path))
    1286           0 :         ExitPostmaster(1);
    1287             : 
    1288             :     /*
    1289             :      * Write the external PID file if requested
    1290             :      */
    1291         572 :     if (external_pid_file)
    1292             :     {
    1293           0 :         FILE       *fpidfile = fopen(external_pid_file, "w");
    1294             : 
    1295           0 :         if (fpidfile)
    1296             :         {
    1297           0 :             fprintf(fpidfile, "%d\n", MyProcPid);
    1298           0 :             fclose(fpidfile);
    1299             : 
    1300             :             /* Make PID file world readable */
    1301           0 :             if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
    1302           0 :                 write_stderr("%s: could not change permissions of external PID file \"%s\": %s\n",
    1303           0 :                              progname, external_pid_file, strerror(errno));
    1304             :         }
    1305             :         else
    1306           0 :             write_stderr("%s: could not write external PID file \"%s\": %s\n",
    1307           0 :                          progname, external_pid_file, strerror(errno));
    1308             : 
    1309           0 :         on_proc_exit(unlink_external_pid_file, 0);
    1310             :     }
    1311             : 
    1312             :     /*
    1313             :      * Remove old temporary files.  At this point there can be no other
    1314             :      * Postgres processes running in this directory, so this should be safe.
    1315             :      */
    1316         572 :     RemovePgTempFiles();
    1317             : 
    1318             :     /*
    1319             :      * Initialize stats collection subsystem (this does NOT start the
    1320             :      * collector process!)
    1321             :      */
    1322         572 :     pgstat_init();
    1323             : 
    1324             :     /*
    1325             :      * Initialize the autovacuum subsystem (again, no process start yet)
    1326             :      */
    1327         572 :     autovac_init();
    1328             : 
    1329             :     /*
    1330             :      * Load configuration files for client authentication.
    1331             :      */
    1332         572 :     if (!load_hba())
    1333             :     {
    1334             :         /*
    1335             :          * It makes no sense to continue if we fail to load the HBA file,
    1336             :          * since there is no way to connect to the database in this case.
    1337             :          */
    1338           0 :         ereport(FATAL,
    1339             :                 (errmsg("could not load pg_hba.conf")));
    1340             :     }
    1341         572 :     if (!load_ident())
    1342             :     {
    1343             :         /*
    1344             :          * We can start up without the IDENT file, although it means that you
    1345             :          * cannot log in using any of the authentication methods that need a
    1346             :          * user name mapping. load_ident() already logged the details of error
    1347             :          * to the log.
    1348             :          */
    1349             :     }
    1350             : 
    1351             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
    1352             : 
    1353             :     /*
    1354             :      * On macOS, libintl replaces setlocale() with a version that calls
    1355             :      * CFLocaleCopyCurrent() when its second argument is "" and every relevant
    1356             :      * environment variable is unset or empty.  CFLocaleCopyCurrent() makes
    1357             :      * the process multithreaded.  The postmaster calls sigprocmask() and
    1358             :      * calls fork() without an immediate exec(), both of which have undefined
    1359             :      * behavior in a multithreaded program.  A multithreaded postmaster is the
    1360             :      * normal case on Windows, which offers neither fork() nor sigprocmask().
    1361             :      */
    1362             :     if (pthread_is_threaded_np() != 0)
    1363             :         ereport(FATAL,
    1364             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1365             :                  errmsg("postmaster became multithreaded during startup"),
    1366             :                  errhint("Set the LC_ALL environment variable to a valid locale.")));
    1367             : #endif
    1368             : 
    1369             :     /*
    1370             :      * Remember postmaster startup time
    1371             :      */
    1372         572 :     PgStartTime = GetCurrentTimestamp();
    1373             : 
    1374             :     /*
    1375             :      * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
    1376             :      * see what's happening.
    1377             :      */
    1378         572 :     AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STARTING);
    1379             : 
    1380             :     /*
    1381             :      * We're ready to rock and roll...
    1382             :      */
    1383         572 :     StartupPID = StartupDataBase();
    1384             :     Assert(StartupPID != 0);
    1385         572 :     StartupStatus = STARTUP_RUNNING;
    1386         572 :     pmState = PM_STARTUP;
    1387             : 
    1388             :     /* Some workers may be scheduled to start now */
    1389         572 :     maybe_start_bgworkers();
    1390             : 
    1391         572 :     status = ServerLoop();
    1392             : 
    1393             :     /*
    1394             :      * ServerLoop probably shouldn't ever return, but if it does, close down.
    1395             :      */
    1396           0 :     ExitPostmaster(status != STATUS_OK);
    1397             : 
    1398             :     abort();                    /* not reached */
    1399             : }
    1400             : 
    1401             : 
    1402             : /*
    1403             :  * on_proc_exit callback to close server's listen sockets
    1404             :  */
    1405             : static void
    1406         566 : CloseServerPorts(int status, Datum arg)
    1407             : {
    1408             :     int         i;
    1409             : 
    1410             :     /*
    1411             :      * First, explicitly close all the socket FDs.  We used to just let this
    1412             :      * happen implicitly at postmaster exit, but it's better to close them
    1413             :      * before we remove the postmaster.pid lockfile; otherwise there's a race
    1414             :      * condition if a new postmaster wants to re-use the TCP port number.
    1415             :      */
    1416       36790 :     for (i = 0; i < MAXLISTEN; i++)
    1417             :     {
    1418       36224 :         if (ListenSocket[i] != PGINVALID_SOCKET)
    1419             :         {
    1420         590 :             StreamClose(ListenSocket[i]);
    1421         590 :             ListenSocket[i] = PGINVALID_SOCKET;
    1422             :         }
    1423             :     }
    1424             : 
    1425             :     /*
    1426             :      * Next, remove any filesystem entries for Unix sockets.  To avoid race
    1427             :      * conditions against incoming postmasters, this must happen after closing
    1428             :      * the sockets and before removing lock files.
    1429             :      */
    1430         566 :     RemoveSocketFiles();
    1431             : 
    1432             :     /*
    1433             :      * We don't do anything about socket lock files here; those will be
    1434             :      * removed in a later on_proc_exit callback.
    1435             :      */
    1436         566 : }
    1437             : 
    1438             : /*
    1439             :  * on_proc_exit callback to delete external_pid_file
    1440             :  */
    1441             : static void
    1442           0 : unlink_external_pid_file(int status, Datum arg)
    1443             : {
    1444           0 :     if (external_pid_file)
    1445           0 :         unlink(external_pid_file);
    1446           0 : }
    1447             : 
    1448             : 
    1449             : /*
    1450             :  * Compute and check the directory paths to files that are part of the
    1451             :  * installation (as deduced from the postgres executable's own location)
    1452             :  */
    1453             : static void
    1454         580 : getInstallationPaths(const char *argv0)
    1455             : {
    1456             :     DIR        *pdir;
    1457             : 
    1458             :     /* Locate the postgres executable itself */
    1459         580 :     if (find_my_exec(argv0, my_exec_path) < 0)
    1460           0 :         elog(FATAL, "%s: could not locate my own executable path", argv0);
    1461             : 
    1462             : #ifdef EXEC_BACKEND
    1463             :     /* Locate executable backend before we change working directory */
    1464             :     if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
    1465             :                         postgres_exec_path) < 0)
    1466             :         ereport(FATAL,
    1467             :                 (errmsg("%s: could not locate matching postgres executable",
    1468             :                         argv0)));
    1469             : #endif
    1470             : 
    1471             :     /*
    1472             :      * Locate the pkglib directory --- this has to be set early in case we try
    1473             :      * to load any modules from it in response to postgresql.conf entries.
    1474             :      */
    1475         580 :     get_pkglib_path(my_exec_path, pkglib_path);
    1476             : 
    1477             :     /*
    1478             :      * Verify that there's a readable directory there; otherwise the Postgres
    1479             :      * installation is incomplete or corrupt.  (A typical cause of this
    1480             :      * failure is that the postgres executable has been moved or hardlinked to
    1481             :      * some directory that's not a sibling of the installation lib/
    1482             :      * directory.)
    1483             :      */
    1484         580 :     pdir = AllocateDir(pkglib_path);
    1485         580 :     if (pdir == NULL)
    1486           0 :         ereport(ERROR,
    1487             :                 (errcode_for_file_access(),
    1488             :                  errmsg("could not open directory \"%s\": %m",
    1489             :                         pkglib_path),
    1490             :                  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
    1491             :                          my_exec_path)));
    1492         580 :     FreeDir(pdir);
    1493             : 
    1494             :     /*
    1495             :      * XXX is it worth similarly checking the share/ directory?  If the lib/
    1496             :      * directory is there, then share/ probably is too.
    1497             :      */
    1498         580 : }
    1499             : 
    1500             : /*
    1501             :  * Check that pg_control exists in the correct location in the data directory.
    1502             :  *
    1503             :  * No attempt is made to validate the contents of pg_control here.  This is
    1504             :  * just a sanity check to see if we are looking at a real data directory.
    1505             :  */
    1506             : static void
    1507         578 : checkControlFile(void)
    1508             : {
    1509             :     char        path[MAXPGPATH];
    1510             :     FILE       *fp;
    1511             : 
    1512         578 :     snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
    1513             : 
    1514         578 :     fp = AllocateFile(path, PG_BINARY_R);
    1515         578 :     if (fp == NULL)
    1516             :     {
    1517           0 :         write_stderr("%s: could not find the database system\n"
    1518             :                      "Expected to find it in the directory \"%s\",\n"
    1519             :                      "but could not open file \"%s\": %s\n",
    1520           0 :                      progname, DataDir, path, strerror(errno));
    1521           0 :         ExitPostmaster(2);
    1522             :     }
    1523         578 :     FreeFile(fp);
    1524         578 : }
    1525             : 
    1526             : /*
    1527             :  * Determine how long should we let ServerLoop sleep.
    1528             :  *
    1529             :  * In normal conditions we wait at most one minute, to ensure that the other
    1530             :  * background tasks handled by ServerLoop get done even when no requests are
    1531             :  * arriving.  However, if there are background workers waiting to be started,
    1532             :  * we don't actually sleep so that they are quickly serviced.  Other exception
    1533             :  * cases are as shown in the code.
    1534             :  */
    1535             : static void
    1536       16730 : DetermineSleepTime(struct timeval *timeout)
    1537             : {
    1538       16730 :     TimestampTz next_wakeup = 0;
    1539             : 
    1540             :     /*
    1541             :      * Normal case: either there are no background workers at all, or we're in
    1542             :      * a shutdown sequence (during which we ignore bgworkers altogether).
    1543             :      */
    1544       31036 :     if (Shutdown > NoShutdown ||
    1545       28612 :         (!StartWorkerNeeded && !HaveCrashedWorker))
    1546             :     {
    1547       16730 :         if (AbortStartTime != 0)
    1548             :         {
    1549             :             /* time left to abort; clamp to 0 in case it already expired */
    1550         434 :             timeout->tv_sec = SIGKILL_CHILDREN_AFTER_SECS -
    1551         434 :                 (time(NULL) - AbortStartTime);
    1552         434 :             timeout->tv_sec = Max(timeout->tv_sec, 0);
    1553         434 :             timeout->tv_usec = 0;
    1554             :         }
    1555             :         else
    1556             :         {
    1557       16296 :             timeout->tv_sec = 60;
    1558       16296 :             timeout->tv_usec = 0;
    1559             :         }
    1560       16730 :         return;
    1561             :     }
    1562             : 
    1563           0 :     if (StartWorkerNeeded)
    1564             :     {
    1565           0 :         timeout->tv_sec = 0;
    1566           0 :         timeout->tv_usec = 0;
    1567           0 :         return;
    1568             :     }
    1569             : 
    1570           0 :     if (HaveCrashedWorker)
    1571             :     {
    1572             :         slist_mutable_iter siter;
    1573             : 
    1574             :         /*
    1575             :          * When there are crashed bgworkers, we sleep just long enough that
    1576             :          * they are restarted when they request to be.  Scan the list to
    1577             :          * determine the minimum of all wakeup times according to most recent
    1578             :          * crash time and requested restart interval.
    1579             :          */
    1580           0 :         slist_foreach_modify(siter, &BackgroundWorkerList)
    1581             :         {
    1582             :             RegisteredBgWorker *rw;
    1583             :             TimestampTz this_wakeup;
    1584             : 
    1585           0 :             rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
    1586             : 
    1587           0 :             if (rw->rw_crashed_at == 0)
    1588           0 :                 continue;
    1589             : 
    1590           0 :             if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
    1591           0 :                 || rw->rw_terminate)
    1592             :             {
    1593           0 :                 ForgetBackgroundWorker(&siter);
    1594           0 :                 continue;
    1595             :             }
    1596             : 
    1597           0 :             this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
    1598             :                                                       1000L * rw->rw_worker.bgw_restart_time);
    1599           0 :             if (next_wakeup == 0 || this_wakeup < next_wakeup)
    1600           0 :                 next_wakeup = this_wakeup;
    1601             :         }
    1602             :     }
    1603             : 
    1604           0 :     if (next_wakeup != 0)
    1605             :     {
    1606             :         long        secs;
    1607             :         int         microsecs;
    1608             : 
    1609           0 :         TimestampDifference(GetCurrentTimestamp(), next_wakeup,
    1610             :                             &secs, &microsecs);
    1611           0 :         timeout->tv_sec = secs;
    1612           0 :         timeout->tv_usec = microsecs;
    1613             : 
    1614             :         /* Ensure we don't exceed one minute */
    1615           0 :         if (timeout->tv_sec > 60)
    1616             :         {
    1617           0 :             timeout->tv_sec = 60;
    1618           0 :             timeout->tv_usec = 0;
    1619             :         }
    1620             :     }
    1621             :     else
    1622             :     {
    1623           0 :         timeout->tv_sec = 60;
    1624           0 :         timeout->tv_usec = 0;
    1625             :     }
    1626             : }
    1627             : 
    1628             : /*
    1629             :  * Main idle loop of postmaster
    1630             :  *
    1631             :  * NB: Needs to be called with signals blocked
    1632             :  */
    1633             : static int
    1634         572 : ServerLoop(void)
    1635             : {
    1636             :     fd_set      readmask;
    1637             :     int         nSockets;
    1638             :     time_t      last_lockfile_recheck_time,
    1639             :                 last_touch_time;
    1640             : 
    1641         572 :     last_lockfile_recheck_time = last_touch_time = time(NULL);
    1642             : 
    1643         572 :     nSockets = initMasks(&readmask);
    1644             : 
    1645             :     for (;;)
    1646       16722 :     {
    1647             :         fd_set      rmask;
    1648             :         int         selres;
    1649             :         time_t      now;
    1650             : 
    1651             :         /*
    1652             :          * Wait for a connection request to arrive.
    1653             :          *
    1654             :          * We block all signals except while sleeping. That makes it safe for
    1655             :          * signal handlers, which again block all signals while executing, to
    1656             :          * do nontrivial work.
    1657             :          *
    1658             :          * If we are in PM_WAIT_DEAD_END state, then we don't want to accept
    1659             :          * any new connections, so we don't call select(), and just sleep.
    1660             :          */
    1661       17294 :         memcpy((char *) &rmask, (char *) &readmask, sizeof(fd_set));
    1662             : 
    1663       17294 :         if (pmState == PM_WAIT_DEAD_END)
    1664             :         {
    1665         564 :             PG_SETMASK(&UnBlockSig);
    1666             : 
    1667         564 :             pg_usleep(100000L); /* 100 msec seems reasonable */
    1668          22 :             selres = 0;
    1669             : 
    1670          22 :             PG_SETMASK(&BlockSig);
    1671             :         }
    1672             :         else
    1673             :         {
    1674             :             /* must set timeout each time; some OSes change it! */
    1675             :             struct timeval timeout;
    1676             : 
    1677             :             /* Needs to run with blocked signals! */
    1678       16730 :             DetermineSleepTime(&timeout);
    1679             : 
    1680       16730 :             PG_SETMASK(&UnBlockSig);
    1681             : 
    1682       16730 :             selres = select(nSockets, &rmask, NULL, NULL, &timeout);
    1683             : 
    1684       16702 :             PG_SETMASK(&BlockSig);
    1685             :         }
    1686             : 
    1687             :         /* Now check the select() result */
    1688       16724 :         if (selres < 0)
    1689             :         {
    1690        9796 :             if (errno != EINTR && errno != EWOULDBLOCK)
    1691             :             {
    1692           0 :                 ereport(LOG,
    1693             :                         (errcode_for_socket_access(),
    1694             :                          errmsg("select() failed in postmaster: %m")));
    1695           0 :                 return STATUS_ERROR;
    1696             :             }
    1697             :         }
    1698             : 
    1699             :         /*
    1700             :          * New connection pending on any of our sockets? If so, fork a child
    1701             :          * process to deal with it.
    1702             :          */
    1703       16724 :         if (selres > 0)
    1704             :         {
    1705             :             int         i;
    1706             : 
    1707       14200 :             for (i = 0; i < MAXLISTEN; i++)
    1708             :             {
    1709       14200 :                 if (ListenSocket[i] == PGINVALID_SOCKET)
    1710        6904 :                     break;
    1711        7296 :                 if (FD_ISSET(ListenSocket[i], &rmask))
    1712             :                 {
    1713             :                     Port       *port;
    1714             : 
    1715        6906 :                     port = ConnCreate(ListenSocket[i]);
    1716        6906 :                     if (port)
    1717             :                     {
    1718        6906 :                         BackendStartup(port);
    1719             : 
    1720             :                         /*
    1721             :                          * We no longer need the open socket or port structure
    1722             :                          * in this process
    1723             :                          */
    1724        6904 :                         StreamClose(port->sock);
    1725        6904 :                         ConnFree(port);
    1726             :                     }
    1727             :                 }
    1728             :             }
    1729             :         }
    1730             : 
    1731             :         /* If we have lost the log collector, try to start a new one */
    1732       16722 :         if (SysLoggerPID == 0 && Logging_collector)
    1733           0 :             SysLoggerPID = SysLogger_Start();
    1734             : 
    1735             :         /*
    1736             :          * If no background writer process is running, and we are not in a
    1737             :          * state that prevents it, start one.  It doesn't matter if this
    1738             :          * fails, we'll just try again later.  Likewise for the checkpointer.
    1739             :          */
    1740       20586 :         if (pmState == PM_RUN || pmState == PM_RECOVERY ||
    1741        3864 :             pmState == PM_HOT_STANDBY)
    1742             :         {
    1743       13676 :             if (CheckpointerPID == 0)
    1744           0 :                 CheckpointerPID = StartCheckpointer();
    1745       13676 :             if (BgWriterPID == 0)
    1746           0 :                 BgWriterPID = StartBackgroundWriter();
    1747             :         }
    1748             : 
    1749             :         /*
    1750             :          * Likewise, if we have lost the walwriter process, try to start a new
    1751             :          * one.  But this is needed only in normal operation (else we cannot
    1752             :          * be writing any new WAL).
    1753             :          */
    1754       16722 :         if (WalWriterPID == 0 && pmState == PM_RUN)
    1755           0 :             WalWriterPID = StartWalWriter();
    1756             : 
    1757             :         /*
    1758             :          * If we have lost the autovacuum launcher, try to start a new one. We
    1759             :          * don't want autovacuum to run in binary upgrade mode because
    1760             :          * autovacuum might update relfrozenxid for empty tables before the
    1761             :          * physical files are put in place.
    1762             :          */
    1763       19428 :         if (!IsBinaryUpgrade && AutoVacPID == 0 &&
    1764        5412 :             (AutoVacuumingActive() || start_autovac_launcher) &&
    1765        2478 :             pmState == PM_RUN)
    1766             :         {
    1767           0 :             AutoVacPID = StartAutoVacLauncher();
    1768           0 :             if (AutoVacPID != 0)
    1769           0 :                 start_autovac_launcher = false; /* signal processed */
    1770             :         }
    1771             : 
    1772             :         /* If we have lost the stats collector, try to start a new one */
    1773       16802 :         if (PgStatPID == 0 &&
    1774         160 :             (pmState == PM_RUN || pmState == PM_HOT_STANDBY))
    1775           0 :             PgStatPID = pgstat_start();
    1776             : 
    1777             :         /* If we have lost the archiver, try to start a new one. */
    1778       16722 :         if (PgArchPID == 0 && PgArchStartupAllowed())
    1779           0 :             PgArchPID = pgarch_start();
    1780             : 
    1781             :         /* If we need to signal the autovacuum launcher, do so now */
    1782       16722 :         if (avlauncher_needs_signal)
    1783             :         {
    1784           0 :             avlauncher_needs_signal = false;
    1785           0 :             if (AutoVacPID != 0)
    1786           0 :                 kill(AutoVacPID, SIGUSR2);
    1787             :         }
    1788             : 
    1789             :         /* If we need to start a WAL receiver, try to do that now */
    1790       16722 :         if (WalReceiverRequested)
    1791         188 :             MaybeStartWalReceiver();
    1792             : 
    1793             :         /* Get other worker processes running, if needed */
    1794       16722 :         if (StartWorkerNeeded || HaveCrashedWorker)
    1795        3118 :             maybe_start_bgworkers();
    1796             : 
    1797             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
    1798             : 
    1799             :         /*
    1800             :          * With assertions enabled, check regularly for appearance of
    1801             :          * additional threads.  All builds check at start and exit.
    1802             :          */
    1803             :         Assert(pthread_is_threaded_np() == 0);
    1804             : #endif
    1805             : 
    1806             :         /*
    1807             :          * Lastly, check to see if it's time to do some things that we don't
    1808             :          * want to do every single time through the loop, because they're a
    1809             :          * bit expensive.  Note that there's up to a minute of slop in when
    1810             :          * these tasks will be performed, since DetermineSleepTime() will let
    1811             :          * us sleep at most that long; except for SIGKILL timeout which has
    1812             :          * special-case logic there.
    1813             :          */
    1814       16722 :         now = time(NULL);
    1815             : 
    1816             :         /*
    1817             :          * If we already sent SIGQUIT to children and they are slow to shut
    1818             :          * down, it's time to send them SIGKILL.  This doesn't happen
    1819             :          * normally, but under certain conditions backends can get stuck while
    1820             :          * shutting down.  This is a last measure to get them unwedged.
    1821             :          *
    1822             :          * Note we also do this during recovery from a process crash.
    1823             :          */
    1824       17370 :         if ((Shutdown >= ImmediateShutdown || (FatalError && !SendStop)) &&
    1825        1288 :             AbortStartTime != 0 &&
    1826         640 :             (now - AbortStartTime) >= SIGKILL_CHILDREN_AFTER_SECS)
    1827             :         {
    1828             :             /* We were gentle with them before. Not anymore */
    1829           0 :             TerminateChildren(SIGKILL);
    1830             :             /* reset flag so we don't SIGKILL again */
    1831           0 :             AbortStartTime = 0;
    1832             :         }
    1833             : 
    1834             :         /*
    1835             :          * Once a minute, verify that postmaster.pid hasn't been removed or
    1836             :          * overwritten.  If it has, we force a shutdown.  This avoids having
    1837             :          * postmasters and child processes hanging around after their database
    1838             :          * is gone, and maybe causing problems if a new database cluster is
    1839             :          * created in the same place.  It also provides some protection
    1840             :          * against a DBA foolishly removing postmaster.pid and manually
    1841             :          * starting a new postmaster.  Data corruption is likely to ensue from
    1842             :          * that anyway, but we can minimize the damage by aborting ASAP.
    1843             :          */
    1844       16722 :         if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
    1845             :         {
    1846          10 :             if (!RecheckDataDirLockFile())
    1847             :             {
    1848           0 :                 ereport(LOG,
    1849             :                         (errmsg("performing immediate shutdown because data directory lock file is invalid")));
    1850           0 :                 kill(MyProcPid, SIGQUIT);
    1851             :             }
    1852          10 :             last_lockfile_recheck_time = now;
    1853             :         }
    1854             : 
    1855             :         /*
    1856             :          * Touch Unix socket and lock files every 58 minutes, to ensure that
    1857             :          * they are not removed by overzealous /tmp-cleaning tasks.  We assume
    1858             :          * no one runs cleaners with cutoff times of less than an hour ...
    1859             :          */
    1860       16722 :         if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
    1861             :         {
    1862           0 :             TouchSocketFiles();
    1863           0 :             TouchSocketLockFiles();
    1864           0 :             last_touch_time = now;
    1865             :         }
    1866             :     }
    1867             : }
    1868             : 
    1869             : /*
    1870             :  * Initialise the masks for select() for the ports we are listening on.
    1871             :  * Return the number of sockets to listen on.
    1872             :  */
    1873             : static int
    1874         572 : initMasks(fd_set *rmask)
    1875             : {
    1876         572 :     int         maxsock = -1;
    1877             :     int         i;
    1878             : 
    1879         572 :     FD_ZERO(rmask);
    1880             : 
    1881        1168 :     for (i = 0; i < MAXLISTEN; i++)
    1882             :     {
    1883        1168 :         int         fd = ListenSocket[i];
    1884             : 
    1885        1168 :         if (fd == PGINVALID_SOCKET)
    1886         572 :             break;
    1887         596 :         FD_SET(fd, rmask);
    1888             : 
    1889         596 :         if (fd > maxsock)
    1890         596 :             maxsock = fd;
    1891             :     }
    1892             : 
    1893         572 :     return maxsock + 1;
    1894             : }
    1895             : 
    1896             : 
    1897             : /*
    1898             :  * Read a client's startup packet and do something according to it.
    1899             :  *
    1900             :  * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
    1901             :  * not return at all.
    1902             :  *
    1903             :  * (Note that ereport(FATAL) stuff is sent to the client, so only use it
    1904             :  * if that's what you want.  Return STATUS_ERROR if you don't want to
    1905             :  * send anything to the client, which would typically be appropriate
    1906             :  * if we detect a communications failure.)
    1907             :  *
    1908             :  * Set secure_done when negotiation of an encrypted layer (currently, TLS or
    1909             :  * GSSAPI) is already completed.
    1910             :  */
    1911             : static int
    1912        7148 : ProcessStartupPacket(Port *port, bool secure_done)
    1913             : {
    1914             :     int32       len;
    1915             :     void       *buf;
    1916             :     ProtocolVersion proto;
    1917             :     MemoryContext oldcontext;
    1918             : 
    1919        7148 :     pq_startmsgread();
    1920             : 
    1921             :     /*
    1922             :      * Grab the first byte of the length word separately, so that we can tell
    1923             :      * whether we have no data at all or an incomplete packet.  (This might
    1924             :      * sound inefficient, but it's not really, because of buffering in
    1925             :      * pqcomm.c.)
    1926             :      */
    1927        7148 :     if (pq_getbytes((char *) &len, 1) == EOF)
    1928             :     {
    1929             :         /*
    1930             :          * If we get no data at all, don't clutter the log with a complaint;
    1931             :          * such cases often occur for legitimate reasons.  An example is that
    1932             :          * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
    1933             :          * client didn't like our response, it'll probably just drop the
    1934             :          * connection.  Service-monitoring software also often just opens and
    1935             :          * closes a connection without sending anything.  (So do port
    1936             :          * scanners, which may be less benign, but it's not really our job to
    1937             :          * notice those.)
    1938             :          */
    1939          10 :         return STATUS_ERROR;
    1940             :     }
    1941             : 
    1942        7138 :     if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
    1943             :     {
    1944             :         /* Got a partial length word, so bleat about that */
    1945           0 :         if (!secure_done)
    1946           0 :             ereport(COMMERROR,
    1947             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1948             :                      errmsg("incomplete startup packet")));
    1949           0 :         return STATUS_ERROR;
    1950             :     }
    1951             : 
    1952        7138 :     len = pg_ntoh32(len);
    1953        7138 :     len -= 4;
    1954             : 
    1955       14276 :     if (len < (int32) sizeof(ProtocolVersion) ||
    1956        7138 :         len > MAX_STARTUP_PACKET_LENGTH)
    1957             :     {
    1958           0 :         ereport(COMMERROR,
    1959             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1960             :                  errmsg("invalid length of startup packet")));
    1961           0 :         return STATUS_ERROR;
    1962             :     }
    1963             : 
    1964             :     /*
    1965             :      * Allocate at least the size of an old-style startup packet, plus one
    1966             :      * extra byte, and make sure all are zeroes.  This ensures we will have
    1967             :      * null termination of all strings, in both fixed- and variable-length
    1968             :      * packet layouts.
    1969             :      */
    1970        7138 :     if (len <= (int32) sizeof(StartupPacket))
    1971        7138 :         buf = palloc0(sizeof(StartupPacket) + 1);
    1972             :     else
    1973           0 :         buf = palloc0(len + 1);
    1974             : 
    1975        7138 :     if (pq_getbytes(buf, len) == EOF)
    1976             :     {
    1977           0 :         ereport(COMMERROR,
    1978             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    1979             :                  errmsg("incomplete startup packet")));
    1980           0 :         return STATUS_ERROR;
    1981             :     }
    1982        7138 :     pq_endmsgread();
    1983             : 
    1984             :     /*
    1985             :      * The first field is either a protocol version number or a special
    1986             :      * request code.
    1987             :      */
    1988        7138 :     port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
    1989             : 
    1990        7138 :     if (proto == CANCEL_REQUEST_CODE)
    1991             :     {
    1992           2 :         processCancelRequest(port, buf);
    1993             :         /* Not really an error, but we don't want to proceed further */
    1994           2 :         return STATUS_ERROR;
    1995             :     }
    1996             : 
    1997        7136 :     if (proto == NEGOTIATE_SSL_CODE && !secure_done)
    1998             :     {
    1999             :         char        SSLok;
    2000             : 
    2001             : #ifdef USE_SSL
    2002             :         /* No SSL when disabled or on Unix sockets */
    2003         376 :         if (!LoadedSSL || IS_AF_UNIX(port->laddr.addr.ss_family))
    2004         294 :             SSLok = 'N';
    2005             :         else
    2006          82 :             SSLok = 'S';        /* Support for SSL */
    2007             : #else
    2008             :         SSLok = 'N';            /* No support for SSL */
    2009             : #endif
    2010             : 
    2011             : retry1:
    2012         376 :         if (send(port->sock, &SSLok, 1, 0) != 1)
    2013             :         {
    2014           0 :             if (errno == EINTR)
    2015           0 :                 goto retry1;    /* if interrupted, just retry */
    2016           0 :             ereport(COMMERROR,
    2017             :                     (errcode_for_socket_access(),
    2018             :                      errmsg("failed to send SSL negotiation response: %m")));
    2019           0 :             return STATUS_ERROR;    /* close the connection */
    2020             :         }
    2021             : 
    2022             : #ifdef USE_SSL
    2023         376 :         if (SSLok == 'S' && secure_open_server(port) == -1)
    2024          22 :             return STATUS_ERROR;
    2025             : #endif
    2026             :         /* regular startup packet, cancel, etc packet should follow... */
    2027             :         /* but not another SSL negotiation request */
    2028         354 :         return ProcessStartupPacket(port, true);
    2029             :     }
    2030        6760 :     else if (proto == NEGOTIATE_GSS_CODE && !secure_done)
    2031             :     {
    2032           0 :         char        GSSok = 'N';
    2033             : #ifdef ENABLE_GSS
    2034             :         /* No GSSAPI encryption when on Unix socket */
    2035             :         if (!IS_AF_UNIX(port->laddr.addr.ss_family))
    2036             :             GSSok = 'G';
    2037             : #endif
    2038             : 
    2039           0 :         while (send(port->sock, &GSSok, 1, 0) != 1)
    2040             :         {
    2041           0 :             if (errno == EINTR)
    2042           0 :                 continue;
    2043           0 :             ereport(COMMERROR,
    2044             :                     (errcode_for_socket_access(),
    2045             :                      errmsg("failed to send GSSAPI negotiation response: %m")));
    2046           0 :             return STATUS_ERROR;    /* close the connection */
    2047             :         }
    2048             : 
    2049             : #ifdef ENABLE_GSS
    2050             :         if (GSSok == 'G' && secure_open_gssapi(port) == -1)
    2051             :             return STATUS_ERROR;
    2052             : #endif
    2053             :         /* Won't ever see more than one negotiation request */
    2054           0 :         return ProcessStartupPacket(port, true);
    2055             :     }
    2056             : 
    2057             :     /* Could add additional special packet types here */
    2058             : 
    2059             :     /*
    2060             :      * Set FrontendProtocol now so that ereport() knows what format to send if
    2061             :      * we fail during startup.
    2062             :      */
    2063        6760 :     FrontendProtocol = proto;
    2064             : 
    2065             :     /* Check that the major protocol version is in range. */
    2066       13520 :     if (PG_PROTOCOL_MAJOR(proto) < PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST) ||
    2067        6760 :         PG_PROTOCOL_MAJOR(proto) > PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST))
    2068           0 :         ereport(FATAL,
    2069             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2070             :                  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
    2071             :                         PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
    2072             :                         PG_PROTOCOL_MAJOR(PG_PROTOCOL_EARLIEST),
    2073             :                         PG_PROTOCOL_MAJOR(PG_PROTOCOL_LATEST),
    2074             :                         PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST))));
    2075             : 
    2076             :     /*
    2077             :      * Now fetch parameters out of startup packet and save them into the Port
    2078             :      * structure.  All data structures attached to the Port struct must be
    2079             :      * allocated in TopMemoryContext so that they will remain available in a
    2080             :      * running backend (even after PostmasterContext is destroyed).  We need
    2081             :      * not worry about leaking this storage on failure, since we aren't in the
    2082             :      * postmaster process anymore.
    2083             :      */
    2084        6760 :     oldcontext = MemoryContextSwitchTo(TopMemoryContext);
    2085             : 
    2086        6760 :     if (PG_PROTOCOL_MAJOR(proto) >= 3)
    2087             :     {
    2088        6760 :         int32       offset = sizeof(ProtocolVersion);
    2089        6760 :         List       *unrecognized_protocol_options = NIL;
    2090             : 
    2091             :         /*
    2092             :          * Scan packet body for name/option pairs.  We can assume any string
    2093             :          * beginning within the packet body is null-terminated, thanks to
    2094             :          * zeroing extra byte above.
    2095             :          */
    2096        6760 :         port->guc_options = NIL;
    2097             : 
    2098       44678 :         while (offset < len)
    2099             :         {
    2100       37918 :             char       *nameptr = ((char *) buf) + offset;
    2101             :             int32       valoffset;
    2102             :             char       *valptr;
    2103             : 
    2104       37918 :             if (*nameptr == '\0')
    2105        6760 :                 break;          /* found packet terminator */
    2106       31158 :             valoffset = offset + strlen(nameptr) + 1;
    2107       31158 :             if (valoffset >= len)
    2108           0 :                 break;          /* missing value, will complain below */
    2109       31158 :             valptr = ((char *) buf) + valoffset;
    2110             : 
    2111       31158 :             if (strcmp(nameptr, "database") == 0)
    2112        6760 :                 port->database_name = pstrdup(valptr);
    2113       24398 :             else if (strcmp(nameptr, "user") == 0)
    2114        6760 :                 port->user_name = pstrdup(valptr);
    2115       17638 :             else if (strcmp(nameptr, "options") == 0)
    2116        3318 :                 port->cmdline_options = pstrdup(valptr);
    2117       14320 :             else if (strcmp(nameptr, "replication") == 0)
    2118             :             {
    2119             :                 /*
    2120             :                  * Due to backward compatibility concerns the replication
    2121             :                  * parameter is a hybrid beast which allows the value to be
    2122             :                  * either boolean or the string 'database'. The latter
    2123             :                  * connects to a specific database which is e.g. required for
    2124             :                  * logical decoding while.
    2125             :                  */
    2126         468 :                 if (strcmp(valptr, "database") == 0)
    2127             :                 {
    2128         176 :                     am_walsender = true;
    2129         176 :                     am_db_walsender = true;
    2130             :                 }
    2131         292 :                 else if (!parse_bool(valptr, &am_walsender))
    2132           0 :                     ereport(FATAL,
    2133             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2134             :                              errmsg("invalid value for parameter \"%s\": \"%s\"",
    2135             :                                     "replication",
    2136             :                                     valptr),
    2137             :                              errhint("Valid values are: \"false\", 0, \"true\", 1, \"database\".")));
    2138             :             }
    2139       13852 :             else if (strncmp(nameptr, "_pq_.", 5) == 0)
    2140             :             {
    2141             :                 /*
    2142             :                  * Any option beginning with _pq_. is reserved for use as a
    2143             :                  * protocol-level option, but at present no such options are
    2144             :                  * defined.
    2145             :                  */
    2146           0 :                 unrecognized_protocol_options =
    2147           0 :                     lappend(unrecognized_protocol_options, pstrdup(nameptr));
    2148             :             }
    2149             :             else
    2150             :             {
    2151             :                 /* Assume it's a generic GUC option */
    2152       13852 :                 port->guc_options = lappend(port->guc_options,
    2153       13852 :                                             pstrdup(nameptr));
    2154       13852 :                 port->guc_options = lappend(port->guc_options,
    2155       13852 :                                             pstrdup(valptr));
    2156             : 
    2157             :                 /*
    2158             :                  * Copy application_name to port if we come across it.  This
    2159             :                  * is done so we can log the application_name in the
    2160             :                  * connection authorization message.  Note that the GUC would
    2161             :                  * be used but we haven't gone through GUC setup yet.
    2162             :                  */
    2163       13852 :                 if (strcmp(nameptr, "application_name") == 0)
    2164             :                 {
    2165        6672 :                     char       *tmp_app_name = pstrdup(valptr);
    2166             : 
    2167        6672 :                     pg_clean_ascii(tmp_app_name);
    2168             : 
    2169        6672 :                     port->application_name = tmp_app_name;
    2170             :                 }
    2171             :             }
    2172       31158 :             offset = valoffset + strlen(valptr) + 1;
    2173             :         }
    2174             : 
    2175             :         /*
    2176             :          * If we didn't find a packet terminator exactly at the end of the
    2177             :          * given packet length, complain.
    2178             :          */
    2179        6760 :         if (offset != len - 1)
    2180           0 :             ereport(FATAL,
    2181             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
    2182             :                      errmsg("invalid startup packet layout: expected terminator as last byte")));
    2183             : 
    2184             :         /*
    2185             :          * If the client requested a newer protocol version or if the client
    2186             :          * requested any protocol options we didn't recognize, let them know
    2187             :          * the newest minor protocol version we do support and the names of
    2188             :          * any unrecognized options.
    2189             :          */
    2190        6760 :         if (PG_PROTOCOL_MINOR(proto) > PG_PROTOCOL_MINOR(PG_PROTOCOL_LATEST) ||
    2191             :             unrecognized_protocol_options != NIL)
    2192           0 :             SendNegotiateProtocolVersion(unrecognized_protocol_options);
    2193             :     }
    2194             :     else
    2195             :     {
    2196             :         /*
    2197             :          * Get the parameters from the old-style, fixed-width-fields startup
    2198             :          * packet as C strings.  The packet destination was cleared first so a
    2199             :          * short packet has zeros silently added.  We have to be prepared to
    2200             :          * truncate the pstrdup result for oversize fields, though.
    2201             :          */
    2202           0 :         StartupPacket *packet = (StartupPacket *) buf;
    2203             : 
    2204           0 :         port->database_name = pstrdup(packet->database);
    2205           0 :         if (strlen(port->database_name) > sizeof(packet->database))
    2206           0 :             port->database_name[sizeof(packet->database)] = '\0';
    2207           0 :         port->user_name = pstrdup(packet->user);
    2208           0 :         if (strlen(port->user_name) > sizeof(packet->user))
    2209           0 :             port->user_name[sizeof(packet->user)] = '\0';
    2210           0 :         port->cmdline_options = pstrdup(packet->options);
    2211           0 :         if (strlen(port->cmdline_options) > sizeof(packet->options))
    2212           0 :             port->cmdline_options[sizeof(packet->options)] = '\0';
    2213           0 :         port->guc_options = NIL;
    2214             :     }
    2215             : 
    2216             :     /* Check a user name was given. */
    2217        6760 :     if (port->user_name == NULL || port->user_name[0] == '\0')
    2218           0 :         ereport(FATAL,
    2219             :                 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
    2220             :                  errmsg("no PostgreSQL user name specified in startup packet")));
    2221             : 
    2222             :     /* The database defaults to the user name. */
    2223        6760 :     if (port->database_name == NULL || port->database_name[0] == '\0')
    2224           0 :         port->database_name = pstrdup(port->user_name);
    2225             : 
    2226        6760 :     if (Db_user_namespace)
    2227             :     {
    2228             :         /*
    2229             :          * If user@, it is a global user, remove '@'. We only want to do this
    2230             :          * if there is an '@' at the end and no earlier in the user string or
    2231             :          * they may fake as a local user of another database attaching to this
    2232             :          * database.
    2233             :          */
    2234           0 :         if (strchr(port->user_name, '@') ==
    2235           0 :             port->user_name + strlen(port->user_name) - 1)
    2236           0 :             *strchr(port->user_name, '@') = '\0';
    2237             :         else
    2238             :         {
    2239             :             /* Append '@' and dbname */
    2240           0 :             port->user_name = psprintf("%s@%s", port->user_name, port->database_name);
    2241             :         }
    2242             :     }
    2243             : 
    2244             :     /*
    2245             :      * Truncate given database and user names to length of a Postgres name.
    2246             :      * This avoids lookup failures when overlength names are given.
    2247             :      */
    2248        6760 :     if (strlen(port->database_name) >= NAMEDATALEN)
    2249           0 :         port->database_name[NAMEDATALEN - 1] = '\0';
    2250        6760 :     if (strlen(port->user_name) >= NAMEDATALEN)
    2251           0 :         port->user_name[NAMEDATALEN - 1] = '\0';
    2252             : 
    2253             :     /*
    2254             :      * Normal walsender backends, e.g. for streaming replication, are not
    2255             :      * connected to a particular database. But walsenders used for logical
    2256             :      * replication need to connect to a specific database. We allow streaming
    2257             :      * replication commands to be issued even if connected to a database as it
    2258             :      * can make sense to first make a basebackup and then stream changes
    2259             :      * starting from that.
    2260             :      */
    2261        6760 :     if (am_walsender && !am_db_walsender)
    2262         292 :         port->database_name[0] = '\0';
    2263             : 
    2264             :     /*
    2265             :      * Done putting stuff in TopMemoryContext.
    2266             :      */
    2267        6760 :     MemoryContextSwitchTo(oldcontext);
    2268             : 
    2269             :     /*
    2270             :      * If we're going to reject the connection due to database state, say so
    2271             :      * now instead of wasting cycles on an authentication exchange. (This also
    2272             :      * allows a pg_ping utility to be written.)
    2273             :      */
    2274        6760 :     switch (port->canAcceptConnections)
    2275             :     {
    2276             :         case CAC_STARTUP:
    2277          36 :             ereport(FATAL,
    2278             :                     (errcode(ERRCODE_CANNOT_CONNECT_NOW),
    2279             :                      errmsg("the database system is starting up")));
    2280             :             break;
    2281             :         case CAC_SHUTDOWN:
    2282           0 :             ereport(FATAL,
    2283             :                     (errcode(ERRCODE_CANNOT_CONNECT_NOW),
    2284             :                      errmsg("the database system is shutting down")));
    2285             :             break;
    2286             :         case CAC_RECOVERY:
    2287           4 :             ereport(FATAL,
    2288             :                     (errcode(ERRCODE_CANNOT_CONNECT_NOW),
    2289             :                      errmsg("the database system is in recovery mode")));
    2290             :             break;
    2291             :         case CAC_TOOMANY:
    2292           0 :             ereport(FATAL,
    2293             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
    2294             :                      errmsg("sorry, too many clients already")));
    2295             :             break;
    2296             :         case CAC_WAITBACKUP:
    2297             :             /* OK for now, will check in InitPostgres */
    2298           0 :             break;
    2299             :         case CAC_OK:
    2300        6720 :             break;
    2301             :     }
    2302             : 
    2303        6720 :     return STATUS_OK;
    2304             : }
    2305             : 
    2306             : /*
    2307             :  * Send a NegotiateProtocolVersion to the client.  This lets the client know
    2308             :  * that they have requested a newer minor protocol version than we are able
    2309             :  * to speak.  We'll speak the highest version we know about; the client can,
    2310             :  * of course, abandon the connection if that's a problem.
    2311             :  *
    2312             :  * We also include in the response a list of protocol options we didn't
    2313             :  * understand.  This allows clients to include optional parameters that might
    2314             :  * be present either in newer protocol versions or third-party protocol
    2315             :  * extensions without fear of having to reconnect if those options are not
    2316             :  * understood, while at the same time making certain that the client is aware
    2317             :  * of which options were actually accepted.
    2318             :  */
    2319             : static void
    2320           0 : SendNegotiateProtocolVersion(List *unrecognized_protocol_options)
    2321             : {
    2322             :     StringInfoData buf;
    2323             :     ListCell   *lc;
    2324             : 
    2325           0 :     pq_beginmessage(&buf, 'v'); /* NegotiateProtocolVersion */
    2326           0 :     pq_sendint32(&buf, PG_PROTOCOL_LATEST);
    2327           0 :     pq_sendint32(&buf, list_length(unrecognized_protocol_options));
    2328           0 :     foreach(lc, unrecognized_protocol_options)
    2329           0 :         pq_sendstring(&buf, lfirst(lc));
    2330           0 :     pq_endmessage(&buf);
    2331             : 
    2332             :     /* no need to flush, some other message will follow */
    2333           0 : }
    2334             : 
    2335             : /*
    2336             :  * The client has sent a cancel request packet, not a normal
    2337             :  * start-a-new-connection packet.  Perform the necessary processing.
    2338             :  * Nothing is sent back to the client.
    2339             :  */
    2340             : static void
    2341           2 : processCancelRequest(Port *port, void *pkt)
    2342             : {
    2343           2 :     CancelRequestPacket *canc = (CancelRequestPacket *) pkt;
    2344             :     int         backendPID;
    2345             :     int32       cancelAuthCode;
    2346             :     Backend    *bp;
    2347             : 
    2348             : #ifndef EXEC_BACKEND
    2349             :     dlist_iter  iter;
    2350             : #else
    2351             :     int         i;
    2352             : #endif
    2353             : 
    2354           2 :     backendPID = (int) pg_ntoh32(canc->backendPID);
    2355           2 :     cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
    2356             : 
    2357             :     /*
    2358             :      * See if we have a matching backend.  In the EXEC_BACKEND case, we can no
    2359             :      * longer access the postmaster's own backend list, and must rely on the
    2360             :      * duplicate array in shared memory.
    2361             :      */
    2362             : #ifndef EXEC_BACKEND
    2363           2 :     dlist_foreach(iter, &BackendList)
    2364             :     {
    2365           2 :         bp = dlist_container(Backend, elem, iter.cur);
    2366             : #else
    2367             :     for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--)
    2368             :     {
    2369             :         bp = (Backend *) &ShmemBackendArray[i];
    2370             : #endif
    2371           2 :         if (bp->pid == backendPID)
    2372             :         {
    2373           2 :             if (bp->cancel_key == cancelAuthCode)
    2374             :             {
    2375             :                 /* Found a match; signal that backend to cancel current op */
    2376           2 :                 ereport(DEBUG2,
    2377             :                         (errmsg_internal("processing cancel request: sending SIGINT to process %d",
    2378             :                                          backendPID)));
    2379           2 :                 signal_child(bp->pid, SIGINT);
    2380             :             }
    2381             :             else
    2382             :                 /* Right PID, wrong key: no way, Jose */
    2383           0 :                 ereport(LOG,
    2384             :                         (errmsg("wrong key in cancel request for process %d",
    2385             :                                 backendPID)));
    2386           2 :             return;
    2387             :         }
    2388             : #ifndef EXEC_BACKEND            /* make GNU Emacs 26.1 see brace balance */
    2389             :     }
    2390             : #else
    2391             :     }
    2392             : #endif
    2393             : 
    2394             :     /* No matching backend */
    2395           0 :     ereport(LOG,
    2396             :             (errmsg("PID %d in cancel request did not match any process",
    2397             :                     backendPID)));
    2398             : }
    2399             : 
    2400             : /*
    2401             :  * canAcceptConnections --- check to see if database state allows connections.
    2402             :  */
    2403             : static CAC_state
    2404        6968 : canAcceptConnections(void)
    2405             : {
    2406        6968 :     CAC_state   result = CAC_OK;
    2407             : 
    2408             :     /*
    2409             :      * Can't start backends when in startup/shutdown/inconsistent recovery
    2410             :      * state.
    2411             :      *
    2412             :      * In state PM_WAIT_BACKUP only superusers can connect (this must be
    2413             :      * allowed so that a superuser can end online backup mode); we return
    2414             :      * CAC_WAITBACKUP code to indicate that this must be checked later. Note
    2415             :      * that neither CAC_OK nor CAC_WAITBACKUP can safely be returned until we
    2416             :      * have checked for too many children.
    2417             :      */
    2418        6968 :     if (pmState != PM_RUN)
    2419             :     {
    2420         272 :         if (pmState == PM_WAIT_BACKUP)
    2421           0 :             result = CAC_WAITBACKUP;    /* allow superusers only */
    2422         272 :         else if (Shutdown > NoShutdown)
    2423           0 :             return CAC_SHUTDOWN;    /* shutdown is pending */
    2424         540 :         else if (!FatalError &&
    2425         500 :                  (pmState == PM_STARTUP ||
    2426         232 :                   pmState == PM_RECOVERY))
    2427          36 :             return CAC_STARTUP; /* normal startup */
    2428         468 :         else if (!FatalError &&
    2429         232 :                  pmState == PM_HOT_STANDBY)
    2430         232 :             result = CAC_OK;    /* connection OK during hot standby */
    2431             :         else
    2432           4 :             return CAC_RECOVERY;    /* else must be crash recovery */
    2433             :     }
    2434             : 
    2435             :     /*
    2436             :      * Don't start too many children.
    2437             :      *
    2438             :      * We allow more connections than we can have backends here because some
    2439             :      * might still be authenticating; they might fail auth, or some existing
    2440             :      * backend might exit before the auth cycle is completed. The exact
    2441             :      * MaxBackends limit is enforced when a new backend tries to join the
    2442             :      * shared-inval backend array.
    2443             :      *
    2444             :      * The limit here must match the sizes of the per-child-process arrays;
    2445             :      * see comments for MaxLivePostmasterChildren().
    2446             :      */
    2447        6928 :     if (CountChildren(BACKEND_TYPE_ALL) >= MaxLivePostmasterChildren())
    2448           0 :         result = CAC_TOOMANY;
    2449             : 
    2450        6928 :     return result;
    2451             : }
    2452             : 
    2453             : 
    2454             : /*
    2455             :  * ConnCreate -- create a local connection data structure
    2456             :  *
    2457             :  * Returns NULL on failure, other than out-of-memory which is fatal.
    2458             :  */
    2459             : static Port *
    2460        6906 : ConnCreate(int serverFd)
    2461             : {
    2462             :     Port       *port;
    2463             : 
    2464        6906 :     if (!(port = (Port *) calloc(1, sizeof(Port))))
    2465             :     {
    2466           0 :         ereport(LOG,
    2467             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    2468             :                  errmsg("out of memory")));
    2469           0 :         ExitPostmaster(1);
    2470             :     }
    2471             : 
    2472        6906 :     if (StreamConnection(serverFd, port) != STATUS_OK)
    2473             :     {
    2474           0 :         if (port->sock != PGINVALID_SOCKET)
    2475           0 :             StreamClose(port->sock);
    2476           0 :         ConnFree(port);
    2477           0 :         return NULL;
    2478             :     }
    2479             : 
    2480             :     /*
    2481             :      * Allocate GSSAPI specific state struct
    2482             :      */
    2483             : #ifndef EXEC_BACKEND
    2484             : #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
    2485             :     port->gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
    2486             :     if (!port->gss)
    2487             :     {
    2488             :         ereport(LOG,
    2489             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    2490             :                  errmsg("out of memory")));
    2491             :         ExitPostmaster(1);
    2492             :     }
    2493             : #endif
    2494             : #endif
    2495             : 
    2496        6906 :     return port;
    2497             : }
    2498             : 
    2499             : 
    2500             : /*
    2501             :  * ConnFree -- free a local connection data structure
    2502             :  */
    2503             : static void
    2504        6904 : ConnFree(Port *conn)
    2505             : {
    2506             : #ifdef USE_SSL
    2507        6904 :     secure_close(conn);
    2508             : #endif
    2509        6904 :     if (conn->gss)
    2510           0 :         free(conn->gss);
    2511        6904 :     free(conn);
    2512        6904 : }
    2513             : 
    2514             : 
    2515             : /*
    2516             :  * ClosePostmasterPorts -- close all the postmaster's open sockets
    2517             :  *
    2518             :  * This is called during child process startup to release file descriptors
    2519             :  * that are not needed by that child process.  The postmaster still has
    2520             :  * them open, of course.
    2521             :  *
    2522             :  * Note: we pass am_syslogger as a boolean because we don't want to set
    2523             :  * the global variable yet when this is called.
    2524             :  */
    2525             : void
    2526       11730 : ClosePostmasterPorts(bool am_syslogger)
    2527             : {
    2528             :     int         i;
    2529             : 
    2530             : #ifndef WIN32
    2531             : 
    2532             :     /*
    2533             :      * Close the write end of postmaster death watch pipe. It's important to
    2534             :      * do this as early as possible, so that if postmaster dies, others won't
    2535             :      * think that it's still running because we're holding the pipe open.
    2536             :      */
    2537       11730 :     if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]) != 0)
    2538           0 :         ereport(FATAL,
    2539             :                 (errcode_for_file_access(),
    2540             :                  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
    2541       11730 :     postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
    2542             : #endif
    2543             : 
    2544             :     /* Close the listen sockets */
    2545      762450 :     for (i = 0; i < MAXLISTEN; i++)
    2546             :     {
    2547      750720 :         if (ListenSocket[i] != PGINVALID_SOCKET)
    2548             :         {
    2549       12386 :             StreamClose(ListenSocket[i]);
    2550       12386 :             ListenSocket[i] = PGINVALID_SOCKET;
    2551             :         }
    2552             :     }
    2553             : 
    2554             :     /* If using syslogger, close the read side of the pipe */
    2555       11730 :     if (!am_syslogger)
    2556             :     {
    2557             : #ifndef WIN32
    2558       11728 :         if (syslogPipe[0] >= 0)
    2559          18 :             close(syslogPipe[0]);
    2560       11728 :         syslogPipe[0] = -1;
    2561             : #else
    2562             :         if (syslogPipe[0])
    2563             :             CloseHandle(syslogPipe[0]);
    2564             :         syslogPipe[0] = 0;
    2565             : #endif
    2566             :     }
    2567             : 
    2568             : #ifdef USE_BONJOUR
    2569             :     /* If using Bonjour, close the connection to the mDNS daemon */
    2570             :     if (bonjour_sdref)
    2571             :         close(DNSServiceRefSockFD(bonjour_sdref));
    2572             : #endif
    2573       11730 : }
    2574             : 
    2575             : 
    2576             : /*
    2577             :  * InitProcessGlobals -- set MyProcPid, MyStartTime[stamp], random seeds
    2578             :  *
    2579             :  * Called early in the postmaster and every backend.
    2580             :  */
    2581             : void
    2582       13592 : InitProcessGlobals(void)
    2583             : {
    2584             :     unsigned int rseed;
    2585             : 
    2586       13592 :     MyProcPid = getpid();
    2587       13592 :     MyStartTimestamp = GetCurrentTimestamp();
    2588       13592 :     MyStartTime = timestamptz_to_time_t(MyStartTimestamp);
    2589             : 
    2590             :     /*
    2591             :      * Set a different seed for random() in every process.  We want something
    2592             :      * unpredictable, so if possible, use high-quality random bits for the
    2593             :      * seed.  Otherwise, fall back to a seed based on timestamp and PID.
    2594             :      */
    2595       13592 :     if (!pg_strong_random(&rseed, sizeof(rseed)))
    2596             :     {
    2597             :         /*
    2598             :          * Since PIDs and timestamps tend to change more frequently in their
    2599             :          * least significant bits, shift the timestamp left to allow a larger
    2600             :          * total number of seeds in a given time period.  Since that would
    2601             :          * leave only 20 bits of the timestamp that cycle every ~1 second,
    2602             :          * also mix in some higher bits.
    2603             :          */
    2604           0 :         rseed = ((uint64) MyProcPid) ^
    2605           0 :             ((uint64) MyStartTimestamp << 12) ^
    2606           0 :             ((uint64) MyStartTimestamp >> 20);
    2607             :     }
    2608       13592 :     srandom(rseed);
    2609       13592 : }
    2610             : 
    2611             : 
    2612             : /*
    2613             :  * reset_shared -- reset shared memory and semaphores
    2614             :  */
    2615             : static void
    2616         578 : reset_shared(void)
    2617             : {
    2618             :     /*
    2619             :      * Create or re-create shared memory and semaphores.
    2620             :      *
    2621             :      * Note: in each "cycle of life" we will normally assign the same IPC keys
    2622             :      * (if using SysV shmem and/or semas).  This helps ensure that we will
    2623             :      * clean up dead IPC objects if the postmaster crashes and is restarted.
    2624             :      */
    2625         578 :     CreateSharedMemoryAndSemaphores();
    2626         576 : }
    2627             : 
    2628             : 
    2629             : /*
    2630             :  * SIGHUP -- reread config files, and tell children to do same
    2631             :  */
    2632             : static void
    2633          48 : SIGHUP_handler(SIGNAL_ARGS)
    2634             : {
    2635          48 :     int         save_errno = errno;
    2636             : 
    2637          48 :     PG_SETMASK(&BlockSig);
    2638             : 
    2639          48 :     if (Shutdown <= SmartShutdown)
    2640             :     {
    2641          48 :         ereport(LOG,
    2642             :                 (errmsg("received SIGHUP, reloading configuration files")));
    2643          48 :         ProcessConfigFile(PGC_SIGHUP);
    2644          48 :         SignalChildren(SIGHUP);
    2645          48 :         if (StartupPID != 0)
    2646          10 :             signal_child(StartupPID, SIGHUP);
    2647          48 :         if (BgWriterPID != 0)
    2648          48 :             signal_child(BgWriterPID, SIGHUP);
    2649          48 :         if (CheckpointerPID != 0)
    2650          48 :             signal_child(CheckpointerPID, SIGHUP);
    2651          48 :         if (WalWriterPID != 0)
    2652          38 :             signal_child(WalWriterPID, SIGHUP);
    2653          48 :         if (WalReceiverPID != 0)
    2654          10 :             signal_child(WalReceiverPID, SIGHUP);
    2655          48 :         if (AutoVacPID != 0)
    2656          38 :             signal_child(AutoVacPID, SIGHUP);
    2657          48 :         if (PgArchPID != 0)
    2658           0 :             signal_child(PgArchPID, SIGHUP);
    2659          48 :         if (SysLoggerPID != 0)
    2660           0 :             signal_child(SysLoggerPID, SIGHUP);
    2661          48 :         if (PgStatPID != 0)
    2662          48 :             signal_child(PgStatPID, SIGHUP);
    2663             : 
    2664             :         /* Reload authentication config files too */
    2665          48 :         if (!load_hba())
    2666           0 :             ereport(LOG,
    2667             :             /* translator: %s is a configuration file */
    2668             :                     (errmsg("%s was not reloaded", "pg_hba.conf")));
    2669             : 
    2670          48 :         if (!load_ident())
    2671           0 :             ereport(LOG,
    2672             :                     (errmsg("%s was not reloaded", "pg_ident.conf")));
    2673             : 
    2674             : #ifdef USE_SSL
    2675             :         /* Reload SSL configuration as well */
    2676          48 :         if (EnableSSL)
    2677             :         {
    2678           0 :             if (secure_initialize(false) == 0)
    2679           0 :                 LoadedSSL = true;
    2680             :             else
    2681           0 :                 ereport(LOG,
    2682             :                         (errmsg("SSL configuration was not reloaded")));
    2683             :         }
    2684             :         else
    2685             :         {
    2686          48 :             secure_destroy();
    2687          48 :             LoadedSSL = false;
    2688             :         }
    2689             : #endif
    2690             : 
    2691             : #ifdef EXEC_BACKEND
    2692             :         /* Update the starting-point file for future children */
    2693             :         write_nondefault_variables(PGC_SIGHUP);
    2694             : #endif
    2695             :     }
    2696             : 
    2697          48 :     PG_SETMASK(&UnBlockSig);
    2698             : 
    2699          48 :     errno = save_errno;
    2700          48 : }
    2701             : 
    2702             : 
    2703             : /*
    2704             :  * pmdie -- signal handler for processing various postmaster signals.
    2705             :  */
    2706             : static void
    2707         566 : pmdie(SIGNAL_ARGS)
    2708             : {
    2709         566 :     int         save_errno = errno;
    2710             : 
    2711         566 :     PG_SETMASK(&BlockSig);
    2712             : 
    2713         566 :     ereport(DEBUG2,
    2714             :             (errmsg_internal("postmaster received signal %d",
    2715             :                              postgres_signal_arg)));
    2716             : 
    2717         566 :     switch (postgres_signal_arg)
    2718             :     {
    2719             :         case SIGTERM:
    2720             : 
    2721             :             /*
    2722             :              * Smart Shutdown:
    2723             :              *
    2724             :              * Wait for children to end their work, then shut down.
    2725             :              */
    2726           8 :             if (Shutdown >= SmartShutdown)
    2727           0 :                 break;
    2728           8 :             Shutdown = SmartShutdown;
    2729           8 :             ereport(LOG,
    2730             :                     (errmsg("received smart shutdown request")));
    2731             : 
    2732             :             /* Report status */
    2733           8 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
    2734             : #ifdef USE_SYSTEMD
    2735             :             sd_notify(0, "STOPPING=1");
    2736             : #endif
    2737             : 
    2738           8 :             if (pmState == PM_RUN || pmState == PM_RECOVERY ||
    2739           0 :                 pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
    2740             :             {
    2741             :                 /* autovac workers are told to shut down immediately */
    2742             :                 /* and bgworkers too; does this need tweaking? */
    2743           8 :                 SignalSomeChildren(SIGTERM,
    2744             :                                    BACKEND_TYPE_AUTOVAC | BACKEND_TYPE_BGWORKER);
    2745             :                 /* and the autovac launcher too */
    2746           8 :                 if (AutoVacPID != 0)
    2747           0 :                     signal_child(AutoVacPID, SIGTERM);
    2748             :                 /* and the bgwriter too */
    2749           8 :                 if (BgWriterPID != 0)
    2750           8 :                     signal_child(BgWriterPID, SIGTERM);
    2751             :                 /* and the walwriter too */
    2752           8 :                 if (WalWriterPID != 0)
    2753           8 :                     signal_child(WalWriterPID, SIGTERM);
    2754             : 
    2755             :                 /*
    2756             :                  * If we're in recovery, we can't kill the startup process
    2757             :                  * right away, because at present doing so does not release
    2758             :                  * its locks.  We might want to change this in a future
    2759             :                  * release.  For the time being, the PM_WAIT_READONLY state
    2760             :                  * indicates that we're waiting for the regular (read only)
    2761             :                  * backends to die off; once they do, we'll kill the startup
    2762             :                  * and walreceiver processes.
    2763             :                  */
    2764          16 :                 pmState = (pmState == PM_RUN) ?
    2765           8 :                     PM_WAIT_BACKUP : PM_WAIT_READONLY;
    2766             :             }
    2767             : 
    2768             :             /*
    2769             :              * Now wait for online backup mode to end and backends to exit. If
    2770             :              * that is already the case, PostmasterStateMachine will take the
    2771             :              * next step.
    2772             :              */
    2773           8 :             PostmasterStateMachine();
    2774           8 :             break;
    2775             : 
    2776             :         case SIGINT:
    2777             : 
    2778             :             /*
    2779             :              * Fast Shutdown:
    2780             :              *
    2781             :              * Abort all children with SIGTERM (rollback active transactions
    2782             :              * and exit) and shut down when they are gone.
    2783             :              */
    2784         366 :             if (Shutdown >= FastShutdown)
    2785           0 :                 break;
    2786         366 :             Shutdown = FastShutdown;
    2787         366 :             ereport(LOG,
    2788             :                     (errmsg("received fast shutdown request")));
    2789             : 
    2790             :             /* Report status */
    2791         366 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
    2792             : #ifdef USE_SYSTEMD
    2793             :             sd_notify(0, "STOPPING=1");
    2794             : #endif
    2795             : 
    2796         366 :             if (StartupPID != 0)
    2797          22 :                 signal_child(StartupPID, SIGTERM);
    2798         366 :             if (BgWriterPID != 0)
    2799         366 :                 signal_child(BgWriterPID, SIGTERM);
    2800         366 :             if (WalReceiverPID != 0)
    2801          18 :                 signal_child(WalReceiverPID, SIGTERM);
    2802         366 :             if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
    2803             :             {
    2804           0 :                 SignalSomeChildren(SIGTERM, BACKEND_TYPE_BGWORKER);
    2805             : 
    2806             :                 /*
    2807             :                  * Only startup, bgwriter, walreceiver, possibly bgworkers,
    2808             :                  * and/or checkpointer should be active in this state; we just
    2809             :                  * signaled the first four, and we don't want to kill
    2810             :                  * checkpointer yet.
    2811             :                  */
    2812           0 :                 pmState = PM_WAIT_BACKENDS;
    2813             :             }
    2814         388 :             else if (pmState == PM_RUN ||
    2815          44 :                      pmState == PM_WAIT_BACKUP ||
    2816          44 :                      pmState == PM_WAIT_READONLY ||
    2817          44 :                      pmState == PM_WAIT_BACKENDS ||
    2818          22 :                      pmState == PM_HOT_STANDBY)
    2819             :             {
    2820         366 :                 ereport(LOG,
    2821             :                         (errmsg("aborting any active transactions")));
    2822             :                 /* shut down all backends and workers */
    2823         366 :                 SignalSomeChildren(SIGTERM,
    2824             :                                    BACKEND_TYPE_NORMAL | BACKEND_TYPE_AUTOVAC |
    2825             :                                    BACKEND_TYPE_BGWORKER);
    2826             :                 /* and the autovac launcher too */
    2827         366 :                 if (AutoVacPID != 0)
    2828         340 :                     signal_child(AutoVacPID, SIGTERM);
    2829             :                 /* and the walwriter too */
    2830         366 :                 if (WalWriterPID != 0)
    2831         344 :                     signal_child(WalWriterPID, SIGTERM);
    2832         366 :                 pmState = PM_WAIT_BACKENDS;
    2833             :             }
    2834             : 
    2835             :             /*
    2836             :              * Now wait for backends to exit.  If there are none,
    2837             :              * PostmasterStateMachine will take the next step.
    2838             :              */
    2839         366 :             PostmasterStateMachine();
    2840         366 :             break;
    2841             : 
    2842             :         case SIGQUIT:
    2843             : 
    2844             :             /*
    2845             :              * Immediate Shutdown:
    2846             :              *
    2847             :              * abort all children with SIGQUIT, wait for them to exit,
    2848             :              * terminate remaining ones with SIGKILL, then exit without
    2849             :              * attempt to properly shut down the data base system.
    2850             :              */
    2851         192 :             if (Shutdown >= ImmediateShutdown)
    2852           0 :                 break;
    2853         192 :             Shutdown = ImmediateShutdown;
    2854         192 :             ereport(LOG,
    2855             :                     (errmsg("received immediate shutdown request")));
    2856             : 
    2857             :             /* Report status */
    2858         192 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
    2859             : #ifdef USE_SYSTEMD
    2860             :             sd_notify(0, "STOPPING=1");
    2861             : #endif
    2862             : 
    2863         192 :             TerminateChildren(SIGQUIT);
    2864         192 :             pmState = PM_WAIT_BACKENDS;
    2865             : 
    2866             :             /* set stopwatch for them to die */
    2867         192 :             AbortStartTime = time(NULL);
    2868             : 
    2869             :             /*
    2870             :              * Now wait for backends to exit.  If there are none,
    2871             :              * PostmasterStateMachine will take the next step.
    2872             :              */
    2873         192 :             PostmasterStateMachine();
    2874         192 :             break;
    2875             :     }
    2876             : 
    2877         566 :     PG_SETMASK(&UnBlockSig);
    2878             : 
    2879         566 :     errno = save_errno;
    2880         566 : }
    2881             : 
    2882             : /*
    2883             :  * Reaper -- signal handler to cleanup after a child process dies.
    2884             :  */
    2885             : static void
    2886       11450 : reaper(SIGNAL_ARGS)
    2887             : {
    2888       11450 :     int         save_errno = errno;
    2889             :     int         pid;            /* process id of dead child process */
    2890             :     int         exitstatus;     /* its exit status */
    2891             : 
    2892       11450 :     PG_SETMASK(&BlockSig);
    2893             : 
    2894       11450 :     ereport(DEBUG4,
    2895             :             (errmsg_internal("reaping dead processes")));
    2896             : 
    2897       35572 :     while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
    2898             :     {
    2899             :         /*
    2900             :          * Check if this child was a startup process.
    2901             :          */
    2902       12676 :         if (pid == StartupPID)
    2903             :         {
    2904         576 :             StartupPID = 0;
    2905             : 
    2906             :             /*
    2907             :              * Startup process exited in response to a shutdown request (or it
    2908             :              * completed normally regardless of the shutdown request).
    2909             :              */
    2910         654 :             if (Shutdown > NoShutdown &&
    2911         156 :                 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
    2912             :             {
    2913          22 :                 StartupStatus = STARTUP_NOT_RUNNING;
    2914          22 :                 pmState = PM_WAIT_BACKENDS;
    2915             :                 /* PostmasterStateMachine logic does the rest */
    2916          22 :                 continue;
    2917             :             }
    2918             : 
    2919         554 :             if (EXIT_STATUS_3(exitstatus))
    2920             :             {
    2921           0 :                 ereport(LOG,
    2922             :                         (errmsg("shutdown at recovery target")));
    2923           0 :                 StartupStatus = STARTUP_NOT_RUNNING;
    2924           0 :                 Shutdown = SmartShutdown;
    2925           0 :                 TerminateChildren(SIGTERM);
    2926           0 :                 pmState = PM_WAIT_BACKENDS;
    2927             :                 /* PostmasterStateMachine logic does the rest */
    2928           0 :                 continue;
    2929             :             }
    2930             : 
    2931             :             /*
    2932             :              * Unexpected exit of startup process (including FATAL exit)
    2933             :              * during PM_STARTUP is treated as catastrophic. There are no
    2934             :              * other processes running yet, so we can just exit.
    2935             :              */
    2936        1010 :             if (pmState == PM_STARTUP &&
    2937         912 :                 StartupStatus != STARTUP_SIGNALED &&
    2938         456 :                 !EXIT_STATUS_0(exitstatus))
    2939             :             {
    2940           0 :                 LogChildExit(LOG, _("startup process"),
    2941             :                              pid, exitstatus);
    2942           0 :                 ereport(LOG,
    2943             :                         (errmsg("aborting startup due to startup process failure")));
    2944           0 :                 ExitPostmaster(1);
    2945             :             }
    2946             : 
    2947             :             /*
    2948             :              * After PM_STARTUP, any unexpected exit (including FATAL exit) of
    2949             :              * the startup process is catastrophic, so kill other children,
    2950             :              * and set StartupStatus so we don't try to reinitialize after
    2951             :              * they're gone.  Exception: if StartupStatus is STARTUP_SIGNALED,
    2952             :              * then we previously sent the startup process a SIGQUIT; so
    2953             :              * that's probably the reason it died, and we do want to try to
    2954             :              * restart in that case.
    2955             :              *
    2956             :              * This stanza also handles the case where we sent a SIGQUIT
    2957             :              * during PM_STARTUP due to some dead_end child crashing: in that
    2958             :              * situation, if the startup process dies on the SIGQUIT, we need
    2959             :              * to transition to PM_WAIT_BACKENDS state which will allow
    2960             :              * PostmasterStateMachine to restart the startup process.  (On the
    2961             :              * other hand, the startup process might complete normally, if we
    2962             :              * were too late with the SIGQUIT.  In that case we'll fall
    2963             :              * through and commence normal operations.)
    2964             :              */
    2965         554 :             if (!EXIT_STATUS_0(exitstatus))
    2966             :             {
    2967          56 :                 if (StartupStatus == STARTUP_SIGNALED)
    2968             :                 {
    2969          56 :                     StartupStatus = STARTUP_NOT_RUNNING;
    2970          56 :                     if (pmState == PM_STARTUP)
    2971           0 :                         pmState = PM_WAIT_BACKENDS;
    2972             :                 }
    2973             :                 else
    2974           0 :                     StartupStatus = STARTUP_CRASHED;
    2975          56 :                 HandleChildCrash(pid, exitstatus,
    2976          56 :                                  _("startup process"));
    2977          56 :                 continue;
    2978             :             }
    2979             : 
    2980             :             /*
    2981             :              * Startup succeeded, commence normal operations
    2982             :              */
    2983         498 :             StartupStatus = STARTUP_NOT_RUNNING;
    2984         498 :             FatalError = false;
    2985         498 :             AbortStartTime = 0;
    2986         498 :             ReachedNormalRunning = true;
    2987         498 :             pmState = PM_RUN;
    2988             : 
    2989             :             /*
    2990             :              * Crank up the background tasks, if we didn't do that already
    2991             :              * when we entered consistent recovery state.  It doesn't matter
    2992             :              * if this fails, we'll just try again later.
    2993             :              */
    2994         498 :             if (CheckpointerPID == 0)
    2995         456 :                 CheckpointerPID = StartCheckpointer();
    2996         498 :             if (BgWriterPID == 0)
    2997         456 :                 BgWriterPID = StartBackgroundWriter();
    2998         498 :             if (WalWriterPID == 0)
    2999         498 :                 WalWriterPID = StartWalWriter();
    3000             : 
    3001             :             /*
    3002             :              * Likewise, start other special children as needed.  In a restart
    3003             :              * situation, some of them may be alive already.
    3004             :              */
    3005         498 :             if (!IsBinaryUpgrade && AutoVacuumingActive() && AutoVacPID == 0)
    3006         480 :                 AutoVacPID = StartAutoVacLauncher();
    3007         498 :             if (PgArchStartupAllowed() && PgArchPID == 0)
    3008          10 :                 PgArchPID = pgarch_start();
    3009         498 :             if (PgStatPID == 0)
    3010         456 :                 PgStatPID = pgstat_start();
    3011             : 
    3012             :             /* workers may be scheduled to start now */
    3013         498 :             maybe_start_bgworkers();
    3014             : 
    3015             :             /* at this point we are really open for business */
    3016         494 :             ereport(LOG,
    3017             :                     (errmsg("database system is ready to accept connections")));
    3018             : 
    3019             :             /* Report status */
    3020         494 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
    3021             : #ifdef USE_SYSTEMD
    3022             :             sd_notify(0, "READY=1");
    3023             : #endif
    3024             : 
    3025         494 :             continue;
    3026             :         }
    3027             : 
    3028             :         /*
    3029             :          * Was it the bgwriter?  Normal exit can be ignored; we'll start a new
    3030             :          * one at the next iteration of the postmaster's main loop, if
    3031             :          * necessary.  Any other exit condition is treated as a crash.
    3032             :          */
    3033       12100 :         if (pid == BgWriterPID)
    3034             :         {
    3035         570 :             BgWriterPID = 0;
    3036         570 :             if (!EXIT_STATUS_0(exitstatus))
    3037         196 :                 HandleChildCrash(pid, exitstatus,
    3038         196 :                                  _("background writer process"));
    3039         570 :             continue;
    3040             :         }
    3041             : 
    3042             :         /*
    3043             :          * Was it the checkpointer?
    3044             :          */
    3045       11530 :         if (pid == CheckpointerPID)
    3046             :         {
    3047         570 :             CheckpointerPID = 0;
    3048         570 :             if (EXIT_STATUS_0(exitstatus) && pmState == PM_SHUTDOWN)
    3049             :             {
    3050             :                 /*
    3051             :                  * OK, we saw normal exit of the checkpointer after it's been
    3052             :                  * told to shut down.  We expect that it wrote a shutdown
    3053             :                  * checkpoint.  (If for some reason it didn't, recovery will
    3054             :                  * occur on next postmaster start.)
    3055             :                  *
    3056             :                  * At this point we should have no normal backend children
    3057             :                  * left (else we'd not be in PM_SHUTDOWN state) but we might
    3058             :                  * have dead_end children to wait for.
    3059             :                  *
    3060             :                  * If we have an archiver subprocess, tell it to do a last
    3061             :                  * archive cycle and quit. Likewise, if we have walsender
    3062             :                  * processes, tell them to send any remaining WAL and quit.
    3063             :                  */
    3064             :                 Assert(Shutdown > NoShutdown);
    3065             : 
    3066             :                 /* Waken archiver for the last time */
    3067         374 :                 if (PgArchPID != 0)
    3068           0 :                     signal_child(PgArchPID, SIGUSR2);
    3069             : 
    3070             :                 /*
    3071             :                  * Waken walsenders for the last time. No regular backends
    3072             :                  * should be around anymore.
    3073             :                  */
    3074         374 :                 SignalChildren(SIGUSR2);
    3075             : 
    3076         374 :                 pmState = PM_SHUTDOWN_2;
    3077             : 
    3078             :                 /*
    3079             :                  * We can also shut down the stats collector now; there's
    3080             :                  * nothing left for it to do.
    3081             :                  */
    3082         748 :                 if (PgStatPID != 0)
    3083         374 :                     signal_child(PgStatPID, SIGQUIT);
    3084             :             }
    3085             :             else
    3086             :             {
    3087             :                 /*
    3088             :                  * Any unexpected exit of the checkpointer (including FATAL
    3089             :                  * exit) is treated as a crash.
    3090             :                  */
    3091         196 :                 HandleChildCrash(pid, exitstatus,
    3092         196 :                                  _("checkpointer process"));
    3093             :             }
    3094             : 
    3095         570 :             continue;
    3096             :         }
    3097             : 
    3098             :         /*
    3099             :          * Was it the wal writer?  Normal exit can be ignored; we'll start a
    3100             :          * new one at the next iteration of the postmaster's main loop, if
    3101             :          * necessary.  Any other exit condition is treated as a crash.
    3102             :          */
    3103       10960 :         if (pid == WalWriterPID)
    3104             :         {
    3105         492 :             WalWriterPID = 0;
    3106         492 :             if (!EXIT_STATUS_0(exitstatus))
    3107         140 :                 HandleChildCrash(pid, exitstatus,
    3108         140 :                                  _("WAL writer process"));
    3109         492 :             continue;
    3110             :         }
    3111             : 
    3112             :         /*
    3113             :          * Was it the wal receiver?  If exit status is zero (normal) or one
    3114             :          * (FATAL exit), we assume everything is all right just like normal
    3115             :          * backends.  (If we need a new wal receiver, we'll start one at the
    3116             :          * next iteration of the postmaster's main loop.)
    3117             :          */
    3118       10468 :         if (pid == WalReceiverPID)
    3119             :         {
    3120         202 :             WalReceiverPID = 0;
    3121         202 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    3122          22 :                 HandleChildCrash(pid, exitstatus,
    3123          22 :                                  _("WAL receiver process"));
    3124         202 :             continue;
    3125             :         }
    3126             : 
    3127             :         /*
    3128             :          * Was it the autovacuum launcher?  Normal exit can be ignored; we'll
    3129             :          * start a new one at the next iteration of the postmaster's main
    3130             :          * loop, if necessary.  Any other exit condition is treated as a
    3131             :          * crash.
    3132             :          */
    3133       10266 :         if (pid == AutoVacPID)
    3134             :         {
    3135         474 :             AutoVacPID = 0;
    3136         474 :             if (!EXIT_STATUS_0(exitstatus))
    3137         134 :                 HandleChildCrash(pid, exitstatus,
    3138         134 :                                  _("autovacuum launcher process"));
    3139         474 :             continue;
    3140             :         }
    3141             : 
    3142             :         /*
    3143             :          * Was it the archiver?  If so, just try to start a new one; no need
    3144             :          * to force reset of the rest of the system.  (If fail, we'll try
    3145             :          * again in future cycles of the main loop.).  Unless we were waiting
    3146             :          * for it to shut down; don't restart it in that case, and
    3147             :          * PostmasterStateMachine() will advance to the next shutdown step.
    3148             :          */
    3149        9792 :         if (pid == PgArchPID)
    3150             :         {
    3151          10 :             PgArchPID = 0;
    3152          10 :             if (!EXIT_STATUS_0(exitstatus))
    3153          10 :                 LogChildExit(LOG, _("archiver process"),
    3154             :                              pid, exitstatus);
    3155          10 :             if (PgArchStartupAllowed())
    3156           0 :                 PgArchPID = pgarch_start();
    3157          10 :             continue;
    3158             :         }
    3159             : 
    3160             :         /*
    3161             :          * Was it the statistics collector?  If so, just try to start a new
    3162             :          * one; no need to force reset of the rest of the system.  (If fail,
    3163             :          * we'll try again in future cycles of the main loop.)
    3164             :          */
    3165        9782 :         if (pid == PgStatPID)
    3166             :         {
    3167         570 :             PgStatPID = 0;
    3168         570 :             if (!EXIT_STATUS_0(exitstatus))
    3169           0 :                 LogChildExit(LOG, _("statistics collector process"),
    3170             :                              pid, exitstatus);
    3171         570 :             if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
    3172           0 :                 PgStatPID = pgstat_start();
    3173         570 :             continue;
    3174             :         }
    3175             : 
    3176             :         /* Was it the system logger?  If so, try to start a new one */
    3177        9212 :         if (pid == SysLoggerPID)
    3178             :         {
    3179           0 :             SysLoggerPID = 0;
    3180             :             /* for safety's sake, launch new logger *first* */
    3181           0 :             SysLoggerPID = SysLogger_Start();
    3182           0 :             if (!EXIT_STATUS_0(exitstatus))
    3183           0 :                 LogChildExit(LOG, _("system logger process"),
    3184             :                              pid, exitstatus);
    3185           0 :             continue;
    3186             :         }
    3187             : 
    3188             :         /* Was it one of our background workers? */
    3189        9212 :         if (CleanupBackgroundWorker(pid, exitstatus))
    3190             :         {
    3191             :             /* have it be restarted */
    3192        2250 :             HaveCrashedWorker = true;
    3193        2250 :             continue;
    3194             :         }
    3195             : 
    3196             :         /*
    3197             :          * Else do standard backend child cleanup.
    3198             :          */
    3199        6962 :         CleanupBackend(pid, exitstatus);
    3200             :     }                           /* loop over pending child-death reports */
    3201             : 
    3202             :     /*
    3203             :      * After cleaning out the SIGCHLD queue, see if we have any state changes
    3204             :      * or actions to make.
    3205             :      */
    3206       11446 :     PostmasterStateMachine();
    3207             : 
    3208             :     /* Done with signal handler */
    3209       10880 :     PG_SETMASK(&UnBlockSig);
    3210             : 
    3211       10880 :     errno = save_errno;
    3212       10880 : }
    3213             : 
    3214             : /*
    3215             :  * Scan the bgworkers list and see if the given PID (which has just stopped
    3216             :  * or crashed) is in it.  Handle its shutdown if so, and return true.  If not a
    3217             :  * bgworker, return false.
    3218             :  *
    3219             :  * This is heavily based on CleanupBackend.  One important difference is that
    3220             :  * we don't know yet that the dying process is a bgworker, so we must be silent
    3221             :  * until we're sure it is.
    3222             :  */
    3223             : static bool
    3224        9212 : CleanupBackgroundWorker(int pid,
    3225             :                         int exitstatus) /* child's exit status */
    3226             : {
    3227             :     char        namebuf[MAXPGPATH];
    3228             :     slist_mutable_iter iter;
    3229             : 
    3230       18690 :     slist_foreach_modify(iter, &BackgroundWorkerList)
    3231             :     {
    3232             :         RegisteredBgWorker *rw;
    3233             : 
    3234       10470 :         rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
    3235             : 
    3236       10470 :         if (rw->rw_pid != pid)
    3237        8220 :             continue;
    3238             : 
    3239             : #ifdef WIN32
    3240             :         /* see CleanupBackend */
    3241             :         if (exitstatus == ERROR_WAIT_NO_CHILDREN)
    3242             :             exitstatus = 0;
    3243             : #endif
    3244             : 
    3245        2250 :         snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
    3246        2250 :                  rw->rw_worker.bgw_type);
    3247             : 
    3248             : 
    3249        2250 :         if (!EXIT_STATUS_0(exitstatus))
    3250             :         {
    3251             :             /* Record timestamp, so we know when to restart the worker. */
    3252         562 :             rw->rw_crashed_at = GetCurrentTimestamp();
    3253             :         }
    3254             :         else
    3255             :         {
    3256             :             /* Zero exit status means terminate */
    3257        1688 :             rw->rw_crashed_at = 0;
    3258        1688 :             rw->rw_terminate = true;
    3259             :         }
    3260             : 
    3261             :         /*
    3262             :          * Additionally, for shared-memory-connected workers, just like a
    3263             :          * backend, any exit status other than 0 or 1 is considered a crash
    3264             :          * and causes a system-wide restart.
    3265             :          */
    3266        2250 :         if ((rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
    3267             :         {
    3268        2250 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    3269             :             {
    3270         140 :                 HandleChildCrash(pid, exitstatus, namebuf);
    3271         140 :                 return true;
    3272             :             }
    3273             :         }
    3274             : 
    3275             :         /*
    3276             :          * We must release the postmaster child slot whether this worker is
    3277             :          * connected to shared memory or not, but we only treat it as a crash
    3278             :          * if it is in fact connected.
    3279             :          */
    3280        2110 :         if (!ReleasePostmasterChildSlot(rw->rw_child_slot) &&
    3281           0 :             (rw->rw_worker.bgw_flags & BGWORKER_SHMEM_ACCESS) != 0)
    3282             :         {
    3283           0 :             HandleChildCrash(pid, exitstatus, namebuf);
    3284           0 :             return true;
    3285             :         }
    3286             : 
    3287             :         /* Get it out of the BackendList and clear out remaining data */
    3288        2110 :         dlist_delete(&rw->rw_backend->elem);
    3289             : #ifdef EXEC_BACKEND
    3290             :         ShmemBackendArrayRemove(rw->rw_backend);
    3291             : #endif
    3292             : 
    3293             :         /*
    3294             :          * It's possible that this background worker started some OTHER
    3295             :          * background worker and asked to be notified when that worker started
    3296             :          * or stopped.  If so, cancel any notifications destined for the
    3297             :          * now-dead backend.
    3298             :          */
    3299        2110 :         if (rw->rw_backend->bgworker_notify)
    3300          48 :             BackgroundWorkerStopNotifications(rw->rw_pid);
    3301        2110 :         free(rw->rw_backend);
    3302        2110 :         rw->rw_backend = NULL;
    3303        2110 :         rw->rw_pid = 0;
    3304        2110 :         rw->rw_child_slot = 0;
    3305        2110 :         ReportBackgroundWorkerExit(&iter);  /* report child death */
    3306             : 
    3307        2110 :         LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
    3308             :                      namebuf, pid, exitstatus);
    3309             : 
    3310        2110 :         return true;
    3311             :     }
    3312             : 
    3313        6962 :     return false;
    3314             : }
    3315             : 
    3316             : /*
    3317             :  * CleanupBackend -- cleanup after terminated backend.
    3318             :  *
    3319             :  * Remove all local state associated with backend.
    3320             :  *
    3321             :  * If you change this, see also CleanupBackgroundWorker.
    3322             :  */
    3323             : static void
    3324        6962 : CleanupBackend(int pid,
    3325             :                int exitstatus)  /* child's exit status. */
    3326             : {
    3327             :     dlist_mutable_iter iter;
    3328             : 
    3329        6962 :     LogChildExit(DEBUG2, _("server process"), pid, exitstatus);
    3330             : 
    3331             :     /*
    3332             :      * If a backend dies in an ugly way then we must signal all other backends
    3333             :      * to quickdie.  If exit status is zero (normal) or one (FATAL exit), we
    3334             :      * assume everything is all right and proceed to remove the backend from
    3335             :      * the active backend list.
    3336             :      */
    3337             : 
    3338             : #ifdef WIN32
    3339             : 
    3340             :     /*
    3341             :      * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
    3342             :      * since that sometimes happens under load when the process fails to start
    3343             :      * properly (long before it starts using shared memory). Microsoft reports
    3344             :      * it is related to mutex failure:
    3345             :      * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
    3346             :      */
    3347             :     if (exitstatus == ERROR_WAIT_NO_CHILDREN)
    3348             :     {
    3349             :         LogChildExit(LOG, _("server process"), pid, exitstatus);
    3350             :         exitstatus = 0;
    3351             :     }
    3352             : #endif
    3353             : 
    3354        6962 :     if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    3355             :     {
    3356         124 :         HandleChildCrash(pid, exitstatus, _("server process"));
    3357         124 :         return;
    3358             :     }
    3359             : 
    3360       15200 :     dlist_foreach_modify(iter, &BackendList)
    3361             :     {
    3362       15200 :         Backend    *bp = dlist_container(Backend, elem, iter.cur);
    3363             : 
    3364       15200 :         if (bp->pid == pid)
    3365             :         {
    3366        6838 :             if (!bp->dead_end)
    3367             :             {
    3368        6798 :                 if (!ReleasePostmasterChildSlot(bp->child_slot))
    3369             :                 {
    3370             :                     /*
    3371             :                      * Uh-oh, the child failed to clean itself up.  Treat as a
    3372             :                      * crash after all.
    3373             :                      */
    3374           0 :                     HandleChildCrash(pid, exitstatus, _("server process"));
    3375           0 :                     return;
    3376             :                 }
    3377             : #ifdef EXEC_BACKEND
    3378             :                 ShmemBackendArrayRemove(bp);
    3379             : #endif
    3380             :             }
    3381        6838 :             if (bp->bgworker_notify)
    3382             :             {
    3383             :                 /*
    3384             :                  * This backend may have been slated to receive SIGUSR1 when
    3385             :                  * some background worker started or stopped.  Cancel those
    3386             :                  * notifications, as we don't want to signal PIDs that are not
    3387             :                  * PostgreSQL backends.  This gets skipped in the (probably
    3388             :                  * very common) case where the backend has never requested any
    3389             :                  * such notifications.
    3390             :                  */
    3391          48 :                 BackgroundWorkerStopNotifications(bp->pid);
    3392             :             }
    3393        6838 :             dlist_delete(iter.cur);
    3394        6838 :             free(bp);
    3395        6838 :             break;
    3396             :         }
    3397             :     }
    3398             : }
    3399             : 
    3400             : /*
    3401             :  * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
    3402             :  * walwriter, autovacuum, or background worker.
    3403             :  *
    3404             :  * The objectives here are to clean up our local state about the child
    3405             :  * process, and to signal all other remaining children to quickdie.
    3406             :  */
    3407             : static void
    3408        1008 : HandleChildCrash(int pid, int exitstatus, const char *procname)
    3409             : {
    3410             :     dlist_mutable_iter iter;
    3411             :     slist_iter  siter;
    3412             :     Backend    *bp;
    3413             :     bool        take_action;
    3414             : 
    3415             :     /*
    3416             :      * We only log messages and send signals if this is the first process
    3417             :      * crash and we're not doing an immediate shutdown; otherwise, we're only
    3418             :      * here to update postmaster's idea of live processes.  If we have already
    3419             :      * signalled children, nonzero exit status is to be expected, so don't
    3420             :      * clutter log.
    3421             :      */
    3422        1008 :     take_action = !FatalError && Shutdown != ImmediateShutdown;
    3423             : 
    3424        1008 :     if (take_action)
    3425             :     {
    3426           4 :         LogChildExit(LOG, procname, pid, exitstatus);
    3427           4 :         ereport(LOG,
    3428             :                 (errmsg("terminating any other active server processes")));
    3429             :     }
    3430             : 
    3431             :     /* Process background workers. */
    3432        2016 :     slist_foreach(siter, &BackgroundWorkerList)
    3433             :     {
    3434             :         RegisteredBgWorker *rw;
    3435             : 
    3436        1008 :         rw = slist_container(RegisteredBgWorker, rw_lnode, siter.cur);
    3437        1008 :         if (rw->rw_pid == 0)
    3438         436 :             continue;           /* not running */
    3439         572 :         if (rw->rw_pid == pid)
    3440             :         {
    3441             :             /*
    3442             :              * Found entry for freshly-dead worker, so remove it.
    3443             :              */
    3444         140 :             (void) ReleasePostmasterChildSlot(rw->rw_child_slot);
    3445         140 :             dlist_delete(&rw->rw_backend->elem);
    3446             : #ifdef EXEC_BACKEND
    3447             :             ShmemBackendArrayRemove(rw->rw_backend);
    3448             : #endif
    3449         140 :             free(rw->rw_backend);
    3450         140 :             rw->rw_backend = NULL;
    3451         140 :             rw->rw_pid = 0;
    3452         140 :             rw->rw_child_slot = 0;
    3453             :             /* don't reset crashed_at */
    3454             :             /* don't report child stop, either */
    3455             :             /* Keep looping so we can signal remaining workers */
    3456             :         }
    3457             :         else
    3458             :         {
    3459             :             /*
    3460             :              * This worker is still alive.  Unless we did so already, tell it
    3461             :              * to commit hara-kiri.
    3462             :              *
    3463             :              * SIGQUIT is the special signal that says exit without proc_exit
    3464             :              * and let the user know what's going on. But if SendStop is set
    3465             :              * (-s on command line), then we send SIGSTOP instead, so that we
    3466             :              * can get core dumps from all backends by hand.
    3467             :              */
    3468         432 :             if (take_action)
    3469             :             {
    3470           4 :                 ereport(DEBUG2,
    3471             :                         (errmsg_internal("sending %s to process %d",
    3472             :                                          (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3473             :                                          (int) rw->rw_pid)));
    3474           4 :                 signal_child(rw->rw_pid, (SendStop ? SIGSTOP : SIGQUIT));
    3475             :             }
    3476             :         }
    3477             :     }
    3478             : 
    3479             :     /* Process regular backends */
    3480        2092 :     dlist_foreach_modify(iter, &BackendList)
    3481             :     {
    3482        1084 :         bp = dlist_container(Backend, elem, iter.cur);
    3483             : 
    3484        1084 :         if (bp->pid == pid)
    3485             :         {
    3486             :             /*
    3487             :              * Found entry for freshly-dead backend, so remove it.
    3488             :              */
    3489         124 :             if (!bp->dead_end)
    3490             :             {
    3491         124 :                 (void) ReleasePostmasterChildSlot(bp->child_slot);
    3492             : #ifdef EXEC_BACKEND
    3493             :                 ShmemBackendArrayRemove(bp);
    3494             : #endif
    3495             :             }
    3496         124 :             dlist_delete(iter.cur);
    3497         124 :             free(bp);
    3498             :             /* Keep looping so we can signal remaining backends */
    3499             :         }
    3500             :         else
    3501             :         {
    3502             :             /*
    3503             :              * This backend is still alive.  Unless we did so already, tell it
    3504             :              * to commit hara-kiri.
    3505             :              *
    3506             :              * SIGQUIT is the special signal that says exit without proc_exit
    3507             :              * and let the user know what's going on. But if SendStop is set
    3508             :              * (-s on command line), then we send SIGSTOP instead, so that we
    3509             :              * can get core dumps from all backends by hand.
    3510             :              *
    3511             :              * We could exclude dead_end children here, but at least in the
    3512             :              * SIGSTOP case it seems better to include them.
    3513             :              *
    3514             :              * Background workers were already processed above; ignore them
    3515             :              * here.
    3516             :              */
    3517         960 :             if (bp->bkend_type == BACKEND_TYPE_BGWORKER)
    3518         432 :                 continue;
    3519             : 
    3520         528 :             if (take_action)
    3521             :             {
    3522           4 :                 ereport(DEBUG2,
    3523             :                         (errmsg_internal("sending %s to process %d",
    3524             :                                          (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3525             :                                          (int) bp->pid)));
    3526           4 :                 signal_child(bp->pid, (SendStop ? SIGSTOP : SIGQUIT));
    3527             :             }
    3528             :         }
    3529             :     }
    3530             : 
    3531             :     /* Take care of the startup process too */
    3532        1008 :     if (pid == StartupPID)
    3533             :     {
    3534           0 :         StartupPID = 0;
    3535             :         /* Caller adjusts StartupStatus, so don't touch it here */
    3536             :     }
    3537        1008 :     else if (StartupPID != 0 && take_action)
    3538             :     {
    3539           0 :         ereport(DEBUG2,
    3540             :                 (errmsg_internal("sending %s to process %d",
    3541             :                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3542             :                                  (int) StartupPID)));
    3543           0 :         signal_child(StartupPID, (SendStop ? SIGSTOP : SIGQUIT));
    3544           0 :         StartupStatus = STARTUP_SIGNALED;
    3545             :     }
    3546             : 
    3547             :     /* Take care of the bgwriter too */
    3548        1008 :     if (pid == BgWriterPID)
    3549           0 :         BgWriterPID = 0;
    3550        1008 :     else if (BgWriterPID != 0 && take_action)
    3551             :     {
    3552           4 :         ereport(DEBUG2,
    3553             :                 (errmsg_internal("sending %s to process %d",
    3554             :                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3555             :                                  (int) BgWriterPID)));
    3556           4 :         signal_child(BgWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
    3557             :     }
    3558             : 
    3559             :     /* Take care of the checkpointer too */
    3560        1008 :     if (pid == CheckpointerPID)
    3561           0 :         CheckpointerPID = 0;
    3562        1008 :     else if (CheckpointerPID != 0 && take_action)
    3563             :     {
    3564           4 :         ereport(DEBUG2,
    3565             :                 (errmsg_internal("sending %s to process %d",
    3566             :                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3567             :                                  (int) CheckpointerPID)));
    3568           4 :         signal_child(CheckpointerPID, (SendStop ? SIGSTOP : SIGQUIT));
    3569             :     }
    3570             : 
    3571             :     /* Take care of the walwriter too */
    3572        1008 :     if (pid == WalWriterPID)
    3573           0 :         WalWriterPID = 0;
    3574        1008 :     else if (WalWriterPID != 0 && take_action)
    3575             :     {
    3576           4 :         ereport(DEBUG2,
    3577             :                 (errmsg_internal("sending %s to process %d",
    3578             :                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3579             :                                  (int) WalWriterPID)));
    3580           4 :         signal_child(WalWriterPID, (SendStop ? SIGSTOP : SIGQUIT));
    3581             :     }
    3582             : 
    3583             :     /* Take care of the walreceiver too */
    3584        1008 :     if (pid == WalReceiverPID)
    3585           0 :         WalReceiverPID = 0;
    3586        1008 :     else if (WalReceiverPID != 0 && take_action)
    3587             :     {
    3588           0 :         ereport(DEBUG2,
    3589             :                 (errmsg_internal("sending %s to process %d",
    3590             :                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3591             :                                  (int) WalReceiverPID)));
    3592           0 :         signal_child(WalReceiverPID, (SendStop ? SIGSTOP : SIGQUIT));
    3593             :     }
    3594             : 
    3595             :     /* Take care of the autovacuum launcher too */
    3596        1008 :     if (pid == AutoVacPID)
    3597           0 :         AutoVacPID = 0;
    3598        1008 :     else if (AutoVacPID != 0 && take_action)
    3599             :     {
    3600           4 :         ereport(DEBUG2,
    3601             :                 (errmsg_internal("sending %s to process %d",
    3602             :                                  (SendStop ? "SIGSTOP" : "SIGQUIT"),
    3603             :                                  (int) AutoVacPID)));
    3604           4 :         signal_child(AutoVacPID, (SendStop ? SIGSTOP : SIGQUIT));
    3605             :     }
    3606             : 
    3607             :     /*
    3608             :      * Force a power-cycle of the pgarch process too.  (This isn't absolutely
    3609             :      * necessary, but it seems like a good idea for robustness, and it
    3610             :      * simplifies the state-machine logic in the case where a shutdown request
    3611             :      * arrives during crash processing.)
    3612             :      */
    3613        1008 :     if (PgArchPID != 0 && take_action)
    3614             :     {
    3615           0 :         ereport(DEBUG2,
    3616             :                 (errmsg_internal("sending %s to process %d",
    3617             :                                  "SIGQUIT",
    3618             :                                  (int) PgArchPID)));
    3619           0 :         signal_child(PgArchPID, SIGQUIT);
    3620             :     }
    3621             : 
    3622             :     /*
    3623             :      * Force a power-cycle of the pgstat process too.  (This isn't absolutely
    3624             :      * necessary, but it seems like a good idea for robustness, and it
    3625             :      * simplifies the state-machine logic in the case where a shutdown request
    3626             :      * arrives during crash processing.)
    3627             :      */
    3628        1008 :     if (PgStatPID != 0 && take_action)
    3629             :     {
    3630           4 :         ereport(DEBUG2,
    3631             :                 (errmsg_internal("sending %s to process %d",
    3632             :                                  "SIGQUIT",
    3633             :                                  (int) PgStatPID)));
    3634           4 :         signal_child(PgStatPID, SIGQUIT);
    3635           4 :         allow_immediate_pgstat_restart();
    3636             :     }
    3637             : 
    3638             :     /* We do NOT restart the syslogger */
    3639             : 
    3640        1008 :     if (Shutdown != ImmediateShutdown)
    3641          28 :         FatalError = true;
    3642             : 
    3643             :     /* We now transit into a state of waiting for children to die */
    3644        2016 :     if (pmState == PM_RECOVERY ||
    3645        2016 :         pmState == PM_HOT_STANDBY ||
    3646        2012 :         pmState == PM_RUN ||
    3647        2008 :         pmState == PM_WAIT_BACKUP ||
    3648        2008 :         pmState == PM_WAIT_READONLY ||
    3649        1004 :         pmState == PM_SHUTDOWN)
    3650           4 :         pmState = PM_WAIT_BACKENDS;
    3651             : 
    3652             :     /*
    3653             :      * .. and if this doesn't happen quickly enough, now the clock is ticking
    3654             :      * for us to kill them without mercy.
    3655             :      */
    3656        1008 :     if (AbortStartTime == 0)
    3657           4 :         AbortStartTime = time(NULL);
    3658        1008 : }
    3659             : 
    3660             : /*
    3661             :  * Log the death of a child process.
    3662             :  */
    3663             : static void
    3664        9086 : LogChildExit(int lev, const char *procname, int pid, int exitstatus)
    3665             : {
    3666             :     /*
    3667             :      * size of activity_buffer is arbitrary, but set equal to default
    3668             :      * track_activity_query_size
    3669             :      */
    3670             :     char        activity_buffer[1024];
    3671        9086 :     const char *activity = NULL;
    3672             : 
    3673        9086 :     if (!EXIT_STATUS_0(exitstatus))
    3674         694 :         activity = pgstat_get_crashed_backend_activity(pid,
    3675             :                                                        activity_buffer,
    3676             :                                                        sizeof(activity_buffer));
    3677             : 
    3678        9086 :     if (WIFEXITED(exitstatus))
    3679        9082 :         ereport(lev,
    3680             : 
    3681             :         /*------
    3682             :           translator: %s is a noun phrase describing a child process, such as
    3683             :           "server process" */
    3684             :                 (errmsg("%s (PID %d) exited with exit code %d",
    3685             :                         procname, pid, WEXITSTATUS(exitstatus)),
    3686             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    3687           4 :     else if (WIFSIGNALED(exitstatus))
    3688             :     {
    3689             : #if defined(WIN32)
    3690             :         ereport(lev,
    3691             : 
    3692             :         /*------
    3693             :           translator: %s is a noun phrase describing a child process, such as
    3694             :           "server process" */
    3695             :                 (errmsg("%s (PID %d) was terminated by exception 0x%X",
    3696             :                         procname, pid, WTERMSIG(exitstatus)),
    3697             :                  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
    3698             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    3699             : #else
    3700           4 :         ereport(lev,
    3701             : 
    3702             :         /*------
    3703             :           translator: %s is a noun phrase describing a child process, such as
    3704             :           "server process" */
    3705             :                 (errmsg("%s (PID %d) was terminated by signal %d: %s",
    3706             :                         procname, pid, WTERMSIG(exitstatus),
    3707             :                         pg_strsignal(WTERMSIG(exitstatus))),
    3708             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    3709             : #endif
    3710             :     }
    3711             :     else
    3712           0 :         ereport(lev,
    3713             : 
    3714             :         /*------
    3715             :           translator: %s is a noun phrase describing a child process, such as
    3716             :           "server process" */
    3717             :                 (errmsg("%s (PID %d) exited with unrecognized status %d",
    3718             :                         procname, pid, exitstatus),
    3719             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    3720        9086 : }
    3721             : 
    3722             : /*
    3723             :  * Advance the postmaster's state machine and take actions as appropriate
    3724             :  *
    3725             :  * This is common code for pmdie(), reaper() and sigusr1_handler(), which
    3726             :  * receive the signals that might mean we need to change state.
    3727             :  */
    3728             : static void
    3729       12516 : PostmasterStateMachine(void)
    3730             : {
    3731       12516 :     if (pmState == PM_WAIT_BACKUP)
    3732             :     {
    3733             :         /*
    3734             :          * PM_WAIT_BACKUP state ends when online backup mode is not active.
    3735             :          */
    3736           8 :         if (!BackupInProgress())
    3737           8 :             pmState = PM_WAIT_BACKENDS;
    3738             :     }
    3739             : 
    3740       12516 :     if (pmState == PM_WAIT_READONLY)
    3741             :     {
    3742             :         /*
    3743             :          * PM_WAIT_READONLY state ends when we have no regular backends that
    3744             :          * have been started during recovery.  We kill the startup and
    3745             :          * walreceiver processes and transition to PM_WAIT_BACKENDS.  Ideally,
    3746             :          * we might like to kill these processes first and then wait for
    3747             :          * backends to die off, but that doesn't work at present because
    3748             :          * killing the startup process doesn't release its locks.
    3749             :          */
    3750           0 :         if (CountChildren(BACKEND_TYPE_NORMAL) == 0)
    3751             :         {
    3752           0 :             if (StartupPID != 0)
    3753           0 :                 signal_child(StartupPID, SIGTERM);
    3754           0 :             if (WalReceiverPID != 0)
    3755           0 :                 signal_child(WalReceiverPID, SIGTERM);
    3756           0 :             pmState = PM_WAIT_BACKENDS;
    3757             :         }
    3758             :     }
    3759             : 
    3760             :     /*
    3761             :      * If we are in a state-machine state that implies waiting for backends to
    3762             :      * exit, see if they're all gone, and change state if so.
    3763             :      */
    3764       12516 :     if (pmState == PM_WAIT_BACKENDS)
    3765             :     {
    3766             :         /*
    3767             :          * PM_WAIT_BACKENDS state ends when we have no regular backends
    3768             :          * (including autovac workers), no bgworkers (including unconnected
    3769             :          * ones), and no walwriter, autovac launcher or bgwriter.  If we are
    3770             :          * doing crash recovery or an immediate shutdown then we expect the
    3771             :          * checkpointer to exit as well, otherwise not. The archiver, stats,
    3772             :          * and syslogger processes are disregarded since they are not
    3773             :          * connected to shared memory; we also disregard dead_end children
    3774             :          * here. Walsenders are also disregarded, they will be terminated
    3775             :          * later after writing the checkpoint record, like the archiver
    3776             :          * process.
    3777             :          */
    3778        4014 :         if (CountChildren(BACKEND_TYPE_NORMAL | BACKEND_TYPE_WORKER) == 0 &&
    3779        2560 :             StartupPID == 0 &&
    3780        2436 :             WalReceiverPID == 0 &&
    3781        2118 :             BgWriterPID == 0 &&
    3782        1546 :             (CheckpointerPID == 0 ||
    3783        2148 :              (!FatalError && Shutdown < ImmediateShutdown)) &&
    3784        1558 :             WalWriterPID == 0 &&
    3785         686 :             AutoVacPID == 0)
    3786             :         {
    3787         570 :             if (Shutdown >= ImmediateShutdown || FatalError)
    3788             :             {
    3789             :                 /*
    3790             :                  * Start waiting for dead_end children to die.  This state
    3791             :                  * change causes ServerLoop to stop creating new ones.
    3792             :                  */
    3793         196 :                 pmState = PM_WAIT_DEAD_END;
    3794             : 
    3795             :                 /*
    3796             :                  * We already SIGQUIT'd the archiver and stats processes, if
    3797             :                  * any, when we started immediate shutdown or entered
    3798             :                  * FatalError state.
    3799             :                  */
    3800             :             }
    3801             :             else
    3802             :             {
    3803             :                 /*
    3804             :                  * If we get here, we are proceeding with normal shutdown. All
    3805             :                  * the regular children are gone, and it's time to tell the
    3806             :                  * checkpointer to do a shutdown checkpoint.
    3807             :                  */
    3808             :                 Assert(Shutdown > NoShutdown);
    3809             :                 /* Start the checkpointer if not running */
    3810         374 :                 if (CheckpointerPID == 0)
    3811           0 :                     CheckpointerPID = StartCheckpointer();
    3812             :                 /* And tell it to shut down */
    3813         374 :                 if (CheckpointerPID != 0)
    3814             :                 {
    3815         374 :                     signal_child(CheckpointerPID, SIGUSR2);
    3816         374 :                     pmState = PM_SHUTDOWN;
    3817             :                 }
    3818             :                 else
    3819             :                 {
    3820             :                     /*
    3821             :                      * If we failed to fork a checkpointer, just shut down.
    3822             :                      * Any required cleanup will happen at next restart. We
    3823             :                      * set FatalError so that an "abnormal shutdown" message
    3824             :                      * gets logged when we exit.
    3825             :                      */
    3826           0 :                     FatalError = true;
    3827           0 :                     pmState = PM_WAIT_DEAD_END;
    3828             : 
    3829             :                     /* Kill the walsenders, archiver and stats collector too */
    3830           0 :                     SignalChildren(SIGQUIT);
    3831           0 :                     if (PgArchPID != 0)
    3832           0 :                         signal_child(PgArchPID, SIGQUIT);
    3833           0 :                     if (PgStatPID != 0)
    3834           0 :                         signal_child(PgStatPID, SIGQUIT);
    3835             :                 }
    3836             :             }
    3837             :         }
    3838             :     }
    3839             : 
    3840       12516 :     if (pmState == PM_SHUTDOWN_2)
    3841             :     {
    3842             :         /*
    3843             :          * PM_SHUTDOWN_2 state ends when there's no other children than
    3844             :          * dead_end children left. There shouldn't be any regular backends
    3845             :          * left by now anyway; what we're really waiting for is walsenders and
    3846             :          * archiver.
    3847             :          */
    3848         426 :         if (PgArchPID == 0 && CountChildren(BACKEND_TYPE_ALL) == 0)
    3849             :         {
    3850         374 :             pmState = PM_WAIT_DEAD_END;
    3851             :         }
    3852             :     }
    3853             : 
    3854       12516 :     if (pmState == PM_WAIT_DEAD_END)
    3855             :     {
    3856             :         /*
    3857             :          * PM_WAIT_DEAD_END state ends when the BackendList is entirely empty
    3858             :          * (ie, no dead_end children remain), and the archiver and stats
    3859             :          * collector are gone too.
    3860             :          *
    3861             :          * The reason we wait for those two is to protect them against a new
    3862             :          * postmaster starting conflicting subprocesses; this isn't an
    3863             :          * ironclad protection, but it at least helps in the
    3864             :          * shutdown-and-immediately-restart scenario.  Note that they have
    3865             :          * already been sent appropriate shutdown signals, either during a
    3866             :          * normal state transition leading up to PM_WAIT_DEAD_END, or during
    3867             :          * FatalError processing.
    3868             :          */
    3869        2296 :         if (dlist_is_empty(&BackendList) &&
    3870        2280 :             PgArchPID == 0 && PgStatPID == 0)
    3871             :         {
    3872             :             /* These other guys should be dead already */
    3873             :             Assert(StartupPID == 0);
    3874             :             Assert(WalReceiverPID == 0);
    3875             :             Assert(BgWriterPID == 0);
    3876             :             Assert(CheckpointerPID == 0);
    3877             :             Assert(WalWriterPID == 0);
    3878             :             Assert(AutoVacPID == 0);
    3879             :             /* syslogger is not considered here */
    3880         570 :             pmState = PM_NO_CHILDREN;
    3881             :         }
    3882             :     }
    3883             : 
    3884             :     /*
    3885             :      * If we've been told to shut down, we exit as soon as there are no
    3886             :      * remaining children.  If there was a crash, cleanup will occur at the
    3887             :      * next startup.  (Before PostgreSQL 8.3, we tried to recover from the
    3888             :      * crash before exiting, but that seems unwise if we are quitting because
    3889             :      * we got SIGTERM from init --- there may well not be time for recovery
    3890             :      * before init decides to SIGKILL us.)
    3891             :      *
    3892             :      * Note that the syslogger continues to run.  It will exit when it sees
    3893             :      * EOF on its input pipe, which happens when there are no more upstream
    3894             :      * processes.
    3895             :      */
    3896       12516 :     if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
    3897             :     {
    3898         566 :         if (FatalError)
    3899             :         {
    3900           0 :             ereport(LOG, (errmsg("abnormal database system shutdown")));
    3901           0 :             ExitPostmaster(1);
    3902             :         }
    3903             :         else
    3904             :         {
    3905             :             /*
    3906             :              * Terminate exclusive backup mode to avoid recovery after a clean
    3907             :              * fast shutdown.  Since an exclusive backup can only be taken
    3908             :              * during normal running (and not, for example, while running
    3909             :              * under Hot Standby) it only makes sense to do this if we reached
    3910             :              * normal running. If we're still in recovery, the backup file is
    3911             :              * one we're recovering *from*, and we must keep it around so that
    3912             :              * recovery restarts from the right place.
    3913             :              */
    3914         566 :             if (ReachedNormalRunning)
    3915         488 :                 CancelBackup();
    3916             : 
    3917             :             /* Normal exit from the postmaster is here */
    3918         566 :             ExitPostmaster(0);
    3919             :         }
    3920             :     }
    3921             : 
    3922             :     /*
    3923             :      * If the startup process failed, or the user does not want an automatic
    3924             :      * restart after backend crashes, wait for all non-syslogger children to
    3925             :      * exit, and then exit postmaster.  We don't try to reinitialize when the
    3926             :      * startup process fails, because more than likely it will just fail again
    3927             :      * and we will keep trying forever.
    3928             :      */
    3929       11954 :     if (pmState == PM_NO_CHILDREN &&
    3930           8 :         (StartupStatus == STARTUP_CRASHED || !restart_after_crash))
    3931           0 :         ExitPostmaster(1);
    3932             : 
    3933             :     /*
    3934             :      * If we need to recover from a crash, wait for all non-syslogger children
    3935             :      * to exit, then reset shmem and StartupDataBase.
    3936             :      */
    3937       11950 :     if (FatalError && pmState == PM_NO_CHILDREN)
    3938             :     {
    3939           4 :         ereport(LOG,
    3940             :                 (errmsg("all server processes terminated; reinitializing")));
    3941             : 
    3942             :         /* allow background workers to immediately restart */
    3943           4 :         ResetBackgroundWorkerCrashTimes();
    3944             : 
    3945           4 :         shmem_exit(1);
    3946             : 
    3947             :         /* re-read control file into local memory */
    3948           4 :         LocalProcessControlFile(true);
    3949             : 
    3950           4 :         reset_shared();
    3951             : 
    3952           4 :         StartupPID = StartupDataBase();
    3953             :         Assert(StartupPID != 0);
    3954           4 :         StartupStatus = STARTUP_RUNNING;
    3955           4 :         pmState = PM_STARTUP;
    3956             :         /* crash recovery started, reset SIGKILL flag */
    3957           4 :         AbortStartTime = 0;
    3958             :     }
    3959       11950 : }
    3960             : 
    3961             : 
    3962             : /*
    3963             :  * Send a signal to a postmaster child process
    3964             :  *
    3965             :  * On systems that have setsid(), each child process sets itself up as a
    3966             :  * process group leader.  For signals that are generally interpreted in the
    3967             :  * appropriate fashion, we signal the entire process group not just the
    3968             :  * direct child process.  This allows us to, for example, SIGQUIT a blocked
    3969             :  * archive_recovery script, or SIGINT a script being run by a backend via
    3970             :  * system().
    3971             :  *
    3972             :  * There is a race condition for recently-forked children: they might not
    3973             :  * have executed setsid() yet.  So we signal the child directly as well as
    3974             :  * the group.  We assume such a child will handle the signal before trying
    3975             :  * to spawn any grandchild processes.  We also assume that signaling the
    3976             :  * child twice will not cause any problems.
    3977             :  */
    3978             : static void
    3979        4142 : signal_child(pid_t pid, int signal)
    3980             : {
    3981        4142 :     if (kill(pid, signal) < 0)
    3982           0 :         elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
    3983             : #ifdef HAVE_SETSID
    3984        4142 :     switch (signal)
    3985             :     {
    3986             :         case SIGINT:
    3987             :         case SIGTERM:
    3988             :         case SIGQUIT:
    3989             :         case SIGSTOP:
    3990             :         case SIGKILL:
    3991        3280 :             if (kill(-pid, signal) < 0)
    3992           6 :                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
    3993        3280 :             break;
    3994             :         default:
    3995         862 :             break;
    3996             :     }
    3997             : #endif
    3998        4142 : }
    3999             : 
    4000             : /*
    4001             :  * Send a signal to the targeted children (but NOT special children;
    4002             :  * dead_end children are never signaled, either).
    4003             :  */
    4004             : static bool
    4005         988 : SignalSomeChildren(int signal, int target)
    4006             : {
    4007             :     dlist_iter  iter;
    4008         988 :     bool        signaled = false;
    4009             : 
    4010        2048 :     dlist_foreach(iter, &BackendList)
    4011             :     {
    4012        1060 :         Backend    *bp = dlist_container(Backend, elem, iter.cur);
    4013             : 
    4014        1060 :         if (bp->dead_end)
    4015           0 :             continue;
    4016             : 
    4017             :         /*
    4018             :          * Since target == BACKEND_TYPE_ALL is the most common case, we test
    4019             :          * it first and avoid touching shared memory for every child.
    4020             :          */
    4021        1060 :         if (target != BACKEND_TYPE_ALL)
    4022             :         {
    4023             :             /*
    4024             :              * Assign bkend_type for any recently announced WAL Sender
    4025             :              * processes.
    4026             :              */
    4027         880 :             if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
    4028         252 :                 IsPostmasterChildWalSender(bp->child_slot))
    4029          34 :                 bp->bkend_type = BACKEND_TYPE_WALSND;
    4030             : 
    4031         628 :             if (!(target & bp->bkend_type))
    4032          42 :                 continue;
    4033             :         }
    4034             : 
    4035        1018 :         ereport(DEBUG4,
    4036             :                 (errmsg_internal("sending signal %d to process %d",
    4037             :                                  signal, (int) bp->pid)));
    4038        1018 :         signal_child(bp->pid, signal);
    4039        1018 :         signaled = true;
    4040             :     }
    4041         988 :     return signaled;
    4042             : }
    4043             : 
    4044             : /*
    4045             :  * Send a termination signal to children.  This considers all of our children
    4046             :  * processes, except syslogger and dead_end backends.
    4047             :  */
    4048             : static void
    4049         192 : TerminateChildren(int signal)
    4050             : {
    4051         192 :     SignalChildren(signal);
    4052         192 :     if (StartupPID != 0)
    4053             :     {
    4054          56 :         signal_child(StartupPID, signal);
    4055          56 :         if (signal == SIGQUIT || signal == SIGKILL)
    4056          56 :             StartupStatus = STARTUP_SIGNALED;
    4057             :     }
    4058         192 :     if (BgWriterPID != 0)
    4059         192 :         signal_child(BgWriterPID, signal);
    4060         192 :     if (CheckpointerPID != 0)
    4061         192 :         signal_child(CheckpointerPID, signal);
    4062         192 :     if (WalWriterPID != 0)
    4063         136 :         signal_child(WalWriterPID, signal);
    4064         192 :     if (WalReceiverPID != 0)
    4065          22 :         signal_child(WalReceiverPID, signal);
    4066         192 :     if (AutoVacPID != 0)
    4067         130 :         signal_child(AutoVacPID, signal);
    4068         192 :     if (PgArchPID != 0)
    4069          10 :         signal_child(PgArchPID, signal);
    4070         192 :     if (PgStatPID != 0)
    4071         192 :         signal_child(PgStatPID, signal);
    4072         192 : }
    4073             : 
    4074             : /*
    4075             :  * BackendStartup -- start backend process
    4076             :  *
    4077             :  * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
    4078             :  *
    4079             :  * Note: if you change this code, also consider StartAutovacuumWorker.
    4080             :  */
    4081             : static int
    4082        6906 : BackendStartup(Port *port)
    4083             : {
    4084             :     Backend    *bn;             /* for backend cleanup */
    4085             :     pid_t       pid;
    4086             : 
    4087             :     /*
    4088             :      * Create backend data structure.  Better before the fork() so we can
    4089             :      * handle failure cleanly.
    4090             :      */
    4091        6906 :     bn = (Backend *) malloc(sizeof(Backend));
    4092        6906 :     if (!bn)
    4093             :     {
    4094           0 :         ereport(LOG,
    4095             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    4096             :                  errmsg("out of memory")));
    4097           0 :         return STATUS_ERROR;
    4098             :     }
    4099             : 
    4100             :     /*
    4101             :      * Compute the cancel key that will be assigned to this backend. The
    4102             :      * backend will have its own copy in the forked-off process' value of
    4103             :      * MyCancelKey, so that it can transmit the key to the frontend.
    4104             :      */
    4105        6906 :     if (!RandomCancelKey(&MyCancelKey))
    4106             :     {
    4107           0 :         free(bn);
    4108           0 :         ereport(LOG,
    4109             :                 (errcode(ERRCODE_INTERNAL_ERROR),
    4110             :                  errmsg("could not generate random cancel key")));
    4111           0 :         return STATUS_ERROR;
    4112             :     }
    4113             : 
    4114        6906 :     bn->cancel_key = MyCancelKey;
    4115             : 
    4116             :     /* Pass down canAcceptConnections state */
    4117        6906 :     port->canAcceptConnections = canAcceptConnections();
    4118        6946 :     bn->dead_end = (port->canAcceptConnections != CAC_OK &&
    4119          40 :                     port->canAcceptConnections != CAC_WAITBACKUP);
    4120             : 
    4121             :     /*
    4122             :      * Unless it's a dead_end child, assign it a child slot number
    4123             :      */
    4124        6906 :     if (!bn->dead_end)
    4125        6866 :         bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
    4126             :     else
    4127          40 :         bn->child_slot = 0;
    4128             : 
    4129             :     /* Hasn't asked to be notified about any bgworkers yet */
    4130        6906 :     bn->bgworker_notify = false;
    4131             : 
    4132             : #ifdef EXEC_BACKEND
    4133             :     pid = backend_forkexec(port);
    4134             : #else                           /* !EXEC_BACKEND */
    4135        6906 :     pid = fork_process();
    4136       13700 :     if (pid == 0)               /* child */
    4137             :     {
    4138        6796 :         free(bn);
    4139             : 
    4140             :         /* Detangle from postmaster */
    4141        6796 :         InitPostmasterChild();
    4142             : 
    4143             :         /* Close the postmaster's sockets */
    4144        6796 :         ClosePostmasterPorts(false);
    4145             : 
    4146             :         /* Perform additional initialization and collect startup packet */
    4147        6796 :         BackendInitialize(port);
    4148             : 
    4149             :         /* And run the backend */
    4150        6720 :         BackendRun(port);
    4151             :     }
    4152             : #endif                          /* EXEC_BACKEND */
    4153             : 
    4154        6904 :     if (pid < 0)
    4155             :     {
    4156             :         /* in parent, fork failed */
    4157           0 :         int         save_errno = errno;
    4158             : 
    4159           0 :         if (!bn->dead_end)
    4160           0 :             (void) ReleasePostmasterChildSlot(bn->child_slot);
    4161           0 :         free(bn);
    4162           0 :         errno = save_errno;
    4163           0 :         ereport(LOG,
    4164             :                 (errmsg("could not fork new process for connection: %m")));
    4165           0 :         report_fork_failure_to_client(port, save_errno);
    4166           0 :         return STATUS_ERROR;
    4167             :     }
    4168             : 
    4169             :     /* in parent, successful fork */
    4170        6904 :     ereport(DEBUG2,
    4171             :             (errmsg_internal("forked new backend, pid=%d socket=%d",
    4172             :                              (int) pid, (int) port->sock)));
    4173             : 
    4174             :     /*
    4175             :      * Everything's been successful, it's safe to add this backend to our list
    4176             :      * of backends.
    4177             :      */
    4178        6904 :     bn->pid = pid;
    4179        6904 :     bn->bkend_type = BACKEND_TYPE_NORMAL;    /* Can change later to WALSND */
    4180        6904 :     dlist_push_head(&BackendList, &bn->elem);
    4181             : 
    4182             : #ifdef EXEC_BACKEND
    4183             :     if (!bn->dead_end)
    4184             :         ShmemBackendArrayAdd(bn);
    4185             : #endif
    4186             : 
    4187        6904 :     return STATUS_OK;
    4188             : }
    4189             : 
    4190             : /*
    4191             :  * Try to report backend fork() failure to client before we close the
    4192             :  * connection.  Since we do not care to risk blocking the postmaster on
    4193             :  * this connection, we set the connection to non-blocking and try only once.
    4194             :  *
    4195             :  * This is grungy special-purpose code; we cannot use backend libpq since
    4196             :  * it's not up and running.
    4197             :  */
    4198             : static void
    4199           0 : report_fork_failure_to_client(Port *port, int errnum)
    4200             : {
    4201             :     char        buffer[1000];
    4202             :     int         rc;
    4203             : 
    4204             :     /* Format the error message packet (always V2 protocol) */
    4205           0 :     snprintf(buffer, sizeof(buffer), "E%s%s\n",
    4206             :              _("could not fork new process for connection: "),
    4207             :              strerror(errnum));
    4208             : 
    4209             :     /* Set port to non-blocking.  Don't do send() if this fails */
    4210           0 :     if (!pg_set_noblock(port->sock))
    4211           0 :         return;
    4212             : 
    4213             :     /* We'll retry after EINTR, but ignore all other failures */
    4214             :     do
    4215             :     {
    4216           0 :         rc = send(port->sock, buffer, strlen(buffer) + 1, 0);
    4217           0 :     } while (rc < 0 && errno == EINTR);
    4218             : }
    4219             : 
    4220             : 
    4221             : /*
    4222             :  * BackendInitialize -- initialize an interactive (postmaster-child)
    4223             :  *              backend process, and collect the client's startup packet.
    4224             :  *
    4225             :  * returns: nothing.  Will not return at all if there's any failure.
    4226             :  *
    4227             :  * Note: this code does not depend on having any access to shared memory.
    4228             :  * In the EXEC_BACKEND case, we are physically attached to shared memory
    4229             :  * but have not yet set up most of our local pointers to shmem structures.
    4230             :  */
    4231             : static void
    4232        6796 : BackendInitialize(Port *port)
    4233             : {
    4234             :     int         status;
    4235             :     int         ret;
    4236             :     char        remote_host[NI_MAXHOST];
    4237             :     char        remote_port[NI_MAXSERV];
    4238             :     char        remote_ps_data[NI_MAXHOST];
    4239             : 
    4240             :     /* Save port etc. for ps status */
    4241        6796 :     MyProcPort = port;
    4242             : 
    4243             :     /*
    4244             :      * PreAuthDelay is a debugging aid for investigating problems in the
    4245             :      * authentication cycle: it can be set in postgresql.conf to allow time to
    4246             :      * attach to the newly-forked backend with a debugger.  (See also
    4247             :      * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
    4248             :      * is not honored until after authentication.)
    4249             :      */
    4250        6796 :     if (PreAuthDelay > 0)
    4251           0 :         pg_usleep(PreAuthDelay * 1000000L);
    4252             : 
    4253             :     /* This flag will remain set until InitPostgres finishes authentication */
    4254        6796 :     ClientAuthInProgress = true;    /* limit visibility of log messages */
    4255             : 
    4256             :     /* set these to empty in case they are needed before we set them up */
    4257        6796 :     port->remote_host = "";
    4258        6796 :     port->remote_port = "";
    4259             : 
    4260             :     /*
    4261             :      * Initialize libpq and enable reporting of ereport errors to the client.
    4262             :      * Must do this now because authentication uses libpq to send messages.
    4263             :      */
    4264        6796 :     pq_init();                  /* initialize libpq to talk to client */
    4265        6796 :     whereToSendOutput = DestRemote; /* now safe to ereport to client */
    4266             : 
    4267             :     /*
    4268             :      * We arrange for a simple exit(1) if we receive SIGTERM or SIGQUIT or
    4269             :      * timeout while trying to collect the startup packet.  Otherwise the
    4270             :      * postmaster cannot shutdown the database FAST or IMMED cleanly if a
    4271             :      * buggy client fails to send the packet promptly.  XXX it follows that
    4272             :      * the remainder of this function must tolerate losing control at any
    4273             :      * instant.  Likewise, any pg_on_exit_callback registered before or during
    4274             :      * this function must be prepared to execute at any instant between here
    4275             :      * and the end of this function.  Furthermore, affected callbacks execute
    4276             :      * partially or not at all when a second exit-inducing signal arrives
    4277             :      * after proc_exit_prepare() decrements on_proc_exit_index.  (Thanks to
    4278             :      * that mechanic, callbacks need not anticipate more than one call.)  This
    4279             :      * is fragile; it ought to instead follow the norm of handling interrupts
    4280             :      * at selected, safe opportunities.
    4281             :      */
    4282        6796 :     pqsignal(SIGTERM, startup_die);
    4283        6796 :     pqsignal(SIGQUIT, startup_die);
    4284        6796 :     InitializeTimeouts();       /* establishes SIGALRM handler */
    4285        6796 :     PG_SETMASK(&StartupBlockSig);
    4286             : 
    4287             :     /*
    4288             :      * Get the remote host name and port for logging and status display.
    4289             :      */
    4290        6794 :     remote_host[0] = '\0';
    4291        6794 :     remote_port[0] = '\0';
    4292        6794 :     if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
    4293             :                                   remote_host, sizeof(remote_host),
    4294             :                                   remote_port, sizeof(remote_port),
    4295             :                                   (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
    4296           0 :         ereport(WARNING,
    4297             :                 (errmsg_internal("pg_getnameinfo_all() failed: %s",
    4298             :                                  gai_strerror(ret))));
    4299        6794 :     if (remote_port[0] == '\0')
    4300        6414 :         snprintf(remote_ps_data, sizeof(remote_ps_data), "%s", remote_host);
    4301             :     else
    4302         380 :         snprintf(remote_ps_data, sizeof(remote_ps_data), "%s(%s)", remote_host, remote_port);
    4303             : 
    4304             :     /*
    4305             :      * Save remote_host and remote_port in port structure (after this, they
    4306             :      * will appear in log_line_prefix data for log messages).
    4307             :      */
    4308        6794 :     port->remote_host = strdup(remote_host);
    4309        6794 :     port->remote_port = strdup(remote_port);
    4310             : 
    4311             :     /* And now we can issue the Log_connections message, if wanted */
    4312        6794 :     if (Log_connections)
    4313             :     {
    4314         104 :         if (remote_port[0])
    4315          84 :             ereport(LOG,
    4316             :                     (errmsg("connection received: host=%s port=%s",
    4317             :                             remote_host,
    4318             :                             remote_port)));
    4319             :         else
    4320          20 :             ereport(LOG,
    4321             :                     (errmsg("connection received: host=%s",
    4322             :                             remote_host)));
    4323             :     }
    4324             : 
    4325             :     /*
    4326             :      * If we did a reverse lookup to name, we might as well save the results
    4327             :      * rather than possibly repeating the lookup during authentication.
    4328             :      *
    4329             :      * Note that we don't want to specify NI_NAMEREQD above, because then we'd
    4330             :      * get nothing useful for a client without an rDNS entry.  Therefore, we
    4331             :      * must check whether we got a numeric IPv4 or IPv6 address, and not save
    4332             :      * it into remote_hostname if so.  (This test is conservative and might
    4333             :      * sometimes classify a hostname as numeric, but an error in that
    4334             :      * direction is safe; it only results in a possible extra lookup.)
    4335             :      */
    4336        6794 :     if (log_hostname &&
    4337          84 :         ret == 0 &&
    4338         168 :         strspn(remote_host, "0123456789.") < strlen(remote_host) &&
    4339          84 :         strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
    4340          84 :         port->remote_hostname = strdup(remote_host);
    4341             : 
    4342             :     /*
    4343             :      * Ready to begin client interaction.  We will give up and exit(1) after a
    4344             :      * time delay, so that a broken client can't hog a connection
    4345             :      * indefinitely.  PreAuthDelay and any DNS interactions above don't count
    4346             :      * against the time limit.
    4347             :      *
    4348             :      * Note: AuthenticationTimeout is applied here while waiting for the
    4349             :      * startup packet, and then again in InitPostgres for the duration of any
    4350             :      * authentication operations.  So a hostile client could tie up the
    4351             :      * process for nearly twice AuthenticationTimeout before we kick him off.
    4352             :      *
    4353             :      * Note: because PostgresMain will call InitializeTimeouts again, the
    4354             :      * registration of STARTUP_PACKET_TIMEOUT will be lost.  This is okay
    4355             :      * since we never use it again after this function.
    4356             :      */
    4357        6794 :     RegisterTimeout(STARTUP_PACKET_TIMEOUT, StartupPacketTimeoutHandler);
    4358        6794 :     enable_timeout_after(STARTUP_PACKET_TIMEOUT, AuthenticationTimeout * 1000);
    4359             : 
    4360             :     /*
    4361             :      * Receive the startup packet (which might turn out to be a cancel request
    4362             :      * packet).
    4363             :      */
    4364        6794 :     status = ProcessStartupPacket(port, false);
    4365             : 
    4366             :     /*
    4367             :      * Stop here if it was bad or a cancel packet.  ProcessStartupPacket
    4368             :      * already did any appropriate error reporting.
    4369             :      */
    4370        6754 :     if (status != STATUS_OK)
    4371          34 :         proc_exit(0);
    4372             : 
    4373             :     /*
    4374             :      * Now that we have the user and database name, we can set the process
    4375             :      * title for ps.  It's good to do this as early as possible in startup.
    4376             :      *
    4377             :      * For a walsender, the ps display is set in the following form:
    4378             :      *
    4379             :      * postgres: walsender <user> <host> <activity>
    4380             :      *
    4381             :      * To achieve that, we pass "walsender" as username and username as dbname
    4382             :      * to init_ps_display(). XXX: should add a new variant of
    4383             :      * init_ps_display() to avoid abusing the parameters like this.
    4384             :      */
    4385        6720 :     if (am_walsender)
    4386         462 :         init_ps_display(pgstat_get_backend_desc(B_WAL_SENDER), port->user_name, remote_ps_data,
    4387         462 :                         update_process_title ? "authentication" : "");
    4388             :     else
    4389        6258 :         init_ps_display(port->user_name, port->database_name, remote_ps_data,
    4390        6258 :                         update_process_title ? "authentication" : "");
    4391             : 
    4392             :     /*
    4393             :      * Disable the timeout, and prevent SIGTERM/SIGQUIT again.
    4394             :      */
    4395        6720 :     disable_timeout(STARTUP_PACKET_TIMEOUT, false);
    4396        6720 :     PG_SETMASK(&BlockSig);
    4397        6720 : }
    4398             : 
    4399             : 
    4400             : /*
    4401             :  * BackendRun -- set up the backend's argument list and invoke PostgresMain()
    4402             :  *
    4403             :  * returns:
    4404             :  *      Shouldn't return at all.
    4405             :  *      If PostgresMain() fails, return status.
    4406             :  */
    4407             : static void
    4408        6720 : BackendRun(Port *port)
    4409             : {
    4410             :     char      **av;
    4411             :     int         maxac;
    4412             :     int         ac;
    4413             :     int         i;
    4414             : 
    4415             :     /*
    4416             :      * Now, build the argv vector that will be given to PostgresMain.
    4417             :      *
    4418             :      * The maximum possible number of commandline arguments that could come
    4419             :      * from ExtraOptions is (strlen(ExtraOptions) + 1) / 2; see
    4420             :      * pg_split_opts().
    4421             :      */
    4422        6720 :     maxac = 2;                  /* for fixed args supplied below */
    4423        6720 :     maxac += (strlen(ExtraOptions) + 1) / 2;
    4424             : 
    4425        6720 :     av = (char **) MemoryContextAlloc(TopMemoryContext,
    4426             :                                       maxac * sizeof(char *));
    4427        6720 :     ac = 0;
    4428             : 
    4429        6720 :     av[ac++] = "postgres";
    4430             : 
    4431             :     /*
    4432             :      * Pass any backend switches specified with -o on the postmaster's own
    4433             :      * command line.  We assume these are secure.
    4434             :      */
    4435        6720 :     pg_split_opts(av, &ac, ExtraOptions);
    4436             : 
    4437        6720 :     av[ac] = NULL;
    4438             : 
    4439             :     Assert(ac < maxac);
    4440             : 
    4441             :     /*
    4442             :      * Debug: print arguments being passed to backend
    4443             :      */
    4444        6720 :     ereport(DEBUG3,
    4445             :             (errmsg_internal("%s child[%d]: starting with (",
    4446             :                              progname, (int) getpid())));
    4447       13440 :     for (i = 0; i < ac; ++i)
    4448        6720 :         ereport(DEBUG3,
    4449             :                 (errmsg_internal("\t%s", av[i])));
    4450        6720 :     ereport(DEBUG3,
    4451             :             (errmsg_internal(")")));
    4452             : 
    4453             :     /*
    4454             :      * Make sure we aren't in PostmasterContext anymore.  (We can't delete it
    4455             :      * just yet, though, because InitPostgres will need the HBA data.)
    4456             :      */
    4457        6720 :     MemoryContextSwitchTo(TopMemoryContext);
    4458             : 
    4459        6720 :     PostgresMain(ac, av, port->database_name, port->user_name);
    4460             : }
    4461             : 
    4462             : 
    4463             : #ifdef EXEC_BACKEND
    4464             : 
    4465             : /*
    4466             :  * postmaster_forkexec -- fork and exec a postmaster subprocess
    4467             :  *
    4468             :  * The caller must have set up the argv array already, except for argv[2]
    4469             :  * which will be filled with the name of the temp variable file.
    4470             :  *
    4471             :  * Returns the child process PID, or -1 on fork failure (a suitable error
    4472             :  * message has been logged on failure).
    4473             :  *
    4474             :  * All uses of this routine will dispatch to SubPostmasterMain in the
    4475             :  * child process.
    4476             :  */
    4477             : pid_t
    4478             : postmaster_forkexec(int argc, char *argv[])
    4479             : {
    4480             :     Port        port;
    4481             : 
    4482             :     /* This entry point passes dummy values for the Port variables */
    4483             :     memset(&port, 0, sizeof(port));
    4484             :     return internal_forkexec(argc, argv, &port);
    4485             : }
    4486             : 
    4487             : /*
    4488             :  * backend_forkexec -- fork/exec off a backend process
    4489             :  *
    4490             :  * Some operating systems (WIN32) don't have fork() so we have to simulate
    4491             :  * it by storing parameters that need to be passed to the child and
    4492             :  * then create a new child process.
    4493             :  *
    4494             :  * returns the pid of the fork/exec'd process, or -1 on failure
    4495             :  */
    4496             : static pid_t
    4497             : backend_forkexec(Port *port)
    4498             : {
    4499             :     char       *av[4];
    4500             :     int         ac = 0;
    4501             : 
    4502             :     av[ac++] = "postgres";
    4503             :     av[ac++] = "--forkbackend";
    4504             :     av[ac++] = NULL;            /* filled in by internal_forkexec */
    4505             : 
    4506             :     av[ac] = NULL;
    4507             :     Assert(ac < lengthof(av));
    4508             : 
    4509             :     return internal_forkexec(ac, av, port);
    4510             : }
    4511             : 
    4512             : #ifndef WIN32
    4513             : 
    4514             : /*
    4515             :  * internal_forkexec non-win32 implementation
    4516             :  *
    4517             :  * - writes out backend variables to the parameter file
    4518             :  * - fork():s, and then exec():s the child process
    4519             :  */
    4520             : static pid_t
    4521             : internal_forkexec(int argc, char *argv[], Port *port)
    4522             : {
    4523             :     static unsigned long tmpBackendFileNum = 0;
    4524             :     pid_t       pid;
    4525             :     char        tmpfilename[MAXPGPATH];
    4526             :     BackendParameters param;
    4527             :     FILE       *fp;
    4528             : 
    4529             :     if (!save_backend_variables(&param, port))
    4530             :         return -1;              /* log made by save_backend_variables */
    4531             : 
    4532             :     /* Calculate name for temp file */
    4533             :     snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
    4534             :              PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
    4535             :              MyProcPid, ++tmpBackendFileNum);
    4536             : 
    4537             :     /* Open file */
    4538             :     fp = AllocateFile(tmpfilename, PG_BINARY_W);
    4539             :     if (!fp)
    4540             :     {
    4541             :         /*
    4542             :          * As in OpenTemporaryFileInTablespace, try to make the temp-file
    4543             :          * directory, ignoring errors.
    4544             :          */
    4545             :         (void) MakePGDirectory(PG_TEMP_FILES_DIR);
    4546             : 
    4547             :         fp = AllocateFile(tmpfilename, PG_BINARY_W);
    4548             :         if (!fp)
    4549             :         {
    4550             :             ereport(LOG,
    4551             :                     (errcode_for_file_access(),
    4552             :                      errmsg("could not create file \"%s\": %m",
    4553             :                             tmpfilename)));
    4554             :             return -1;
    4555             :         }
    4556             :     }
    4557             : 
    4558             :     if (fwrite(&param, sizeof(param), 1, fp) != 1)
    4559             :     {
    4560             :         ereport(LOG,
    4561             :                 (errcode_for_file_access(),
    4562             :                  errmsg("could not write to file \"%s\": %m", tmpfilename)));
    4563             :         FreeFile(fp);
    4564             :         return -1;
    4565             :     }
    4566             : 
    4567             :     /* Release file */
    4568             :     if (FreeFile(fp))
    4569             :     {
    4570             :         ereport(LOG,
    4571             :                 (errcode_for_file_access(),
    4572             :                  errmsg("could not write to file \"%s\": %m", tmpfilename)));
    4573             :         return -1;
    4574             :     }
    4575             : 
    4576             :     /* Make sure caller set up argv properly */
    4577             :     Assert(argc >= 3);
    4578             :     Assert(argv[argc] == NULL);
    4579             :     Assert(strncmp(argv[1], "--fork", 6) == 0);
    4580             :     Assert(argv[2] == NULL);
    4581             : 
    4582             :     /* Insert temp file name after --fork argument */
    4583             :     argv[2] = tmpfilename;
    4584             : 
    4585             :     /* Fire off execv in child */
    4586             :     if ((pid = fork_process()) == 0)
    4587             :     {
    4588             :         if (execv(postgres_exec_path, argv) < 0)
    4589             :         {
    4590             :             ereport(LOG,
    4591             :                     (errmsg("could not execute server process \"%s\": %m",
    4592             :                             postgres_exec_path)));
    4593             :             /* We're already in the child process here, can't return */
    4594             :             exit(1);
    4595             :         }
    4596             :     }
    4597             : 
    4598             :     return pid;                 /* Parent returns pid, or -1 on fork failure */
    4599             : }
    4600             : #else                           /* WIN32 */
    4601             : 
    4602             : /*
    4603             :  * internal_forkexec win32 implementation
    4604             :  *
    4605             :  * - starts backend using CreateProcess(), in suspended state
    4606             :  * - writes out backend variables to the parameter file
    4607             :  *  - during this, duplicates handles and sockets required for
    4608             :  *    inheritance into the new process
    4609             :  * - resumes execution of the new process once the backend parameter
    4610             :  *   file is complete.
    4611             :  */
    4612             : static pid_t
    4613             : internal_forkexec(int argc, char *argv[], Port *port)
    4614             : {
    4615             :     int         retry_count = 0;
    4616             :     STARTUPINFO si;
    4617             :     PROCESS_INFORMATION pi;
    4618             :     int         i;
    4619             :     int         j;
    4620             :     char        cmdLine[MAXPGPATH * 2];
    4621             :     HANDLE      paramHandle;
    4622             :     BackendParameters *param;
    4623             :     SECURITY_ATTRIBUTES sa;
    4624             :     char        paramHandleStr[32];
    4625             :     win32_deadchild_waitinfo *childinfo;
    4626             : 
    4627             :     /* Make sure caller set up argv properly */
    4628             :     Assert(argc >= 3);
    4629             :     Assert(argv[argc] == NULL);
    4630             :     Assert(strncmp(argv[1], "--fork", 6) == 0);
    4631             :     Assert(argv[2] == NULL);
    4632             : 
    4633             :     /* Resume here if we need to retry */
    4634             : retry:
    4635             : 
    4636             :     /* Set up shared memory for parameter passing */
    4637             :     ZeroMemory(&sa, sizeof(sa));
    4638             :     sa.nLength = sizeof(sa);
    4639             :     sa.bInheritHandle = TRUE;
    4640             :     paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
    4641             :                                     &sa,
    4642             :                                     PAGE_READWRITE,
    4643             :                                     0,
    4644             :                                     sizeof(BackendParameters),
    4645             :                                     NULL);
    4646             :     if (paramHandle == INVALID_HANDLE_VALUE)
    4647             :     {
    4648             :         elog(LOG, "could not create backend parameter file mapping: error code %lu",
    4649             :              GetLastError());
    4650             :         return -1;
    4651             :     }
    4652             : 
    4653             :     param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
    4654             :     if (!param)
    4655             :     {
    4656             :         elog(LOG, "could not map backend parameter memory: error code %lu",
    4657             :              GetLastError());
    4658             :         CloseHandle(paramHandle);
    4659             :         return -1;
    4660             :     }
    4661             : 
    4662             :     /* Insert temp file name after --fork argument */
    4663             : #ifdef _WIN64
    4664             :     sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
    4665             : #else
    4666             :     sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
    4667             : #endif
    4668             :     argv[2] = paramHandleStr;
    4669             : 
    4670             :     /* Format the cmd line */
    4671             :     cmdLine[sizeof(cmdLine) - 1] = '\0';
    4672             :     cmdLine[sizeof(cmdLine) - 2] = '\0';
    4673             :     snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
    4674             :     i = 0;
    4675             :     while (argv[++i] != NULL)
    4676             :     {
    4677             :         j = strlen(cmdLine);
    4678             :         snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
    4679             :     }
    4680             :     if (cmdLine[sizeof(cmdLine) - 2] != '\0')
    4681             :     {
    4682             :         elog(LOG, "subprocess command line too long");
    4683             :         return -1;
    4684             :     }
    4685             : 
    4686             :     memset(&pi, 0, sizeof(pi));
    4687             :     memset(&si, 0, sizeof(si));
    4688             :     si.cb = sizeof(si);
    4689             : 
    4690             :     /*
    4691             :      * Create the subprocess in a suspended state. This will be resumed later,
    4692             :      * once we have written out the parameter file.
    4693             :      */
    4694             :     if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
    4695             :                        NULL, NULL, &si, &pi))
    4696             :     {
    4697             :         elog(LOG, "CreateProcess call failed: %m (error code %lu)",
    4698             :              GetLastError());
    4699             :         return -1;
    4700             :     }
    4701             : 
    4702             :     if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
    4703             :     {
    4704             :         /*
    4705             :          * log made by save_backend_variables, but we have to clean up the
    4706             :          * mess with the half-started process
    4707             :          */
    4708             :         if (!TerminateProcess(pi.hProcess, 255))
    4709             :             ereport(LOG,
    4710             :                     (errmsg_internal("could not terminate unstarted process: error code %lu",
    4711             :                                      GetLastError())));
    4712             :         CloseHandle(pi.hProcess);
    4713             :         CloseHandle(pi.hThread);
    4714             :         return -1;              /* log made by save_backend_variables */
    4715             :     }
    4716             : 
    4717             :     /* Drop the parameter shared memory that is now inherited to the backend */
    4718             :     if (!UnmapViewOfFile(param))
    4719             :         elog(LOG, "could not unmap view of backend parameter file: error code %lu",
    4720             :              GetLastError());
    4721             :     if (!CloseHandle(paramHandle))
    4722             :         elog(LOG, "could not close handle to backend parameter file: error code %lu",
    4723             :              GetLastError());
    4724             : 
    4725             :     /*
    4726             :      * Reserve the memory region used by our main shared memory segment before
    4727             :      * we resume the child process.  Normally this should succeed, but if ASLR
    4728             :      * is active then it might sometimes fail due to the stack or heap having
    4729             :      * gotten mapped into that range.  In that case, just terminate the
    4730             :      * process and retry.
    4731             :      */
    4732             :     if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
    4733             :     {
    4734             :         /* pgwin32_ReserveSharedMemoryRegion already made a log entry */
    4735             :         if (!TerminateProcess(pi.hProcess, 255))
    4736             :             ereport(LOG,
    4737             :                     (errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
    4738             :                                      GetLastError())));
    4739             :         CloseHandle(pi.hProcess);
    4740             :         CloseHandle(pi.hThread);
    4741             :         if (++retry_count < 100)
    4742             :             goto retry;
    4743             :         ereport(LOG,
    4744             :                 (errmsg("giving up after too many tries to reserve shared memory"),
    4745             :                  errhint("This might be caused by ASLR or antivirus software.")));
    4746             :         return -1;
    4747             :     }
    4748             : 
    4749             :     /*
    4750             :      * Now that the backend variables are written out, we start the child
    4751             :      * thread so it can start initializing while we set up the rest of the
    4752             :      * parent state.
    4753             :      */
    4754             :     if (ResumeThread(pi.hThread) == -1)
    4755             :     {
    4756             :         if (!TerminateProcess(pi.hProcess, 255))
    4757             :         {
    4758             :             ereport(LOG,
    4759             :                     (errmsg_internal("could not terminate unstartable process: error code %lu",
    4760             :                                      GetLastError())));
    4761             :             CloseHandle(pi.hProcess);
    4762             :             CloseHandle(pi.hThread);
    4763             :             return -1;
    4764             :         }
    4765             :         CloseHandle(pi.hProcess);
    4766             :         CloseHandle(pi.hThread);
    4767             :         ereport(LOG,
    4768             :                 (errmsg_internal("could not resume thread of unstarted process: error code %lu",
    4769             :                                  GetLastError())));
    4770             :         return -1;
    4771             :     }
    4772             : 
    4773             :     /*
    4774             :      * Queue a waiter to signal when this child dies. The wait will be handled
    4775             :      * automatically by an operating system thread pool.
    4776             :      *
    4777             :      * Note: use malloc instead of palloc, since it needs to be thread-safe.
    4778             :      * Struct will be free():d from the callback function that runs on a
    4779             :      * different thread.
    4780             :      */
    4781             :     childinfo = malloc(sizeof(win32_deadchild_waitinfo));
    4782             :     if (!childinfo)
    4783             :         ereport(FATAL,
    4784             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    4785             :                  errmsg("out of memory")));
    4786             : 
    4787             :     childinfo->procHandle = pi.hProcess;
    4788             :     childinfo->procId = pi.dwProcessId;
    4789             : 
    4790             :     if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
    4791             :                                      pi.hProcess,
    4792             :                                      pgwin32_deadchild_callback,
    4793             :                                      childinfo,
    4794             :                                      INFINITE,
    4795             :                                      WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
    4796             :         ereport(FATAL,
    4797             :                 (errmsg_internal("could not register process for wait: error code %lu",
    4798             :                                  GetLastError())));
    4799             : 
    4800             :     /* Don't close pi.hProcess here - the wait thread needs access to it */
    4801             : 
    4802             :     CloseHandle(pi.hThread);
    4803             : 
    4804             :     return pi.dwProcessId;
    4805             : }
    4806             : #endif                          /* WIN32 */
    4807             : 
    4808             : 
    4809             : /*
    4810             :  * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
    4811             :  *          to what it would be if we'd simply forked on Unix, and then
    4812             :  *          dispatch to the appropriate place.
    4813             :  *
    4814             :  * The first two command line arguments are expected to be "--forkFOO"
    4815             :  * (where FOO indicates which postmaster child we are to become), and
    4816             :  * the name of a variables file that we can read to load data that would
    4817             :  * have been inherited by fork() on Unix.  Remaining arguments go to the
    4818             :  * subprocess FooMain() routine.
    4819             :  */
    4820             : void
    4821             : SubPostmasterMain(int argc, char *argv[])
    4822             : {
    4823             :     Port        port;
    4824             : 
    4825             :     /* In EXEC_BACKEND case we will not have inherited these settings */
    4826             :     IsPostmasterEnvironment = true;
    4827             :     whereToSendOutput = DestNone;
    4828             : 
    4829             :     /* Setup as postmaster child */
    4830             :     InitPostmasterChild();
    4831             : 
    4832             :     /* Setup essential subsystems (to ensure elog() behaves sanely) */
    4833             :     InitializeGUCOptions();
    4834             : 
    4835             :     /* Check we got appropriate args */
    4836             :     if (argc < 3)
    4837             :         elog(FATAL, "invalid subpostmaster invocation");
    4838             : 
    4839             :     /* Read in the variables file */
    4840             :     memset(&port, 0, sizeof(Port));
    4841             :     read_backend_variables(argv[2], &port);
    4842             : 
    4843             :     /* Close the postmaster's sockets (as soon as we know them) */
    4844             :     ClosePostmasterPorts(strcmp(argv[1], "--forklog") == 0);
    4845             : 
    4846             :     /*
    4847             :      * Set reference point for stack-depth checking
    4848             :      */
    4849             :     set_stack_base();
    4850             : 
    4851             :     /*
    4852             :      * Set up memory area for GSS information. Mirrors the code in ConnCreate
    4853             :      * for the non-exec case.
    4854             :      */
    4855             : #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
    4856             :     port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
    4857             :     if (!port.gss)
    4858             :         ereport(FATAL,
    4859             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    4860             :                  errmsg("out of memory")));
    4861             : #endif
    4862             : 
    4863             :     /*
    4864             :      * If appropriate, physically re-attach to shared memory segment. We want
    4865             :      * to do this before going any further to ensure that we can attach at the
    4866             :      * same address the postmaster used.  On the other hand, if we choose not
    4867             :      * to re-attach, we may have other cleanup to do.
    4868             :      *
    4869             :      * If testing EXEC_BACKEND on Linux, you should run this as root before
    4870             :      * starting the postmaster:
    4871             :      *
    4872             :      * echo 0 >/proc/sys/kernel/randomize_va_space
    4873             :      *
    4874             :      * This prevents using randomized stack and code addresses that cause the
    4875             :      * child process's memory map to be different from the parent's, making it
    4876             :      * sometimes impossible to attach to shared memory at the desired address.
    4877             :      * Return the setting to its old value (usually '1' or '2') when finished.
    4878             :      */
    4879             :     if (strcmp(argv[1], "--forkbackend") == 0 ||
    4880             :         strcmp(argv[1], "--forkavlauncher") == 0 ||
    4881             :         strcmp(argv[1], "--forkavworker") == 0 ||
    4882             :         strcmp(argv[1], "--forkboot") == 0 ||
    4883             :         strncmp(argv[1], "--forkbgworker=", 15) == 0)
    4884             :         PGSharedMemoryReAttach();
    4885             :     else
    4886             :         PGSharedMemoryNoReAttach();
    4887             : 
    4888             :     /* autovacuum needs this set before calling InitProcess */
    4889             :     if (strcmp(argv[1], "--forkavlauncher") == 0)
    4890             :         AutovacuumLauncherIAm();
    4891             :     if (strcmp(argv[1], "--forkavworker") == 0)
    4892             :         AutovacuumWorkerIAm();
    4893             : 
    4894             :     /*
    4895             :      * Start our win32 signal implementation. This has to be done after we
    4896             :      * read the backend variables, because we need to pick up the signal pipe
    4897             :      * from the parent process.
    4898             :      */
    4899             : #ifdef WIN32
    4900             :     pgwin32_signal_initialize();
    4901             : #endif
    4902             : 
    4903             :     /* In EXEC_BACKEND case we will not have inherited these settings */
    4904             :     pqinitmask();
    4905             :     PG_SETMASK(&BlockSig);
    4906             : 
    4907             :     /* Read in remaining GUC variables */
    4908             :     read_nondefault_variables();
    4909             : 
    4910             :     /*
    4911             :      * Check that the data directory looks valid, which will also check the
    4912             :      * privileges on the data directory and update our umask and file/group
    4913             :      * variables for creating files later.  Note: this should really be done
    4914             :      * before we create any files or directories.
    4915             :      */
    4916             :     checkDataDir();
    4917             : 
    4918             :     /*
    4919             :      * (re-)read control file, as it contains config. The postmaster will
    4920             :      * already have read this, but this process doesn't know about that.
    4921             :      */
    4922             :     LocalProcessControlFile(false);
    4923             : 
    4924             :     /*
    4925             :      * Reload any libraries that were preloaded by the postmaster.  Since we
    4926             :      * exec'd this process, those libraries didn't come along with us; but we
    4927             :      * should load them into all child processes to be consistent with the
    4928             :      * non-EXEC_BACKEND behavior.
    4929             :      */
    4930             :     process_shared_preload_libraries();
    4931             : 
    4932             :     /* Run backend or appropriate child */
    4933             :     if (strcmp(argv[1], "--forkbackend") == 0)
    4934             :     {
    4935             :         Assert(argc == 3);      /* shouldn't be any more args */
    4936             : 
    4937             :         /*
    4938             :          * Need to reinitialize the SSL library in the backend, since the
    4939             :          * context structures contain function pointers and cannot be passed
    4940             :          * through the parameter file.
    4941             :          *
    4942             :          * If for some reason reload fails (maybe the user installed broken
    4943             :          * key files), soldier on without SSL; that's better than all
    4944             :          * connections becoming impossible.
    4945             :          *
    4946             :          * XXX should we do this in all child processes?  For the moment it's
    4947             :          * enough to do it in backend children.
    4948             :          */
    4949             : #ifdef USE_SSL
    4950             :         if (EnableSSL)
    4951             :         {
    4952             :             if (secure_initialize(false) == 0)
    4953             :                 LoadedSSL = true;
    4954             :             else
    4955             :                 ereport(LOG,
    4956             :                         (errmsg("SSL configuration could not be loaded in child process")));
    4957             :         }
    4958             : #endif
    4959             : 
    4960             :         /*
    4961             :          * Perform additional initialization and collect startup packet.
    4962             :          *
    4963             :          * We want to do this before InitProcess() for a couple of reasons: 1.
    4964             :          * so that we aren't eating up a PGPROC slot while waiting on the
    4965             :          * client. 2. so that if InitProcess() fails due to being out of
    4966             :          * PGPROC slots, we have already initialized libpq and are able to
    4967             :          * report the error to the client.
    4968             :          */
    4969             :         BackendInitialize(&port);
    4970             : 
    4971             :         /* Restore basic shared memory pointers */
    4972             :         InitShmemAccess(UsedShmemSegAddr);
    4973             : 
    4974             :         /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
    4975             :         InitProcess();
    4976             : 
    4977             :         /* Attach process to shared data structures */
    4978             :         CreateSharedMemoryAndSemaphores();
    4979             : 
    4980             :         /* And run the backend */
    4981             :         BackendRun(&port);      /* does not return */
    4982             :     }
    4983             :     if (strcmp(argv[1], "--forkboot") == 0)
    4984             :     {
    4985             :         /* Restore basic shared memory pointers */
    4986             :         InitShmemAccess(UsedShmemSegAddr);
    4987             : 
    4988             :         /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
    4989             :         InitAuxiliaryProcess();
    4990             : 
    4991             :         /* Attach process to shared data structures */
    4992             :         CreateSharedMemoryAndSemaphores();
    4993             : 
    4994             :         AuxiliaryProcessMain(argc - 2, argv + 2);   /* does not return */
    4995             :     }
    4996             :     if (strcmp(argv[1], "--forkavlauncher") == 0)
    4997             :     {
    4998             :         /* Restore basic shared memory pointers */
    4999             :         InitShmemAccess(UsedShmemSegAddr);
    5000             : 
    5001             :         /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
    5002             :         InitProcess();
    5003             : 
    5004             :         /* Attach process to shared data structures */
    5005             :         CreateSharedMemoryAndSemaphores();
    5006             : 
    5007             :         AutoVacLauncherMain(argc - 2, argv + 2);    /* does not return */
    5008             :     }
    5009             :     if (strcmp(argv[1], "--forkavworker") == 0)
    5010             :     {
    5011             :         /* Restore basic shared memory pointers */
    5012             :         InitShmemAccess(UsedShmemSegAddr);
    5013             : 
    5014             :         /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
    5015             :         InitProcess();
    5016             : 
    5017             :         /* Attach process to shared data structures */
    5018             :         CreateSharedMemoryAndSemaphores();
    5019             : 
    5020             :         AutoVacWorkerMain(argc - 2, argv + 2);  /* does not return */
    5021             :     }
    5022             :     if (strncmp(argv[1], "--forkbgworker=", 15) == 0)
    5023             :     {
    5024             :         int         shmem_slot;
    5025             : 
    5026             :         /* do this as early as possible; in particular, before InitProcess() */
    5027             :         IsBackgroundWorker = true;
    5028             : 
    5029             :         /* Restore basic shared memory pointers */
    5030             :         InitShmemAccess(UsedShmemSegAddr);
    5031             : 
    5032             :         /* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
    5033             :         InitProcess();
    5034             : 
    5035             :         /* Attach process to shared data structures */
    5036             :         CreateSharedMemoryAndSemaphores();
    5037             : 
    5038             :         /* Fetch MyBgworkerEntry from shared memory */
    5039             :         shmem_slot = atoi(argv[1] + 15);
    5040             :         MyBgworkerEntry = BackgroundWorkerEntry(shmem_slot);
    5041             : 
    5042             :         StartBackgroundWorker();
    5043             :     }
    5044             :     if (strcmp(argv[1], "--forkarch") == 0)
    5045             :     {
    5046             :         /* Do not want to attach to shared memory */
    5047             : 
    5048             :         PgArchiverMain(argc, argv); /* does not return */
    5049             :     }
    5050             :     if (strcmp(argv[1], "--forkcol") == 0)
    5051             :     {
    5052             :         /* Do not want to attach to shared memory */
    5053             : 
    5054             :         PgstatCollectorMain(argc, argv);    /* does not return */
    5055             :     }
    5056             :     if (strcmp(argv[1], "--forklog") == 0)
    5057             :     {
    5058             :         /* Do not want to attach to shared memory */
    5059             : 
    5060             :         SysLoggerMain(argc, argv);  /* does not return */
    5061             :     }
    5062             : 
    5063             :     abort();                    /* shouldn't get here */
    5064             : }
    5065             : #endif                          /* EXEC_BACKEND */
    5066             : 
    5067             : 
    5068             : /*
    5069             :  * ExitPostmaster -- cleanup
    5070             :  *
    5071             :  * Do NOT call exit() directly --- always go through here!
    5072             :  */
    5073             : static void
    5074         566 : ExitPostmaster(int status)
    5075             : {
    5076             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
    5077             : 
    5078             :     /*
    5079             :      * There is no known cause for a postmaster to become multithreaded after
    5080             :      * startup.  Recheck to account for the possibility of unknown causes.
    5081             :      * This message uses LOG level, because an unclean shutdown at this point
    5082             :      * would usually not look much different from a clean shutdown.
    5083             :      */
    5084             :     if (pthread_is_threaded_np() != 0)
    5085             :         ereport(LOG,
    5086             :                 (errcode(ERRCODE_INTERNAL_ERROR),
    5087             :                  errmsg_internal("postmaster became multithreaded"),
    5088             :                  errdetail("Please report this to <pgsql-bugs@lists.postgresql.org>.")));
    5089             : #endif
    5090             : 
    5091             :     /* should cleanup shared memory and kill all backends */
    5092             : 
    5093             :     /*
    5094             :      * Not sure of the semantics here.  When the Postmaster dies, should the
    5095             :      * backends all be killed? probably not.
    5096             :      *
    5097             :      * MUST     -- vadim 05-10-1999
    5098             :      */
    5099             : 
    5100         566 :     proc_exit(status);
    5101             : }
    5102             : 
    5103             : /*
    5104             :  * sigusr1_handler - handle signal conditions from child processes
    5105             :  */
    5106             : static void
    5107        1828 : sigusr1_handler(SIGNAL_ARGS)
    5108             : {
    5109        1828 :     int         save_errno = errno;
    5110             : 
    5111        1828 :     PG_SETMASK(&BlockSig);
    5112             : 
    5113             :     /* Process background worker state change. */
    5114        1828 :     if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE))
    5115             :     {
    5116         840 :         BackgroundWorkerStateChange();
    5117         840 :         StartWorkerNeeded = true;
    5118             :     }
    5119             : 
    5120             :     /*
    5121             :      * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
    5122             :      * unexpected states. If the startup process quickly starts up, completes
    5123             :      * recovery, exits, we might process the death of the startup process
    5124             :      * first. We don't want to go back to recovery in that case.
    5125             :      */
    5126        1948 :     if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
    5127         240 :         pmState == PM_STARTUP && Shutdown == NoShutdown)
    5128             :     {
    5129             :         /* WAL redo has started. We're out of reinitialization. */
    5130         120 :         FatalError = false;
    5131         120 :         AbortStartTime = 0;
    5132             : 
    5133             :         /*
    5134             :          * Crank up the background tasks.  It doesn't matter if this fails,
    5135             :          * we'll just try again later.
    5136             :          */
    5137             :         Assert(CheckpointerPID == 0);
    5138         120 :         CheckpointerPID = StartCheckpointer();
    5139             :         Assert(BgWriterPID == 0);
    5140         120 :         BgWriterPID = StartBackgroundWriter();
    5141             : 
    5142             :         /*
    5143             :          * Start the archiver if we're responsible for (re-)archiving received
    5144             :          * files.
    5145             :          */
    5146             :         Assert(PgArchPID == 0);
    5147         120 :         if (XLogArchivingAlways())
    5148           0 :             PgArchPID = pgarch_start();
    5149             : 
    5150             :         /*
    5151             :          * If we aren't planning to enter hot standby mode later, treat
    5152             :          * RECOVERY_STARTED as meaning we're out of startup, and report status
    5153             :          * accordingly.
    5154             :          */
    5155         120 :         if (!EnableHotStandby)
    5156             :         {
    5157           0 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STANDBY);
    5158             : #ifdef USE_SYSTEMD
    5159             :             sd_notify(0, "READY=1");
    5160             : #endif
    5161             :         }
    5162             : 
    5163         120 :         pmState = PM_RECOVERY;
    5164             :     }
    5165        1948 :     if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
    5166         240 :         pmState == PM_RECOVERY && Shutdown == NoShutdown)
    5167             :     {
    5168             :         /*
    5169             :          * Likewise, start other special children as needed.
    5170             :          */
    5171             :         Assert(PgStatPID == 0);
    5172         120 :         PgStatPID = pgstat_start();
    5173             : 
    5174         120 :         ereport(LOG,
    5175             :                 (errmsg("database system is ready to accept read only connections")));
    5176             : 
    5177             :         /* Report status */
    5178         120 :         AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
    5179             : #ifdef USE_SYSTEMD
    5180             :         sd_notify(0, "READY=1");
    5181             : #endif
    5182             : 
    5183         120 :         pmState = PM_HOT_STANDBY;
    5184             :         /* Some workers may be scheduled to start now */
    5185         120 :         StartWorkerNeeded = true;
    5186             :     }
    5187             : 
    5188        1828 :     if (StartWorkerNeeded || HaveCrashedWorker)
    5189         962 :         maybe_start_bgworkers();
    5190             : 
    5191        1854 :     if (CheckPostmasterSignal(PMSIGNAL_WAKEN_ARCHIVER) &&
    5192          26 :         PgArchPID != 0)
    5193             :     {
    5194             :         /*
    5195             :          * Send SIGUSR1 to archiver process, to wake it up and begin archiving
    5196             :          * next WAL file.
    5197             :          */
    5198          22 :         signal_child(PgArchPID, SIGUSR1);
    5199             :     }
    5200             : 
    5201             :     /* Tell syslogger to rotate logfile if requested */
    5202        1828 :     if (SysLoggerPID != 0)
    5203             :     {
    5204           2 :         if (CheckLogrotateSignal())
    5205             :         {
    5206           2 :             signal_child(SysLoggerPID, SIGUSR1);
    5207           2 :             RemoveLogrotateSignalFiles();
    5208             :         }
    5209           0 :         else if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE))
    5210             :         {
    5211           0 :             signal_child(SysLoggerPID, SIGUSR1);
    5212             :         }
    5213             :     }
    5214             : 
    5215        1834 :     if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) &&
    5216           6 :         Shutdown == NoShutdown)
    5217             :     {
    5218             :         /*
    5219             :          * Start one iteration of the autovacuum daemon, even if autovacuuming
    5220             :          * is nominally not enabled.  This is so we can have an active defense
    5221             :          * against transaction ID wraparound.  We set a flag for the main loop
    5222             :          * to do it rather than trying to do it here --- this is because the
    5223             :          * autovac process itself may send the signal, and we want to handle
    5224             :          * that by launching another iteration as soon as the current one
    5225             :          * completes.
    5226             :          */
    5227           6 :         start_autovac_launcher = true;
    5228             :     }
    5229             : 
    5230        1890 :     if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) &&
    5231          62 :         Shutdown == NoShutdown)
    5232             :     {
    5233             :         /* The autovacuum launcher wants us to start a worker process. */
    5234          62 :         StartAutovacuumWorker();
    5235             :     }
    5236             : 
    5237        1828 :     if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER))
    5238             :     {
    5239             :         /* Startup Process wants us to start the walreceiver process. */
    5240             :         /* Start immediately if possible, else remember request for later. */
    5241         214 :         WalReceiverRequested = true;
    5242         214 :         MaybeStartWalReceiver();
    5243             :     }
    5244             : 
    5245             :     /*
    5246             :      * Try to advance postmaster's state machine, if a child requests it.
    5247             :      *
    5248             :      * Be careful about the order of this action relative to sigusr1_handler's
    5249             :      * other actions.  Generally, this should be after other actions, in case
    5250             :      * they have effects PostmasterStateMachine would need to know about.
    5251             :      * However, we should do it before the CheckPromoteSignal step, which
    5252             :      * cannot have any (immediate) effect on the state machine, but does
    5253             :      * depend on what state we're in now.
    5254             :      */
    5255        1828 :     if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE))
    5256             :     {
    5257         504 :         PostmasterStateMachine();
    5258             :     }
    5259             : 
    5260        2238 :     if (StartupPID != 0 &&
    5261        1202 :         (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
    5262         798 :          pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY) &&
    5263         406 :         CheckPromoteSignal())
    5264             :     {
    5265             :         /* Tell startup process to finish recovery */
    5266          46 :         signal_child(StartupPID, SIGUSR2);
    5267             :     }
    5268             : 
    5269        1828 :     PG_SETMASK(&UnBlockSig);
    5270             : 
    5271        1828 :     errno = save_errno;
    5272        1828 : }
    5273             : 
    5274             : /*
    5275             :  * SIGTERM or SIGQUIT while processing startup packet.
    5276             :  * Clean up and exit(1).
    5277             :  *
    5278             :  * XXX: possible future improvement: try to send a message indicating
    5279             :  * why we are disconnecting.  Problem is to be sure we don't block while
    5280             :  * doing so, nor mess up SSL initialization.  In practice, if the client
    5281             :  * has wedged here, it probably couldn't do anything with the message anyway.
    5282             :  */
    5283             : static void
    5284           2 : startup_die(SIGNAL_ARGS)
    5285             : {
    5286           2 :     proc_exit(1);
    5287             : }
    5288             : 
    5289             : /*
    5290             :  * Dummy signal handler
    5291             :  *
    5292             :  * We use this for signals that we don't actually use in the postmaster,
    5293             :  * but we do use in backends.  If we were to SIG_IGN such signals in the
    5294             :  * postmaster, then a newly started backend might drop a signal that arrives
    5295             :  * before it's able to reconfigure its signal processing.  (See notes in
    5296             :  * tcop/postgres.c.)
    5297             :  */
    5298             : static void
    5299           0 : dummy_handler(SIGNAL_ARGS)
    5300             : {
    5301           0 : }
    5302             : 
    5303             : /*
    5304             :  * Timeout while processing startup packet.
    5305             :  * As for startup_die(), we clean up and exit(1).
    5306             :  */
    5307             : static void
    5308           0 : StartupPacketTimeoutHandler(void)
    5309             : {
    5310           0 :     proc_exit(1);
    5311             : }
    5312             : 
    5313             : 
    5314             : /*
    5315             :  * Generate a random cancel key.
    5316             :  */
    5317             : static bool
    5318        9224 : RandomCancelKey(int32 *cancel_key)
    5319             : {
    5320        9224 :     return pg_strong_random(cancel_key, sizeof(int32));
    5321             : }
    5322             : 
    5323             : /*
    5324             :  * Count up number of child processes of specified types (dead_end children
    5325             :  * are always excluded).
    5326             :  */
    5327             : static int
    5328       10034 : CountChildren(int target)
    5329             : {
    5330             :     dlist_iter  iter;
    5331       10034 :     int         cnt = 0;
    5332             : 
    5333       31406 :     dlist_foreach(iter, &BackendList)
    5334             :     {
    5335       21372 :         Backend    *bp = dlist_container(Backend, elem, iter.cur);
    5336             : 
    5337       21372 :         if (bp->dead_end)
    5338           0 :             continue;
    5339             : 
    5340             :         /*
    5341             :          * Since target == BACKEND_TYPE_ALL is the most common case, we test
    5342             :          * it first and avoid touching shared memory for every child.
    5343             :          */
    5344       21372 :         if (target != BACKEND_TYPE_ALL)
    5345             :         {
    5346             :             /*
    5347             :              * Assign bkend_type for any recently announced WAL Sender
    5348             :              * processes.
    5349             :              */
    5350        2622 :             if (bp->bkend_type == BACKEND_TYPE_NORMAL &&
    5351         570 :                 IsPostmasterChildWalSender(bp->child_slot))
    5352          42 :                 bp->bkend_type = BACKEND_TYPE_WALSND;
    5353             : 
    5354        2052 :             if (!(target & bp->bkend_type))
    5355         242 :                 continue;
    5356             :         }
    5357             : 
    5358       21130 :         cnt++;
    5359             :     }
    5360       10034 :     return cnt;
    5361             : }
    5362             : 
    5363             : 
    5364             : /*
    5365             :  * StartChildProcess -- start an auxiliary process for the postmaster
    5366             :  *
    5367             :  * "type" determines what kind of child will be started.  All child types
    5368             :  * initially go to AuxiliaryProcessMain, which will handle common setup.
    5369             :  *
    5370             :  * Return value of StartChildProcess is subprocess' PID, or 0 if failed
    5371             :  * to start subprocess.
    5372             :  */
    5373             : static pid_t
    5374        2428 : StartChildProcess(AuxProcType type)
    5375             : {
    5376             :     pid_t       pid;
    5377             :     char       *av[10];
    5378        2428 :     int         ac = 0;
    5379             :     char        typebuf[32];
    5380             : 
    5381             :     /*
    5382             :      * Set up command-line arguments for subprocess
    5383             :      */
    5384        2428 :     av[ac++] = "postgres";
    5385             : 
    5386             : #ifdef EXEC_BACKEND
    5387             :     av[ac++] = "--forkboot";
    5388             :     av[ac++] = NULL;            /* filled in by postmaster_forkexec */
    5389             : #endif
    5390             : 
    5391        2428 :     snprintf(typebuf, sizeof(typebuf), "-x%d", type);
    5392        2428 :     av[ac++] = typebuf;
    5393             : 
    5394        2428 :     av[ac] = NULL;
    5395             :     Assert(ac < lengthof(av));
    5396             : 
    5397             : #ifdef EXEC_BACKEND
    5398             :     pid = postmaster_forkexec(ac, av);
    5399             : #else                           /* !EXEC_BACKEND */
    5400        2428 :     pid = fork_process();
    5401             : 
    5402        4250 :     if (pid == 0)               /* child */
    5403             :     {
    5404        1822 :         InitPostmasterChild();
    5405             : 
    5406             :         /* Close the postmaster's sockets */
    5407        1822 :         ClosePostmasterPorts(false);
    5408             : 
    5409             :         /* Release postmaster's working memory context */
    5410        1822 :         MemoryContextSwitchTo(TopMemoryContext);
    5411        1822 :         MemoryContextDelete(PostmasterContext);
    5412        1822 :         PostmasterContext = NULL;
    5413             : 
    5414        1822 :         AuxiliaryProcessMain(ac, av);
    5415             :         ExitPostmaster(0);
    5416             :     }
    5417             : #endif                          /* EXEC_BACKEND */
    5418             : 
    5419        2428 :     if (pid < 0)
    5420             :     {
    5421             :         /* in parent, fork failed */
    5422           0 :         int         save_errno = errno;
    5423             : 
    5424           0 :         errno = save_errno;
    5425           0 :         switch (type)
    5426             :         {
    5427             :             case StartupProcess:
    5428           0 :                 ereport(LOG,
    5429             :                         (errmsg("could not fork startup process: %m")));
    5430           0 :                 break;
    5431             :             case BgWriterProcess:
    5432           0 :                 ereport(LOG,
    5433             :                         (errmsg("could not fork background writer process: %m")));
    5434           0 :                 break;
    5435             :             case CheckpointerProcess:
    5436           0 :                 ereport(LOG,
    5437             :                         (errmsg("could not fork checkpointer process: %m")));
    5438           0 :                 break;
    5439             :             case WalWriterProcess:
    5440           0 :                 ereport(LOG,
    5441             :                         (errmsg("could not fork WAL writer process: %m")));
    5442           0 :                 break;
    5443             :             case WalReceiverProcess:
    5444           0 :                 ereport(LOG,
    5445             :                         (errmsg("could not fork WAL receiver process: %m")));
    5446           0 :                 break;
    5447             :             default:
    5448           0 :                 ereport(LOG,
    5449             :                         (errmsg("could not fork process: %m")));
    5450           0 :                 break;
    5451             :         }
    5452             : 
    5453             :         /*
    5454             :          * fork failure is fatal during startup, but there's no need to choke
    5455             :          * immediately if starting other child types fails.
    5456             :          */
    5457           0 :         if (type == StartupProcess)
    5458           0 :             ExitPostmaster(1);
    5459           0 :         return 0;
    5460             :     }
    5461             : 
    5462             :     /*
    5463             :      * in parent, successful fork
    5464             :      */
    5465        2428 :     return pid;
    5466             : }
    5467             : 
    5468             : /*
    5469             :  * StartAutovacuumWorker
    5470             :  *      Start an autovac worker process.
    5471             :  *
    5472             :  * This function is here because it enters the resulting PID into the
    5473             :  * postmaster's private backends list.
    5474             :  *
    5475             :  * NB -- this code very roughly matches BackendStartup.
    5476             :  */
    5477             : static void
    5478          62 : StartAutovacuumWorker(void)
    5479             : {
    5480             :     Backend    *bn;
    5481             : 
    5482             :     /*
    5483             :      * If not in condition to run a process, don't try, but handle it like a
    5484             :      * fork failure.  This does not normally happen, since the signal is only
    5485             :      * supposed to be sent by autovacuum launcher when it's OK to do it, but
    5486             :      * we have to check to avoid race-condition problems during DB state
    5487             :      * changes.
    5488             :      */
    5489          62 :     if (canAcceptConnections() == CAC_OK)
    5490             :     {
    5491             :         /*
    5492             :          * Compute the cancel key that will be assigned to this session. We
    5493             :          * probably don't need cancel keys for autovac workers, but we'd
    5494             :          * better have something random in the field to prevent unfriendly
    5495             :          * people from sending cancels to them.
    5496             :          */
    5497          62 :         if (!RandomCancelKey(&MyCancelKey))
    5498             :         {
    5499           0 :             ereport(LOG,
    5500             :                     (errcode(ERRCODE_INTERNAL_ERROR),
    5501             :                      errmsg("could not generate random cancel key")));
    5502           0 :             return;
    5503             :         }
    5504             : 
    5505          62 :         bn = (Backend *) malloc(sizeof(Backend));
    5506          62 :         if (bn)
    5507             :         {
    5508          62 :             bn->cancel_key = MyCancelKey;
    5509             : 
    5510             :             /* Autovac workers are not dead_end and need a child slot */
    5511          62 :             bn->dead_end = false;
    5512          62 :             bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
    5513          62 :             bn->bgworker_notify = false;
    5514             : 
    5515          62 :             bn->pid = StartAutoVacWorker();
    5516          62 :             if (bn->pid > 0)
    5517             :             {
    5518          62 :                 bn->bkend_type = BACKEND_TYPE_AUTOVAC;
    5519          62 :                 dlist_push_head(&BackendList, &bn->elem);
    5520             : #ifdef EXEC_BACKEND
    5521             :                 ShmemBackendArrayAdd(bn);
    5522             : #endif
    5523             :                 /* all OK */
    5524          62 :                 return;
    5525             :             }
    5526             : 
    5527             :             /*
    5528             :              * fork failed, fall through to report -- actual error message was
    5529             :              * logged by StartAutoVacWorker
    5530             :              */
    5531           0 :             (void) ReleasePostmasterChildSlot(bn->child_slot);
    5532           0 :             free(bn);
    5533             :         }
    5534             :         else
    5535           0 :             ereport(LOG,
    5536             :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    5537             :                      errmsg("out of memory")));
    5538             :     }
    5539             : 
    5540             :     /*
    5541             :      * Report the failure to the launcher, if it's running.  (If it's not, we
    5542             :      * might not even be connected to shared memory, so don't try to call
    5543             :      * AutoVacWorkerFailed.)  Note that we also need to signal it so that it
    5544             :      * responds to the condition, but we don't do that here, instead waiting
    5545             :      * for ServerLoop to do it.  This way we avoid a ping-pong signalling in
    5546             :      * quick succession between the autovac launcher and postmaster in case
    5547             :      * things get ugly.
    5548             :      */
    5549           0 :     if (AutoVacPID != 0)
    5550             :     {
    5551           0 :         AutoVacWorkerFailed();
    5552           0 :         avlauncher_needs_signal = true;
    5553             :     }
    5554             : }
    5555             : 
    5556             : /*
    5557             :  * MaybeStartWalReceiver
    5558             :  *      Start the WAL receiver process, if not running and our state allows.
    5559             :  *
    5560             :  * Note: if WalReceiverPID is already nonzero, it might seem that we should
    5561             :  * clear WalReceiverRequested.  However, there's a race condition if the
    5562             :  * walreceiver terminates and the startup process immediately requests a new
    5563             :  * one: it's quite possible to get the signal for the request before reaping
    5564             :  * the dead walreceiver process.  Better to risk launching an extra
    5565             :  * walreceiver than to miss launching one we need.  (The walreceiver code
    5566             :  * has logic to recognize that it should go away if not needed.)
    5567             :  */
    5568             : static void
    5569         402 : MaybeStartWalReceiver(void)
    5570             : {
    5571         644 :     if (WalReceiverPID == 0 &&
    5572         718 :         (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
    5573         476 :          pmState == PM_HOT_STANDBY || pmState == PM_WAIT_READONLY) &&
    5574         202 :         Shutdown == NoShutdown)
    5575             :     {
    5576         202 :         WalReceiverPID = StartWalReceiver();
    5577         202 :         if (WalReceiverPID != 0)
    5578         202 :             WalReceiverRequested = false;
    5579             :         /* else leave the flag set, so we'll try again later */
    5580             :     }
    5581         402 : }
    5582             : 
    5583             : 
    5584             : /*
    5585             :  * Create the opts file
    5586             :  */
    5587             : static bool
    5588         572 : CreateOptsFile(int argc, char *argv[], char *fullprogname)
    5589             : {
    5590             :     FILE       *fp;
    5591             :     int         i;
    5592             : 
    5593             : #define OPTS_FILE   "postmaster.opts"
    5594             : 
    5595         572 :     if ((fp = fopen(OPTS_FILE, "w")) == NULL)
    5596             :     {
    5597           0 :         elog(LOG, "could not create file \"%s\": %m", OPTS_FILE);
    5598           0 :         return false;
    5599             :     }
    5600             : 
    5601         572 :     fprintf(fp, "%s", fullprogname);
    5602        2892 :     for (i = 1; i < argc; i++)
    5603        2320 :         fprintf(fp, " \"%s\"", argv[i]);
    5604         572 :     fputs("\n", fp);
    5605             : 
    5606         572 :     if (fclose(fp))
    5607             :     {
    5608           0 :         elog(LOG, "could not write file \"%s\": %m", OPTS_FILE);
    5609           0 :         return false;
    5610             :     }
    5611             : 
    5612         572 :     return true;
    5613             : }
    5614             : 
    5615             : 
    5616             : /*
    5617             :  * MaxLivePostmasterChildren
    5618             :  *
    5619             :  * This reports the number of entries needed in per-child-process arrays
    5620             :  * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
    5621             :  * These arrays include regular backends, autovac workers, walsenders
    5622             :  * and background workers, but not special children nor dead_end children.
    5623             :  * This allows the arrays to have a fixed maximum size, to wit the same
    5624             :  * too-many-children limit enforced by canAcceptConnections().  The exact value
    5625             :  * isn't too critical as long as it's more than MaxBackends.
    5626             :  */
    5627             : int
    5628       14356 : MaxLivePostmasterChildren(void)
    5629             : {
    5630       28712 :     return 2 * (MaxConnections + autovacuum_max_workers + 1 +
    5631       14356 :                 max_wal_senders + max_worker_processes);
    5632             : }
    5633             : 
    5634             : /*
    5635             :  * Connect background worker to a database.
    5636             :  */
    5637             : void
    5638         364 : BackgroundWorkerInitializeConnection(const char *dbname, const char *username, uint32 flags)
    5639             : {
    5640         364 :     BackgroundWorker *worker = MyBgworkerEntry;
    5641             : 
    5642             :     /* XXX is this the right errcode? */
    5643         364 :     if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION))
    5644           0 :         ereport(FATAL,
    5645             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    5646             :                  errmsg("database connection requirement not indicated during registration")));
    5647             : 
    5648         364 :     InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
    5649             : 
    5650             :     /* it had better not gotten out of "init" mode yet */
    5651         360 :     if (!IsInitProcessingMode())
    5652           0 :         ereport(ERROR,
    5653             :                 (errmsg("invalid processing mode in background worker")));
    5654         360 :     SetProcessingMode(NormalProcessing);
    5655         360 : }
    5656             : 
    5657             : /*
    5658             :  * Connect background worker to a database using OIDs.
    5659             :  */
    5660             : void
    5661        1738 : BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
    5662             : {
    5663        1738 :     BackgroundWorker *worker = MyBgworkerEntry;
    5664             : 
    5665             :     /* XXX is this the right errcode? */
    5666        1738 :     if (!(worker->bgw_flags & BGWORKER_BACKEND_DATABASE_CONNECTION))
    5667           0 :         ereport(FATAL,
    5668             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    5669             :                  errmsg("database connection requirement not indicated during registration")));
    5670             : 
    5671        1738 :     InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
    5672             : 
    5673             :     /* it had better not gotten out of "init" mode yet */
    5674        1738 :     if (!IsInitProcessingMode())
    5675           0 :         ereport(ERROR,
    5676             :                 (errmsg("invalid processing mode in background worker")));
    5677        1738 :     SetProcessingMode(NormalProcessing);
    5678        1738 : }
    5679             : 
    5680             : /*
    5681             :  * Block/unblock signals in a background worker
    5682             :  */
    5683             : void
    5684           0 : BackgroundWorkerBlockSignals(void)
    5685             : {
    5686           0 :     PG_SETMASK(&BlockSig);
    5687           0 : }
    5688             : 
    5689             : void
    5690        2116 : BackgroundWorkerUnblockSignals(void)
    5691             : {
    5692        2116 :     PG_SETMASK(&UnBlockSig);
    5693        2116 : }
    5694             : 
    5695             : #ifdef EXEC_BACKEND
    5696             : static pid_t
    5697             : bgworker_forkexec(int shmem_slot)
    5698             : {
    5699             :     char       *av[10];
    5700             :     int         ac = 0;
    5701             :     char        forkav[MAXPGPATH];
    5702             : 
    5703             :     snprintf(forkav, MAXPGPATH, "--forkbgworker=%d", shmem_slot);
    5704             : 
    5705             :     av[ac++] = "postgres";
    5706             :     av[ac++] = forkav;
    5707             :     av[ac++] = NULL;            /* filled in by postmaster_forkexec */
    5708             :     av[ac] = NULL;
    5709             : 
    5710             :     Assert(ac < lengthof(av));
    5711             : 
    5712             :     return postmaster_forkexec(ac, av);
    5713             : }
    5714             : #endif
    5715             : 
    5716             : /*
    5717             :  * Start a new bgworker.
    5718             :  * Starting time conditions must have been checked already.
    5719             :  *
    5720             :  * Returns true on success, false on failure.
    5721             :  * In either case, update the RegisteredBgWorker's state appropriately.
    5722             :  *
    5723             :  * This code is heavily based on autovacuum.c, q.v.
    5724             :  */
    5725             : static bool
    5726        2256 : do_start_bgworker(RegisteredBgWorker *rw)
    5727             : {
    5728             :     pid_t       worker_pid;
    5729             : 
    5730             :     Assert(rw->rw_pid == 0);
    5731             : 
    5732             :     /*
    5733             :      * Allocate and assign the Backend element.  Note we must do this before
    5734             :      * forking, so that we can handle out of memory properly.
    5735             :      *
    5736             :      * Treat failure as though the worker had crashed.  That way, the
    5737             :      * postmaster will wait a bit before attempting to start it again; if it
    5738             :      * tried again right away, most likely it'd find itself repeating the
    5739             :      * out-of-memory or fork failure condition.
    5740             :      */
    5741        2256 :     if (!assign_backendlist_entry(rw))
    5742             :     {
    5743           0 :         rw->rw_crashed_at = GetCurrentTimestamp();
    5744           0 :         return false;
    5745             :     }
    5746             : 
    5747        2256 :     ereport(DEBUG1,
    5748             :             (errmsg("starting background worker process \"%s\"",
    5749             :                     rw->rw_worker.bgw_name)));
    5750             : 
    5751             : #ifdef EXEC_BACKEND
    5752             :     switch ((worker_pid = bgworker_forkexec(rw->rw_shmem_slot)))
    5753             : #else
    5754        2256 :     switch ((worker_pid = fork_process()))
    5755             : #endif
    5756             :     {
    5757             :         case -1:
    5758             :             /* in postmaster, fork failed ... */
    5759           0 :             ereport(LOG,
    5760             :                     (errmsg("could not fork worker process: %m")));
    5761             :             /* undo what assign_backendlist_entry did */
    5762           0 :             ReleasePostmasterChildSlot(rw->rw_child_slot);
    5763           0 :             rw->rw_child_slot = 0;
    5764           0 :             free(rw->rw_backend);
    5765           0 :             rw->rw_backend = NULL;
    5766             :             /* mark entry as crashed, so we'll try again later */
    5767           0 :             rw->rw_crashed_at = GetCurrentTimestamp();
    5768           0 :             break;
    5769             : 
    5770             : #ifndef EXEC_BACKEND
    5771             :         case 0:
    5772             :             /* in postmaster child ... */
    5773        2116 :             InitPostmasterChild();
    5774             : 
    5775             :             /* Close the postmaster's sockets */
    5776        2116 :             ClosePostmasterPorts(false);
    5777             : 
    5778             :             /*
    5779             :              * Before blowing away PostmasterContext, save this bgworker's
    5780             :              * data where it can find it.
    5781             :              */
    5782        2116 :             MyBgworkerEntry = (BackgroundWorker *)
    5783        2116 :                 MemoryContextAlloc(TopMemoryContext, sizeof(BackgroundWorker));
    5784        2116 :             memcpy(MyBgworkerEntry, &rw->rw_worker, sizeof(BackgroundWorker));
    5785             : 
    5786             :             /* Release postmaster's working memory context */
    5787        2116 :             MemoryContextSwitchTo(TopMemoryContext);
    5788        2116 :             MemoryContextDelete(PostmasterContext);
    5789        2116 :             PostmasterContext = NULL;
    5790             : 
    5791        2116 :             StartBackgroundWorker();
    5792             : 
    5793             :             exit(1);            /* should not get here */
    5794             :             break;
    5795             : #endif
    5796             :         default:
    5797             :             /* in postmaster, fork successful ... */
    5798        2252 :             rw->rw_pid = worker_pid;
    5799        2252 :             rw->rw_backend->pid = rw->rw_pid;
    5800        2252 :             ReportBackgroundWorkerPID(rw);
    5801             :             /* add new worker to lists of backends */
    5802        2252 :             dlist_push_head(&BackendList, &rw->rw_backend->elem);
    5803             : #ifdef EXEC_BACKEND
    5804             :             ShmemBackendArrayAdd(rw->rw_backend);
    5805             : #endif
    5806        2252 :             return true;
    5807             :     }
    5808             : 
    5809           0 :     return false;
    5810             : }
    5811             : 
    5812             : /*
    5813             :  * Does the current postmaster state require starting a worker with the
    5814             :  * specified start_time?
    5815             :  */
    5816             : static bool
    5817        2952 : bgworker_should_start_now(BgWorkerStartTime start_time)
    5818             : {
    5819        2952 :     switch (pmState)
    5820             :     {
    5821             :         case PM_NO_CHILDREN:
    5822             :         case PM_WAIT_DEAD_END:
    5823             :         case PM_SHUTDOWN_2:
    5824             :         case PM_SHUTDOWN:
    5825             :         case PM_WAIT_BACKENDS:
    5826             :         case PM_WAIT_READONLY:
    5827             :         case PM_WAIT_BACKUP:
    5828           0 :             break;
    5829             : 
    5830             :         case PM_RUN:
    5831        2256 :             if (start_time == BgWorkerStart_RecoveryFinished)
    5832         626 :                 return true;
    5833             :             /* fall through */
    5834             : 
    5835             :         case PM_HOT_STANDBY:
    5836        1750 :             if (start_time == BgWorkerStart_ConsistentState)
    5837        1630 :                 return true;
    5838             :             /* fall through */
    5839             : 
    5840             :         case PM_RECOVERY:
    5841             :         case PM_STARTUP:
    5842             :         case PM_INIT:
    5843         696 :             if (start_time == BgWorkerStart_PostmasterStart)
    5844           0 :                 return true;
    5845             :             /* fall through */
    5846             : 
    5847             :     }
    5848             : 
    5849         696 :     return false;
    5850             : }
    5851             : 
    5852             : /*
    5853             :  * Allocate the Backend struct for a connected background worker, but don't
    5854             :  * add it to the list of backends just yet.
    5855             :  *
    5856             :  * On failure, return false without changing any worker state.
    5857             :  *
    5858             :  * Some info from the Backend is copied into the passed rw.
    5859             :  */
    5860             : static bool
    5861        2256 : assign_backendlist_entry(RegisteredBgWorker *rw)
    5862             : {
    5863             :     Backend    *bn;
    5864             : 
    5865             :     /*
    5866             :      * Compute the cancel key that will be assigned to this session. We
    5867             :      * probably don't need cancel keys for background workers, but we'd better
    5868             :      * have something random in the field to prevent unfriendly people from
    5869             :      * sending cancels to them.
    5870             :      */
    5871        2256 :     if (!RandomCancelKey(&MyCancelKey))
    5872             :     {
    5873           0 :         ereport(LOG,
    5874             :                 (errcode(ERRCODE_INTERNAL_ERROR),
    5875             :                  errmsg("could not generate random cancel key")));
    5876           0 :         return false;
    5877             :     }
    5878             : 
    5879        2256 :     bn = malloc(sizeof(Backend));
    5880        2256 :     if (bn == NULL)
    5881             :     {
    5882           0 :         ereport(LOG,
    5883             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    5884             :                  errmsg("out of memory")));
    5885           0 :         return false;
    5886             :     }
    5887             : 
    5888        2256 :     bn->cancel_key = MyCancelKey;
    5889        2256 :     bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot();
    5890        2256 :     bn->bkend_type = BACKEND_TYPE_BGWORKER;
    5891        2256 :     bn->dead_end = false;
    5892        2256 :     bn->bgworker_notify = false;
    5893             : 
    5894        2256 :     rw->rw_backend = bn;
    5895        2256 :     rw->rw_child_slot = bn->child_slot;
    5896             : 
    5897        2256 :     return true;
    5898             : }
    5899             : 
    5900             : /*
    5901             :  * If the time is right, start background worker(s).
    5902             :  *
    5903             :  * As a side effect, the bgworker control variables are set or reset
    5904             :  * depending on whether more workers may need to be started.
    5905             :  *
    5906             :  * We limit the number of workers started per call, to avoid consuming the
    5907             :  * postmaster's attention for too long when many such requests are pending.
    5908             :  * As long as StartWorkerNeeded is true, ServerLoop will not block and will
    5909             :  * call this function again after dealing with any other issues.
    5910             :  */
    5911             : static void
    5912        5150 : maybe_start_bgworkers(void)
    5913             : {
    5914             : #define MAX_BGWORKERS_TO_LAUNCH 100
    5915        5150 :     int         num_launched = 0;
    5916        5150 :     TimestampTz now = 0;
    5917             :     slist_mutable_iter iter;
    5918             : 
    5919             :     /*
    5920             :      * During crash recovery, we have no need to be called until the state
    5921             :      * transition out of recovery.
    5922             :      */
    5923        5150 :     if (FatalError)
    5924             :     {
    5925           4 :         StartWorkerNeeded = false;
    5926           4 :         HaveCrashedWorker = false;
    5927           8 :         return;
    5928             :     }
    5929             : 
    5930             :     /* Don't need to be called again unless we find a reason for it below */
    5931        5146 :     StartWorkerNeeded = false;
    5932        5146 :     HaveCrashedWorker = false;
    5933             : 
    5934       14204 :     slist_foreach_modify(iter, &BackgroundWorkerList)
    5935             :     {
    5936             :         RegisteredBgWorker *rw;
    5937             : 
    5938        9062 :         rw = slist_container(RegisteredBgWorker, rw_lnode, iter.cur);
    5939             : 
    5940             :         /* ignore if already running */
    5941        9062 :         if (rw->rw_pid != 0)
    5942        4568 :             continue;
    5943             : 
    5944             :         /* if marked for death, clean up and remove from list */
    5945        4494 :         if (rw->rw_terminate)
    5946             :         {
    5947           0 :             ForgetBackgroundWorker(&iter);
    5948           0 :             continue;
    5949             :         }
    5950             : 
    5951             :         /*
    5952             :          * If this worker has crashed previously, maybe it needs to be
    5953             :          * restarted (unless on registration it specified it doesn't want to
    5954             :          * be restarted at all).  Check how long ago did a crash last happen.
    5955             :          * If the last crash is too recent, don't start it right away; let it
    5956             :          * be restarted once enough time has passed.
    5957             :          */
    5958        4494 :         if (rw->rw_crashed_at != 0)
    5959             :         {
    5960        1542 :             if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
    5961             :             {
    5962             :                 int         notify_pid;
    5963             : 
    5964           0 :                 notify_pid = rw->rw_worker.bgw_notify_pid;
    5965             : 
    5966           0 :                 ForgetBackgroundWorker(&iter);
    5967             : 
    5968             :                 /* Report worker is gone now. */
    5969           0 :                 if (notify_pid != 0)
    5970           0 :                     kill(notify_pid, SIGUSR1);
    5971             : 
    5972           0 :                 continue;
    5973             :             }
    5974             : 
    5975             :             /* read system time only when needed */
    5976        1542 :             if (now == 0)
    5977        1542 :                 now = GetCurrentTimestamp();
    5978             : 
    5979        1542 :             if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now,
    5980        1542 :                                             rw->rw_worker.bgw_restart_time * 1000))
    5981             :             {
    5982             :                 /* Set flag to remember that we have workers to start later */
    5983        1542 :                 HaveCrashedWorker = true;
    5984        1542 :                 continue;
    5985             :             }
    5986             :         }
    5987             : 
    5988        2952 :         if (bgworker_should_start_now(rw->rw_worker.bgw_start_time))
    5989             :         {
    5990             :             /* reset crash time before trying to start worker */
    5991        2256 :             rw->rw_crashed_at = 0;
    5992             : 
    5993             :             /*
    5994             :              * Try to start the worker.
    5995             :              *
    5996             :              * On failure, give up processing workers for now, but set
    5997             :              * StartWorkerNeeded so we'll come back here on the next iteration
    5998             :              * of ServerLoop to try again.  (We don't want to wait, because
    5999             :              * there might be additional ready-to-run workers.)  We could set
    6000             :              * HaveCrashedWorker as well, since this worker is now marked
    6001             :              * crashed, but there's no need because the next run of this
    6002             :              * function will do that.
    6003             :              */
    6004        2256 :             if (!do_start_bgworker(rw))
    6005             :             {
    6006           0 :                 StartWorkerNeeded = true;
    6007           0 :                 return;
    6008             :             }
    6009             : 
    6010             :             /*
    6011             :              * If we've launched as many workers as allowed, quit, but have
    6012             :              * ServerLoop call us again to look for additional ready-to-run
    6013             :              * workers.  There might not be any, but we'll find out the next
    6014             :              * time we run.
    6015             :              */
    6016        2252 :             if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
    6017             :             {
    6018           0 :                 StartWorkerNeeded = true;
    6019           0 :                 return;
    6020             :             }
    6021             :         }
    6022             :     }
    6023             : }
    6024             : 
    6025             : /*
    6026             :  * When a backend asks to be notified about worker state changes, we
    6027             :  * set a flag in its backend entry.  The background worker machinery needs
    6028             :  * to know when such backends exit.
    6029             :  */
    6030             : bool
    6031        1754 : PostmasterMarkPIDForWorkerNotify(int pid)
    6032             : {
    6033             :     dlist_iter  iter;
    6034             :     Backend    *bp;
    6035             : 
    6036        2956 :     dlist_foreach(iter, &BackendList)
    6037             :     {
    6038        2956 :         bp = dlist_container(Backend, elem, iter.cur);
    6039        2956 :         if (bp->pid == pid)
    6040             :         {
    6041        1754 :             bp->bgworker_notify = true;
    6042        1754 :             return true;
    6043             :         }
    6044             :     }
    6045           0 :     return false;
    6046             : }
    6047             : 
    6048             : #ifdef EXEC_BACKEND
    6049             : 
    6050             : /*
    6051             :  * The following need to be available to the save/restore_backend_variables
    6052             :  * functions.  They are marked NON_EXEC_STATIC in their home modules.
    6053             :  */
    6054             : extern slock_t *ShmemLock;
    6055             : extern slock_t *ProcStructLock;
    6056             : extern PGPROC *AuxiliaryProcs;
    6057             : extern PMSignalData *PMSignalState;
    6058             : extern pgsocket pgStatSock;
    6059             : extern pg_time_t first_syslogger_file_time;
    6060             : 
    6061             : #ifndef WIN32
    6062             : #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
    6063             : #define read_inheritable_socket(dest, src) (*(dest) = *(src))
    6064             : #else
    6065             : static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
    6066             : static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
    6067             :                                      pid_t childPid);
    6068             : static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
    6069             : #endif
    6070             : 
    6071             : 
    6072             : /* Save critical backend variables into the BackendParameters struct */
    6073             : #ifndef WIN32
    6074             : static bool
    6075             : save_backend_variables(BackendParameters *param, Port *port)
    6076             : #else
    6077             : static bool
    6078             : save_backend_variables(BackendParameters *param, Port *port,
    6079             :                        HANDLE childProcess, pid_t childPid)
    6080             : #endif
    6081             : {
    6082             :     memcpy(&param->port, port, sizeof(Port));
    6083             :     if (!write_inheritable_socket(&param->portsocket, port->sock, childPid))
    6084             :         return false;
    6085             : 
    6086             :     strlcpy(param->DataDir, DataDir, MAXPGPATH);
    6087             : 
    6088             :     memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket));
    6089             : 
    6090             :     param->MyCancelKey = MyCancelKey;
    6091             :     param->MyPMChildSlot = MyPMChildSlot;
    6092             : 
    6093             : #ifdef WIN32
    6094             :     param->ShmemProtectiveRegion = ShmemProtectiveRegion;
    6095             : #endif
    6096             :     param->UsedShmemSegID = UsedShmemSegID;
    6097             :     param->UsedShmemSegAddr = UsedShmemSegAddr;
    6098             : 
    6099             :     param->ShmemLock = ShmemLock;
    6100             :     param->ShmemVariableCache = ShmemVariableCache;
    6101             :     param->ShmemBackendArray = ShmemBackendArray;
    6102             : 
    6103             : #ifndef HAVE_SPINLOCKS
    6104             :     param->SpinlockSemaArray = SpinlockSemaArray;
    6105             : #endif
    6106             :     param->NamedLWLockTrancheRequests = NamedLWLockTrancheRequests;
    6107             :     param->NamedLWLockTrancheArray = NamedLWLockTrancheArray;
    6108             :     param->MainLWLockArray = MainLWLockArray;
    6109             :     param->ProcStructLock = ProcStructLock;
    6110             :     param->ProcGlobal = ProcGlobal;
    6111             :     param->AuxiliaryProcs = AuxiliaryProcs;
    6112             :     param->PreparedXactProcs = PreparedXactProcs;
    6113             :     param->PMSignalState = PMSignalState;
    6114             :     if (!write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid))
    6115             :         return false;
    6116             : 
    6117             :     param->PostmasterPid = PostmasterPid;
    6118             :     param->PgStartTime = PgStartTime;
    6119             :     param->PgReloadTime = PgReloadTime;
    6120             :     param->first_syslogger_file_time = first_syslogger_file_time;
    6121             : 
    6122             :     param->redirection_done = redirection_done;
    6123             :     param->IsBinaryUpgrade = IsBinaryUpgrade;
    6124             :     param->max_safe_fds = max_safe_fds;
    6125             : 
    6126             :     param->MaxBackends = MaxBackends;
    6127             : 
    6128             : #ifdef WIN32
    6129             :     param->PostmasterHandle = PostmasterHandle;
    6130             :     if (!write_duplicated_handle(&param->initial_signal_pipe,
    6131             :                                  pgwin32_create_signal_listener(childPid),
    6132             :                                  childProcess))
    6133             :         return false;
    6134             : #else
    6135             :     memcpy(&param->postmaster_alive_fds, &postmaster_alive_fds,
    6136             :            sizeof(postmaster_alive_fds));
    6137             : #endif
    6138             : 
    6139             :     memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe));
    6140             : 
    6141             :     strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
    6142             : 
    6143             :     strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
    6144             : 
    6145             :     strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
    6146             : 
    6147             :     return true;
    6148             : }
    6149             : 
    6150             : 
    6151             : #ifdef WIN32
    6152             : /*
    6153             :  * Duplicate a handle for usage in a child process, and write the child
    6154             :  * process instance of the handle to the parameter file.
    6155             :  */
    6156             : static bool
    6157             : write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
    6158             : {
    6159             :     HANDLE      hChild = INVALID_HANDLE_VALUE;
    6160             : 
    6161             :     if (!DuplicateHandle(GetCurrentProcess(),
    6162             :                          src,
    6163             :                          childProcess,
    6164             :                          &hChild,
    6165             :                          0,
    6166             :                          TRUE,
    6167             :                          DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
    6168             :     {
    6169             :         ereport(LOG,
    6170             :                 (errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
    6171             :                                  GetLastError())));
    6172             :         return false;
    6173             :     }
    6174             : 
    6175             :     *dest = hChild;
    6176             :     return true;
    6177             : }
    6178             : 
    6179             : /*
    6180             :  * Duplicate a socket for usage in a child process, and write the resulting
    6181             :  * structure to the parameter file.
    6182             :  * This is required because a number of LSPs (Layered Service Providers) very
    6183             :  * common on Windows (antivirus, firewalls, download managers etc) break
    6184             :  * straight socket inheritance.
    6185             :  */
    6186             : static bool
    6187             : write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
    6188             : {
    6189             :     dest->origsocket = src;
    6190             :     if (src != 0 && src != PGINVALID_SOCKET)
    6191             :     {
    6192             :         /* Actual socket */
    6193             :         if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
    6194             :         {
    6195             :             ereport(LOG,
    6196             :                     (errmsg("could not duplicate socket %d for use in backend: error code %d",
    6197             :                             (int) src, WSAGetLastError())));
    6198             :             return false;
    6199             :         }
    6200             :     }
    6201             :     return true;
    6202             : }
    6203             : 
    6204             : /*
    6205             :  * Read a duplicate socket structure back, and get the socket descriptor.
    6206             :  */
    6207             : static void
    6208             : read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
    6209             : {
    6210             :     SOCKET      s;
    6211             : 
    6212             :     if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
    6213             :     {
    6214             :         /* Not a real socket! */
    6215             :         *dest = src->origsocket;
    6216             :     }
    6217             :     else
    6218             :     {
    6219             :         /* Actual socket, so create from structure */
    6220             :         s = WSASocket(FROM_PROTOCOL_INFO,
    6221             :                       FROM_PROTOCOL_INFO,
    6222             :                       FROM_PROTOCOL_INFO,
    6223             :                       &src->wsainfo,
    6224             :                       0,
    6225             :                       0);
    6226             :         if (s == INVALID_SOCKET)
    6227             :         {
    6228             :             write_stderr("could not create inherited socket: error code %d\n",
    6229             :                          WSAGetLastError());
    6230             :             exit(1);
    6231             :         }
    6232             :         *dest = s;
    6233             : 
    6234             :         /*
    6235             :          * To make sure we don't get two references to the same socket, close
    6236             :          * the original one. (This would happen when inheritance actually
    6237             :          * works..
    6238             :          */
    6239             :         closesocket(src->origsocket);
    6240             :     }
    6241             : }
    6242             : #endif
    6243             : 
    6244             : static void
    6245             : read_backend_variables(char *id, Port *port)
    6246             : {
    6247             :     BackendParameters param;
    6248             : 
    6249             : #ifndef WIN32
    6250             :     /* Non-win32 implementation reads from file */
    6251             :     FILE       *fp;
    6252             : 
    6253             :     /* Open file */
    6254             :     fp = AllocateFile(id, PG_BINARY_R);
    6255             :     if (!fp)
    6256             :     {
    6257             :         write_stderr("could not open backend variables file \"%s\": %s\n",
    6258             :                      id, strerror(errno));
    6259             :         exit(1);
    6260             :     }
    6261             : 
    6262             :     if (fread(&param, sizeof(param), 1, fp) != 1)
    6263             :     {
    6264             :         write_stderr("could not read from backend variables file \"%s\": %s\n",
    6265             :                      id, strerror(errno));
    6266             :         exit(1);
    6267             :     }
    6268             : 
    6269             :     /* Release file */
    6270             :     FreeFile(fp);
    6271             :     if (unlink(id) != 0)
    6272             :     {
    6273             :         write_stderr("could not remove file \"%s\": %s\n",
    6274             :                      id, strerror(errno));
    6275             :         exit(1);
    6276             :     }
    6277             : #else
    6278             :     /* Win32 version uses mapped file */
    6279             :     HANDLE      paramHandle;
    6280             :     BackendParameters *paramp;
    6281             : 
    6282             : #ifdef _WIN64
    6283             :     paramHandle = (HANDLE) _atoi64(id);
    6284             : #else
    6285             :     paramHandle = (HANDLE) atol(id);
    6286             : #endif
    6287             :     paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
    6288             :     if (!paramp)
    6289             :     {
    6290             :         write_stderr("could not map view of backend variables: error code %lu\n",
    6291             :                      GetLastError());
    6292             :         exit(1);
    6293             :     }
    6294             : 
    6295             :     memcpy(&param, paramp, sizeof(BackendParameters));
    6296             : 
    6297             :     if (!UnmapViewOfFile(paramp))
    6298             :     {
    6299             :         write_stderr("could not unmap view of backend variables: error code %lu\n",
    6300             :                      GetLastError());
    6301             :         exit(1);
    6302             :     }
    6303             : 
    6304             :     if (!CloseHandle(paramHandle))
    6305             :     {
    6306             :         write_stderr("could not close handle to backend parameter variables: error code %lu\n",
    6307             :                      GetLastError());
    6308             :         exit(1);
    6309             :     }
    6310             : #endif
    6311             : 
    6312             :     restore_backend_variables(&param, port);
    6313             : }
    6314             : 
    6315             : /* Restore critical backend variables from the BackendParameters struct */
    6316             : static void
    6317             : restore_backend_variables(BackendParameters *param, Port *port)
    6318             : {
    6319             :     memcpy(port, &param->port, sizeof(Port));
    6320             :     read_inheritable_socket(&port->sock, &param->portsocket);
    6321             : 
    6322             :     SetDataDir(param->DataDir);
    6323             : 
    6324             :     memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket));
    6325             : 
    6326             :     MyCancelKey = param->MyCancelKey;
    6327             :     MyPMChildSlot = param->MyPMChildSlot;
    6328             : 
    6329             : #ifdef WIN32
    6330             :     ShmemProtectiveRegion = param->ShmemProtectiveRegion;
    6331             : #endif
    6332             :     UsedShmemSegID = param->UsedShmemSegID;
    6333             :     UsedShmemSegAddr = param->UsedShmemSegAddr;
    6334             : 
    6335             :     ShmemLock = param->ShmemLock;
    6336             :     ShmemVariableCache = param->ShmemVariableCache;
    6337             :     ShmemBackendArray = param->ShmemBackendArray;
    6338             : 
    6339             : #ifndef HAVE_SPINLOCKS
    6340             :     SpinlockSemaArray = param->SpinlockSemaArray;
    6341             : #endif
    6342             :     NamedLWLockTrancheRequests = param->NamedLWLockTrancheRequests;
    6343             :     NamedLWLockTrancheArray = param->NamedLWLockTrancheArray;
    6344             :     MainLWLockArray = param->MainLWLockArray;
    6345             :     ProcStructLock = param->ProcStructLock;
    6346             :     ProcGlobal = param->ProcGlobal;
    6347             :     AuxiliaryProcs = param->AuxiliaryProcs;
    6348             :     PreparedXactProcs = param->PreparedXactProcs;
    6349             :     PMSignalState = param->PMSignalState;
    6350             :     read_inheritable_socket(&pgStatSock, &param->pgStatSock);
    6351             : 
    6352             :     PostmasterPid = param->PostmasterPid;
    6353             :     PgStartTime = param->PgStartTime;
    6354             :     PgReloadTime = param->PgReloadTime;
    6355             :     first_syslogger_file_time = param->first_syslogger_file_time;
    6356             : 
    6357             :     redirection_done = param->redirection_done;
    6358             :     IsBinaryUpgrade = param->IsBinaryUpgrade;
    6359             :     max_safe_fds = param->max_safe_fds;
    6360             : 
    6361             :     MaxBackends = param->MaxBackends;
    6362             : 
    6363             : #ifdef WIN32
    6364             :     PostmasterHandle = param->PostmasterHandle;
    6365             :     pgwin32_initial_signal_pipe = param->initial_signal_pipe;
    6366             : #else
    6367             :     memcpy(&postmaster_alive_fds, &param->postmaster_alive_fds,
    6368             :            sizeof(postmaster_alive_fds));
    6369             : #endif
    6370             : 
    6371             :     memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe));
    6372             : 
    6373             :     strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
    6374             : 
    6375             :     strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
    6376             : 
    6377             :     strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
    6378             : }
    6379             : 
    6380             : 
    6381             : Size
    6382             : ShmemBackendArraySize(void)
    6383             : {
    6384             :     return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
    6385             : }
    6386             : 
    6387             : void
    6388             : ShmemBackendArrayAllocation(void)
    6389             : {
    6390             :     Size        size = ShmemBackendArraySize();
    6391             : 
    6392             :     ShmemBackendArray = (Backend *) ShmemAlloc(size);
    6393             :     /* Mark all slots as empty */
    6394             :     memset(ShmemBackendArray, 0, size);
    6395             : }
    6396             : 
    6397             : static void
    6398             : ShmemBackendArrayAdd(Backend *bn)
    6399             : {
    6400             :     /* The array slot corresponding to my PMChildSlot should be free */
    6401             :     int         i = bn->child_slot - 1;
    6402             : 
    6403             :     Assert(ShmemBackendArray[i].pid == 0);
    6404             :     ShmemBackendArray[i] = *bn;
    6405             : }
    6406             : 
    6407             : static void
    6408             : ShmemBackendArrayRemove(Backend *bn)
    6409             : {
    6410             :     int         i = bn->child_slot - 1;
    6411             : 
    6412             :     Assert(ShmemBackendArray[i].pid == bn->pid);
    6413             :     /* Mark the slot as empty */
    6414             :     ShmemBackendArray[i].pid = 0;
    6415             : }
    6416             : #endif                          /* EXEC_BACKEND */
    6417             : 
    6418             : 
    6419             : #ifdef WIN32
    6420             : 
    6421             : /*
    6422             :  * Subset implementation of waitpid() for Windows.  We assume pid is -1
    6423             :  * (that is, check all child processes) and options is WNOHANG (don't wait).
    6424             :  */
    6425             : static pid_t
    6426             : waitpid(pid_t pid, int *exitstatus, int options)
    6427             : {
    6428             :     DWORD       dwd;
    6429             :     ULONG_PTR   key;
    6430             :     OVERLAPPED *ovl;
    6431             : 
    6432             :     /*
    6433             :      * Check if there are any dead children. If there are, return the pid of
    6434             :      * the first one that died.
    6435             :      */
    6436             :     if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
    6437             :     {
    6438             :         *exitstatus = (int) key;
    6439             :         return dwd;
    6440             :     }
    6441             : 
    6442             :     return -1;
    6443             : }
    6444             : 
    6445             : /*
    6446             :  * Note! Code below executes on a thread pool! All operations must
    6447             :  * be thread safe! Note that elog() and friends must *not* be used.
    6448             :  */
    6449             : static void WINAPI
    6450             : pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
    6451             : {
    6452             :     win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
    6453             :     DWORD       exitcode;
    6454             : 
    6455             :     if (TimerOrWaitFired)
    6456             :         return;                 /* timeout. Should never happen, since we use
    6457             :                                  * INFINITE as timeout value. */
    6458             : 
    6459             :     /*
    6460             :      * Remove handle from wait - required even though it's set to wait only
    6461             :      * once
    6462             :      */
    6463             :     UnregisterWaitEx(childinfo->waitHandle, NULL);
    6464             : 
    6465             :     if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
    6466             :     {
    6467             :         /*
    6468             :          * Should never happen. Inform user and set a fixed exitcode.
    6469             :          */
    6470             :         write_stderr("could not read exit code for process\n");
    6471             :         exitcode = 255;
    6472             :     }
    6473             : 
    6474             :     if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
    6475             :         write_stderr("could not post child completion status\n");
    6476             : 
    6477             :     /*
    6478             :      * Handle is per-process, so we close it here instead of in the
    6479             :      * originating thread
    6480             :      */
    6481             :     CloseHandle(childinfo->procHandle);
    6482             : 
    6483             :     /*
    6484             :      * Free struct that was allocated before the call to
    6485             :      * RegisterWaitForSingleObject()
    6486             :      */
    6487             :     free(childinfo);
    6488             : 
    6489             :     /* Queue SIGCHLD signal */
    6490             :     pg_queue_signal(SIGCHLD);
    6491             : }
    6492             : #endif                          /* WIN32 */
    6493             : 
    6494             : /*
    6495             :  * Initialize one and only handle for monitoring postmaster death.
    6496             :  *
    6497             :  * Called once in the postmaster, so that child processes can subsequently
    6498             :  * monitor if their parent is dead.
    6499             :  */
    6500             : static void
    6501         572 : InitPostmasterDeathWatchHandle(void)
    6502             : {
    6503             : #ifndef WIN32
    6504             : 
    6505             :     /*
    6506             :      * Create a pipe. Postmaster holds the write end of the pipe open
    6507             :      * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
    6508             :      * the read file descriptor to select() to wake up in case postmaster
    6509             :      * dies, or check for postmaster death with a (read() == 0). Children must
    6510             :      * close the write end as soon as possible after forking, because EOF
    6511             :      * won't be signaled in the read end until all processes have closed the
    6512             :      * write fd. That is taken care of in ClosePostmasterPorts().
    6513             :      */
    6514             :     Assert(MyProcPid == PostmasterPid);
    6515         572 :     if (pipe(postmaster_alive_fds) < 0)
    6516           0 :         ereport(FATAL,
    6517             :                 (errcode_for_file_access(),
    6518             :                  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
    6519             : 
    6520             :     /*
    6521             :      * Set O_NONBLOCK to allow testing for the fd's presence with a read()
    6522             :      * call.
    6523             :      */
    6524         572 :     if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
    6525           0 :         ereport(FATAL,
    6526             :                 (errcode_for_socket_access(),
    6527             :                  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
    6528             : #else
    6529             : 
    6530             :     /*
    6531             :      * On Windows, we use a process handle for the same purpose.
    6532             :      */
    6533             :     if (DuplicateHandle(GetCurrentProcess(),
    6534             :                         GetCurrentProcess(),
    6535             :                         GetCurrentProcess(),
    6536             :                         &PostmasterHandle,
    6537             :                         0,
    6538             :                         TRUE,
    6539             :                         DUPLICATE_SAME_ACCESS) == 0)
    6540             :         ereport(FATAL,
    6541             :                 (errmsg_internal("could not duplicate postmaster handle: error code %lu",
    6542             :                                  GetLastError())));
    6543             : #endif                          /* WIN32 */
    6544         572 : }

Generated by: LCOV version 1.13