LCOV - code coverage report
Current view: top level - src/backend/postmaster - postmaster.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 847 1131 74.9 %
Date: 2025-01-29 20:17:04 Functions: 46 50 92.0 %
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 connect to the Postmaster,
       6             :  *    and postmaster forks a new backend process to handle the
       7             :  *    connection.
       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-2025, 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 USE_BONJOUR
      81             : #include <dns_sd.h>
      82             : #endif
      83             : 
      84             : #ifdef USE_SYSTEMD
      85             : #include <systemd/sd-daemon.h>
      86             : #endif
      87             : 
      88             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
      89             : #include <pthread.h>
      90             : #endif
      91             : 
      92             : #include "access/xlog.h"
      93             : #include "access/xlogrecovery.h"
      94             : #include "common/file_perm.h"
      95             : #include "common/pg_prng.h"
      96             : #include "lib/ilist.h"
      97             : #include "libpq/libpq.h"
      98             : #include "libpq/pqsignal.h"
      99             : #include "pg_getopt.h"
     100             : #include "pgstat.h"
     101             : #include "port/pg_bswap.h"
     102             : #include "postmaster/autovacuum.h"
     103             : #include "postmaster/bgworker_internals.h"
     104             : #include "postmaster/pgarch.h"
     105             : #include "postmaster/postmaster.h"
     106             : #include "postmaster/syslogger.h"
     107             : #include "postmaster/walsummarizer.h"
     108             : #include "replication/logicallauncher.h"
     109             : #include "replication/slotsync.h"
     110             : #include "replication/walsender.h"
     111             : #include "storage/fd.h"
     112             : #include "storage/ipc.h"
     113             : #include "storage/pmsignal.h"
     114             : #include "tcop/backend_startup.h"
     115             : #include "tcop/tcopprot.h"
     116             : #include "utils/datetime.h"
     117             : #include "utils/memutils.h"
     118             : #include "utils/pidfile.h"
     119             : #include "utils/timestamp.h"
     120             : #include "utils/varlena.h"
     121             : 
     122             : #ifdef EXEC_BACKEND
     123             : #include "common/file_utils.h"
     124             : #include "storage/pg_shmem.h"
     125             : #endif
     126             : 
     127             : 
     128             : /*
     129             :  * CountChildren and SignalChildren take a bitmask argument to represent
     130             :  * BackendTypes to count or signal.  Define a separate type and functions to
     131             :  * work with the bitmasks, to avoid accidentally passing a plain BackendType
     132             :  * in place of a bitmask or vice versa.
     133             :  */
     134             : typedef struct
     135             : {
     136             :     uint32      mask;
     137             : } BackendTypeMask;
     138             : 
     139             : StaticAssertDecl(BACKEND_NUM_TYPES < 32, "too many backend types for uint32");
     140             : 
     141             : static const BackendTypeMask BTYPE_MASK_ALL = {(1 << BACKEND_NUM_TYPES) - 1};
     142             : static const BackendTypeMask BTYPE_MASK_NONE = {0};
     143             : 
     144             : static inline BackendTypeMask
     145        1608 : btmask(BackendType t)
     146             : {
     147        1608 :     BackendTypeMask mask = {.mask = 1 << t};
     148             : 
     149        1608 :     return mask;
     150             : }
     151             : 
     152             : static inline BackendTypeMask
     153       24952 : btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
     154             : {
     155      107204 :     for (int i = 0; i < nargs; i++)
     156       82252 :         mask.mask |= 1 << t[i];
     157       24952 :     return mask;
     158             : }
     159             : 
     160             : #define btmask_add(mask, ...) \
     161             :     btmask_add_n(mask, \
     162             :         lengthof(((BackendType[]){__VA_ARGS__})), \
     163             :         (BackendType[]){__VA_ARGS__} \
     164             :     )
     165             : 
     166             : static inline BackendTypeMask
     167        6298 : btmask_del(BackendTypeMask mask, BackendType t)
     168             : {
     169        6298 :     mask.mask &= ~(1 << t);
     170        6298 :     return mask;
     171             : }
     172             : 
     173             : static inline BackendTypeMask
     174        4330 : btmask_all_except_n(int nargs, BackendType *t)
     175             : {
     176        4330 :     BackendTypeMask mask = BTYPE_MASK_ALL;
     177             : 
     178       10628 :     for (int i = 0; i < nargs; i++)
     179        6298 :         mask = btmask_del(mask, t[i]);
     180        4330 :     return mask;
     181             : }
     182             : 
     183             : #define btmask_all_except(...) \
     184             :     btmask_all_except_n( \
     185             :         lengthof(((BackendType[]){__VA_ARGS__})), \
     186             :         (BackendType[]){__VA_ARGS__} \
     187             :     )
     188             : 
     189             : static inline bool
     190      107844 : btmask_contains(BackendTypeMask mask, BackendType t)
     191             : {
     192      107844 :     return (mask.mask & (1 << t)) != 0;
     193             : }
     194             : 
     195             : 
     196             : BackgroundWorker *MyBgworkerEntry = NULL;
     197             : 
     198             : /* The socket number we are listening for connections on */
     199             : int         PostPortNumber = DEF_PGPORT;
     200             : 
     201             : /* The directory names for Unix socket(s) */
     202             : char       *Unix_socket_directories;
     203             : 
     204             : /* The TCP listen address(es) */
     205             : char       *ListenAddresses;
     206             : 
     207             : /*
     208             :  * SuperuserReservedConnections is the number of backends reserved for
     209             :  * superuser use, and ReservedConnections is the number of backends reserved
     210             :  * for use by roles with privileges of the pg_use_reserved_connections
     211             :  * predefined role.  These are taken out of the pool of MaxConnections backend
     212             :  * slots, so the number of backend slots available for roles that are neither
     213             :  * superuser nor have privileges of pg_use_reserved_connections is
     214             :  * (MaxConnections - SuperuserReservedConnections - ReservedConnections).
     215             :  *
     216             :  * If the number of remaining slots is less than or equal to
     217             :  * SuperuserReservedConnections, only superusers can make new connections.  If
     218             :  * the number of remaining slots is greater than SuperuserReservedConnections
     219             :  * but less than or equal to
     220             :  * (SuperuserReservedConnections + ReservedConnections), only superusers and
     221             :  * roles with privileges of pg_use_reserved_connections can make new
     222             :  * connections.  Note that pre-existing superuser and
     223             :  * pg_use_reserved_connections connections don't count against the limits.
     224             :  */
     225             : int         SuperuserReservedConnections;
     226             : int         ReservedConnections;
     227             : 
     228             : /* The socket(s) we're listening to. */
     229             : #define MAXLISTEN   64
     230             : static int  NumListenSockets = 0;
     231             : static pgsocket *ListenSockets = NULL;
     232             : 
     233             : /* still more option variables */
     234             : bool        EnableSSL = false;
     235             : 
     236             : int         PreAuthDelay = 0;
     237             : int         AuthenticationTimeout = 60;
     238             : 
     239             : bool        log_hostname;       /* for ps display and logging */
     240             : bool        Log_connections = false;
     241             : 
     242             : bool        enable_bonjour = false;
     243             : char       *bonjour_name;
     244             : bool        restart_after_crash = true;
     245             : bool        remove_temp_files_after_crash = true;
     246             : 
     247             : /*
     248             :  * When terminating child processes after fatal errors, like a crash of a
     249             :  * child process, we normally send SIGQUIT -- and most other comments in this
     250             :  * file are written on the assumption that we do -- but developers might
     251             :  * prefer to use SIGABRT to collect per-child core dumps.
     252             :  */
     253             : bool        send_abort_for_crash = false;
     254             : bool        send_abort_for_kill = false;
     255             : 
     256             : /* special child processes; NULL when not running */
     257             : static PMChild *StartupPMChild = NULL,
     258             :            *BgWriterPMChild = NULL,
     259             :            *CheckpointerPMChild = NULL,
     260             :            *WalWriterPMChild = NULL,
     261             :            *WalReceiverPMChild = NULL,
     262             :            *WalSummarizerPMChild = NULL,
     263             :            *AutoVacLauncherPMChild = NULL,
     264             :            *PgArchPMChild = NULL,
     265             :            *SysLoggerPMChild = NULL,
     266             :            *SlotSyncWorkerPMChild = NULL;
     267             : 
     268             : /* Startup process's status */
     269             : typedef enum
     270             : {
     271             :     STARTUP_NOT_RUNNING,
     272             :     STARTUP_RUNNING,
     273             :     STARTUP_SIGNALED,           /* we sent it a SIGQUIT or SIGKILL */
     274             :     STARTUP_CRASHED,
     275             : } StartupStatusEnum;
     276             : 
     277             : static StartupStatusEnum StartupStatus = STARTUP_NOT_RUNNING;
     278             : 
     279             : /* Startup/shutdown state */
     280             : #define         NoShutdown      0
     281             : #define         SmartShutdown   1
     282             : #define         FastShutdown    2
     283             : #define         ImmediateShutdown   3
     284             : 
     285             : static int  Shutdown = NoShutdown;
     286             : 
     287             : static bool FatalError = false; /* T if recovering from backend crash */
     288             : 
     289             : /*
     290             :  * We use a simple state machine to control startup, shutdown, and
     291             :  * crash recovery (which is rather like shutdown followed by startup).
     292             :  *
     293             :  * After doing all the postmaster initialization work, we enter PM_STARTUP
     294             :  * state and the startup process is launched. The startup process begins by
     295             :  * reading the control file and other preliminary initialization steps.
     296             :  * In a normal startup, or after crash recovery, the startup process exits
     297             :  * with exit code 0 and we switch to PM_RUN state.  However, archive recovery
     298             :  * is handled specially since it takes much longer and we would like to support
     299             :  * hot standby during archive recovery.
     300             :  *
     301             :  * When the startup process is ready to start archive recovery, it signals the
     302             :  * postmaster, and we switch to PM_RECOVERY state. The background writer and
     303             :  * checkpointer are launched, while the startup process continues applying WAL.
     304             :  * If Hot Standby is enabled, then, after reaching a consistent point in WAL
     305             :  * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
     306             :  * state and begin accepting connections to perform read-only queries.  When
     307             :  * archive recovery is finished, the startup process exits with exit code 0
     308             :  * and we switch to PM_RUN state.
     309             :  *
     310             :  * Normal child backends can only be launched when we are in PM_RUN or
     311             :  * PM_HOT_STANDBY state.  (connsAllowed can also restrict launching.)
     312             :  * In other states we handle connection requests by launching "dead-end"
     313             :  * child processes, which will simply send the client an error message and
     314             :  * quit.  (We track these in the ActiveChildList so that we can know when they
     315             :  * are all gone; this is important because they're still connected to shared
     316             :  * memory, and would interfere with an attempt to destroy the shmem segment,
     317             :  * possibly leading to SHMALL failure when we try to make a new one.)
     318             :  * In PM_WAIT_DEAD_END state we are waiting for all the dead-end children
     319             :  * to drain out of the system, and therefore stop accepting connection
     320             :  * requests at all until the last existing child has quit (which hopefully
     321             :  * will not be very long).
     322             :  *
     323             :  * Notice that this state variable does not distinguish *why* we entered
     324             :  * states later than PM_RUN --- Shutdown and FatalError must be consulted
     325             :  * to find that out.  FatalError is never true in PM_RECOVERY, PM_HOT_STANDBY,
     326             :  * or PM_RUN states, nor in PM_WAIT_XLOG_SHUTDOWN states (because we don't
     327             :  * enter those states when trying to recover from a crash).  It can be true in
     328             :  * PM_STARTUP state, because we don't clear it until we've successfully
     329             :  * started WAL redo.
     330             :  */
     331             : typedef enum
     332             : {
     333             :     PM_INIT,                    /* postmaster starting */
     334             :     PM_STARTUP,                 /* waiting for startup subprocess */
     335             :     PM_RECOVERY,                /* in archive recovery mode */
     336             :     PM_HOT_STANDBY,             /* in hot standby mode */
     337             :     PM_RUN,                     /* normal "database is alive" state */
     338             :     PM_STOP_BACKENDS,           /* need to stop remaining backends */
     339             :     PM_WAIT_BACKENDS,           /* waiting for live backends to exit */
     340             :     PM_WAIT_XLOG_SHUTDOWN,      /* waiting for checkpointer to do shutdown
     341             :                                  * ckpt */
     342             :     PM_WAIT_XLOG_ARCHIVAL,      /* waiting for archiver and walsenders to
     343             :                                  * finish */
     344             :     PM_WAIT_CHECKPOINTER,       /* waiting for checkpointer to shut down */
     345             :     PM_WAIT_DEAD_END,           /* waiting for dead-end children to exit */
     346             :     PM_NO_CHILDREN,             /* all important children have exited */
     347             : } PMState;
     348             : 
     349             : static PMState pmState = PM_INIT;
     350             : 
     351             : /*
     352             :  * While performing a "smart shutdown", we restrict new connections but stay
     353             :  * in PM_RUN or PM_HOT_STANDBY state until all the client backends are gone.
     354             :  * connsAllowed is a sub-state indicator showing the active restriction.
     355             :  * It is of no interest unless pmState is PM_RUN or PM_HOT_STANDBY.
     356             :  */
     357             : static bool connsAllowed = true;
     358             : 
     359             : /* Start time of SIGKILL timeout during immediate shutdown or child crash */
     360             : /* Zero means timeout is not running */
     361             : static time_t AbortStartTime = 0;
     362             : 
     363             : /* Length of said timeout */
     364             : #define SIGKILL_CHILDREN_AFTER_SECS     5
     365             : 
     366             : static bool ReachedNormalRunning = false;   /* T if we've reached PM_RUN */
     367             : 
     368             : bool        ClientAuthInProgress = false;   /* T during new-client
     369             :                                              * authentication */
     370             : 
     371             : bool        redirection_done = false;   /* stderr redirected for syslogger? */
     372             : 
     373             : /* received START_AUTOVAC_LAUNCHER signal */
     374             : static bool start_autovac_launcher = false;
     375             : 
     376             : /* the launcher needs to be signaled to communicate some condition */
     377             : static bool avlauncher_needs_signal = false;
     378             : 
     379             : /* received START_WALRECEIVER signal */
     380             : static bool WalReceiverRequested = false;
     381             : 
     382             : /* set when there's a worker that needs to be started up */
     383             : static bool StartWorkerNeeded = true;
     384             : static bool HaveCrashedWorker = false;
     385             : 
     386             : /* set when signals arrive */
     387             : static volatile sig_atomic_t pending_pm_pmsignal;
     388             : static volatile sig_atomic_t pending_pm_child_exit;
     389             : static volatile sig_atomic_t pending_pm_reload_request;
     390             : static volatile sig_atomic_t pending_pm_shutdown_request;
     391             : static volatile sig_atomic_t pending_pm_fast_shutdown_request;
     392             : static volatile sig_atomic_t pending_pm_immediate_shutdown_request;
     393             : 
     394             : /* event multiplexing object */
     395             : static WaitEventSet *pm_wait_set;
     396             : 
     397             : #ifdef USE_SSL
     398             : /* Set when and if SSL has been initialized properly */
     399             : bool        LoadedSSL = false;
     400             : #endif
     401             : 
     402             : #ifdef USE_BONJOUR
     403             : static DNSServiceRef bonjour_sdref = NULL;
     404             : #endif
     405             : 
     406             : /*
     407             :  * postmaster.c - function prototypes
     408             :  */
     409             : static void CloseServerPorts(int status, Datum arg);
     410             : static void unlink_external_pid_file(int status, Datum arg);
     411             : static void getInstallationPaths(const char *argv0);
     412             : static void checkControlFile(void);
     413             : static void handle_pm_pmsignal_signal(SIGNAL_ARGS);
     414             : static void handle_pm_child_exit_signal(SIGNAL_ARGS);
     415             : static void handle_pm_reload_request_signal(SIGNAL_ARGS);
     416             : static void handle_pm_shutdown_request_signal(SIGNAL_ARGS);
     417             : static void process_pm_pmsignal(void);
     418             : static void process_pm_child_exit(void);
     419             : static void process_pm_reload_request(void);
     420             : static void process_pm_shutdown_request(void);
     421             : static void dummy_handler(SIGNAL_ARGS);
     422             : static void CleanupBackend(PMChild *bp, int exitstatus);
     423             : static void HandleChildCrash(int pid, int exitstatus, const char *procname);
     424             : static void LogChildExit(int lev, const char *procname,
     425             :                          int pid, int exitstatus);
     426             : static void PostmasterStateMachine(void);
     427             : static void UpdatePMState(PMState newState);
     428             : 
     429             : static void ExitPostmaster(int status) pg_attribute_noreturn();
     430             : static int  ServerLoop(void);
     431             : static int  BackendStartup(ClientSocket *client_sock);
     432             : static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum);
     433             : static CAC_state canAcceptConnections(BackendType backend_type);
     434             : static void signal_child(PMChild *pmchild, int signal);
     435             : static bool SignalChildren(int signal, BackendTypeMask targetMask);
     436             : static void TerminateChildren(int signal);
     437             : static int  CountChildren(BackendTypeMask targetMask);
     438             : static void LaunchMissingBackgroundProcesses(void);
     439             : static void maybe_start_bgworkers(void);
     440             : static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
     441             : static PMChild *StartChildProcess(BackendType type);
     442             : static void StartSysLogger(void);
     443             : static void StartAutovacuumWorker(void);
     444             : static bool StartBackgroundWorker(RegisteredBgWorker *rw);
     445             : static void InitPostmasterDeathWatchHandle(void);
     446             : 
     447             : #ifdef WIN32
     448             : #define WNOHANG 0               /* ignored, so any integer value will do */
     449             : 
     450             : static pid_t waitpid(pid_t pid, int *exitstatus, int options);
     451             : static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
     452             : 
     453             : static HANDLE win32ChildQueue;
     454             : 
     455             : typedef struct
     456             : {
     457             :     HANDLE      waitHandle;
     458             :     HANDLE      procHandle;
     459             :     DWORD       procId;
     460             : } win32_deadchild_waitinfo;
     461             : #endif                          /* WIN32 */
     462             : 
     463             : /* Macros to check exit status of a child process */
     464             : #define EXIT_STATUS_0(st)  ((st) == 0)
     465             : #define EXIT_STATUS_1(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 1)
     466             : #define EXIT_STATUS_3(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 3)
     467             : 
     468             : #ifndef WIN32
     469             : /*
     470             :  * File descriptors for pipe used to monitor if postmaster is alive.
     471             :  * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
     472             :  */
     473             : int         postmaster_alive_fds[2] = {-1, -1};
     474             : #else
     475             : /* Process handle of postmaster used for the same purpose on Windows */
     476             : HANDLE      PostmasterHandle;
     477             : #endif
     478             : 
     479             : /*
     480             :  * Postmaster main entry point
     481             :  */
     482             : void
     483        1558 : PostmasterMain(int argc, char *argv[])
     484             : {
     485             :     int         opt;
     486             :     int         status;
     487        1558 :     char       *userDoption = NULL;
     488        1558 :     bool        listen_addr_saved = false;
     489        1558 :     char       *output_config_variable = NULL;
     490             : 
     491        1558 :     InitProcessGlobals();
     492             : 
     493        1558 :     PostmasterPid = MyProcPid;
     494             : 
     495        1558 :     IsPostmasterEnvironment = true;
     496             : 
     497             :     /*
     498             :      * Start our win32 signal implementation
     499             :      */
     500             : #ifdef WIN32
     501             :     pgwin32_signal_initialize();
     502             : #endif
     503             : 
     504             :     /*
     505             :      * We should not be creating any files or directories before we check the
     506             :      * data directory (see checkDataDir()), but just in case set the umask to
     507             :      * the most restrictive (owner-only) permissions.
     508             :      *
     509             :      * checkDataDir() will reset the umask based on the data directory
     510             :      * permissions.
     511             :      */
     512        1558 :     umask(PG_MODE_MASK_OWNER);
     513             : 
     514             :     /*
     515             :      * By default, palloc() requests in the postmaster will be allocated in
     516             :      * the PostmasterContext, which is space that can be recycled by backends.
     517             :      * Allocated data that needs to be available to backends should be
     518             :      * allocated in TopMemoryContext.
     519             :      */
     520        1558 :     PostmasterContext = AllocSetContextCreate(TopMemoryContext,
     521             :                                               "Postmaster",
     522             :                                               ALLOCSET_DEFAULT_SIZES);
     523        1558 :     MemoryContextSwitchTo(PostmasterContext);
     524             : 
     525             :     /* Initialize paths to installation files */
     526        1558 :     getInstallationPaths(argv[0]);
     527             : 
     528             :     /*
     529             :      * Set up signal handlers for the postmaster process.
     530             :      *
     531             :      * CAUTION: when changing this list, check for side-effects on the signal
     532             :      * handling setup of child processes.  See tcop/postgres.c,
     533             :      * bootstrap/bootstrap.c, postmaster/bgwriter.c, postmaster/walwriter.c,
     534             :      * postmaster/autovacuum.c, postmaster/pgarch.c, postmaster/syslogger.c,
     535             :      * postmaster/bgworker.c and postmaster/checkpointer.c.
     536             :      */
     537        1558 :     pqinitmask();
     538        1558 :     sigprocmask(SIG_SETMASK, &BlockSig, NULL);
     539             : 
     540        1558 :     pqsignal(SIGHUP, handle_pm_reload_request_signal);
     541        1558 :     pqsignal(SIGINT, handle_pm_shutdown_request_signal);
     542        1558 :     pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
     543        1558 :     pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
     544        1558 :     pqsignal(SIGALRM, SIG_IGN); /* ignored */
     545        1558 :     pqsignal(SIGPIPE, SIG_IGN); /* ignored */
     546        1558 :     pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
     547        1558 :     pqsignal(SIGUSR2, dummy_handler);   /* unused, reserve for children */
     548        1558 :     pqsignal(SIGCHLD, handle_pm_child_exit_signal);
     549             : 
     550             :     /* This may configure SIGURG, depending on platform. */
     551        1558 :     InitializeLatchSupport();
     552        1558 :     InitProcessLocalLatch();
     553             : 
     554             :     /*
     555             :      * No other place in Postgres should touch SIGTTIN/SIGTTOU handling.  We
     556             :      * ignore those signals in a postmaster environment, so that there is no
     557             :      * risk of a child process freezing up due to writing to stderr.  But for
     558             :      * a standalone backend, their default handling is reasonable.  Hence, all
     559             :      * child processes should just allow the inherited settings to stand.
     560             :      */
     561             : #ifdef SIGTTIN
     562        1558 :     pqsignal(SIGTTIN, SIG_IGN); /* ignored */
     563             : #endif
     564             : #ifdef SIGTTOU
     565        1558 :     pqsignal(SIGTTOU, SIG_IGN); /* ignored */
     566             : #endif
     567             : 
     568             :     /* ignore SIGXFSZ, so that ulimit violations work like disk full */
     569             : #ifdef SIGXFSZ
     570        1558 :     pqsignal(SIGXFSZ, SIG_IGN); /* ignored */
     571             : #endif
     572             : 
     573             :     /* Begin accepting signals. */
     574        1558 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
     575             : 
     576             :     /*
     577             :      * Options setup
     578             :      */
     579        1558 :     InitializeGUCOptions();
     580             : 
     581        1558 :     opterr = 1;
     582             : 
     583             :     /*
     584             :      * Parse command-line options.  CAUTION: keep this in sync with
     585             :      * tcop/postgres.c (the option sets should not conflict) and with the
     586             :      * common help() function in main/main.c.
     587             :      */
     588        5388 :     while ((opt = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:")) != -1)
     589             :     {
     590        3832 :         switch (opt)
     591             :         {
     592           0 :             case 'B':
     593           0 :                 SetConfigOption("shared_buffers", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     594           0 :                 break;
     595             : 
     596          44 :             case 'b':
     597             :                 /* Undocumented flag used for binary upgrades */
     598          44 :                 IsBinaryUpgrade = true;
     599          44 :                 break;
     600             : 
     601           4 :             case 'C':
     602           4 :                 output_config_variable = strdup(optarg);
     603           4 :                 break;
     604             : 
     605        1292 :             case '-':
     606             : 
     607             :                 /*
     608             :                  * Error if the user misplaced a special must-be-first option
     609             :                  * for dispatching to a subprogram.  parse_dispatch_option()
     610             :                  * returns DISPATCH_POSTMASTER if it doesn't find a match, so
     611             :                  * error for anything else.
     612             :                  */
     613        1292 :                 if (parse_dispatch_option(optarg) != DISPATCH_POSTMASTER)
     614           0 :                     ereport(ERROR,
     615             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     616             :                              errmsg("--%s must be first argument", optarg)));
     617             : 
     618             :                 /* FALLTHROUGH */
     619             :             case 'c':
     620             :                 {
     621             :                     char       *name,
     622             :                                *value;
     623             : 
     624        1812 :                     ParseLongOption(optarg, &name, &value);
     625        1812 :                     if (!value)
     626             :                     {
     627           2 :                         if (opt == '-')
     628           2 :                             ereport(ERROR,
     629             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
     630             :                                      errmsg("--%s requires a value",
     631             :                                             optarg)));
     632             :                         else
     633           0 :                             ereport(ERROR,
     634             :                                     (errcode(ERRCODE_SYNTAX_ERROR),
     635             :                                      errmsg("-c %s requires a value",
     636             :                                             optarg)));
     637             :                     }
     638             : 
     639        1810 :                     SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
     640        1810 :                     pfree(name);
     641        1810 :                     pfree(value);
     642        1810 :                     break;
     643             :                 }
     644             : 
     645        1556 :             case 'D':
     646        1556 :                 userDoption = strdup(optarg);
     647        1556 :                 break;
     648             : 
     649           0 :             case 'd':
     650           0 :                 set_debug_options(atoi(optarg), PGC_POSTMASTER, PGC_S_ARGV);
     651           0 :                 break;
     652             : 
     653           0 :             case 'E':
     654           0 :                 SetConfigOption("log_statement", "all", PGC_POSTMASTER, PGC_S_ARGV);
     655           0 :                 break;
     656             : 
     657           0 :             case 'e':
     658           0 :                 SetConfigOption("datestyle", "euro", PGC_POSTMASTER, PGC_S_ARGV);
     659           0 :                 break;
     660             : 
     661         176 :             case 'F':
     662         176 :                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
     663         176 :                 break;
     664             : 
     665           0 :             case 'f':
     666           0 :                 if (!set_plan_disabling_options(optarg, PGC_POSTMASTER, PGC_S_ARGV))
     667             :                 {
     668           0 :                     write_stderr("%s: invalid argument for option -f: \"%s\"\n",
     669             :                                  progname, optarg);
     670           0 :                     ExitPostmaster(1);
     671             :                 }
     672           0 :                 break;
     673             : 
     674           0 :             case 'h':
     675           0 :                 SetConfigOption("listen_addresses", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     676           0 :                 break;
     677             : 
     678           0 :             case 'i':
     679           0 :                 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
     680           0 :                 break;
     681             : 
     682           0 :             case 'j':
     683             :                 /* only used by interactive backend */
     684           0 :                 break;
     685             : 
     686         176 :             case 'k':
     687         176 :                 SetConfigOption("unix_socket_directories", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     688         176 :                 break;
     689             : 
     690           0 :             case 'l':
     691           0 :                 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
     692           0 :                 break;
     693             : 
     694           0 :             case 'N':
     695           0 :                 SetConfigOption("max_connections", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     696           0 :                 break;
     697             : 
     698           0 :             case 'O':
     699           0 :                 SetConfigOption("allow_system_table_mods", "true", PGC_POSTMASTER, PGC_S_ARGV);
     700           0 :                 break;
     701             : 
     702           0 :             case 'P':
     703           0 :                 SetConfigOption("ignore_system_indexes", "true", PGC_POSTMASTER, PGC_S_ARGV);
     704           0 :                 break;
     705             : 
     706          64 :             case 'p':
     707          64 :                 SetConfigOption("port", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     708          64 :                 break;
     709             : 
     710           0 :             case 'r':
     711             :                 /* only used by single-user backend */
     712           0 :                 break;
     713             : 
     714           0 :             case 'S':
     715           0 :                 SetConfigOption("work_mem", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     716           0 :                 break;
     717             : 
     718           0 :             case 's':
     719           0 :                 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
     720           0 :                 break;
     721             : 
     722           0 :             case 'T':
     723             : 
     724             :                 /*
     725             :                  * This option used to be defined as sending SIGSTOP after a
     726             :                  * backend crash, but sending SIGABRT seems more useful.
     727             :                  */
     728           0 :                 SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
     729           0 :                 break;
     730             : 
     731           0 :             case 't':
     732             :                 {
     733           0 :                     const char *tmp = get_stats_option_name(optarg);
     734             : 
     735           0 :                     if (tmp)
     736             :                     {
     737           0 :                         SetConfigOption(tmp, "true", PGC_POSTMASTER, PGC_S_ARGV);
     738             :                     }
     739             :                     else
     740             :                     {
     741           0 :                         write_stderr("%s: invalid argument for option -t: \"%s\"\n",
     742             :                                      progname, optarg);
     743           0 :                         ExitPostmaster(1);
     744             :                     }
     745           0 :                     break;
     746             :                 }
     747             : 
     748           0 :             case 'W':
     749           0 :                 SetConfigOption("post_auth_delay", optarg, PGC_POSTMASTER, PGC_S_ARGV);
     750           0 :                 break;
     751             : 
     752           0 :             default:
     753           0 :                 write_stderr("Try \"%s --help\" for more information.\n",
     754             :                              progname);
     755           0 :                 ExitPostmaster(1);
     756             :         }
     757             :     }
     758             : 
     759             :     /*
     760             :      * Postmaster accepts no non-option switch arguments.
     761             :      */
     762        1556 :     if (optind < argc)
     763             :     {
     764           0 :         write_stderr("%s: invalid argument: \"%s\"\n",
     765           0 :                      progname, argv[optind]);
     766           0 :         write_stderr("Try \"%s --help\" for more information.\n",
     767             :                      progname);
     768           0 :         ExitPostmaster(1);
     769             :     }
     770             : 
     771             :     /*
     772             :      * Locate the proper configuration files and data directory, and read
     773             :      * postgresql.conf for the first time.
     774             :      */
     775        1556 :     if (!SelectConfigFiles(userDoption, progname))
     776           0 :         ExitPostmaster(2);
     777             : 
     778        1554 :     if (output_config_variable != NULL)
     779             :     {
     780             :         /*
     781             :          * If this is a runtime-computed GUC, it hasn't yet been initialized,
     782             :          * and the present value is not useful.  However, this is a convenient
     783             :          * place to print the value for most GUCs because it is safe to run
     784             :          * postmaster startup to this point even if the server is already
     785             :          * running.  For the handful of runtime-computed GUCs that we cannot
     786             :          * provide meaningful values for yet, we wait until later in
     787             :          * postmaster startup to print the value.  We won't be able to use -C
     788             :          * on running servers for those GUCs, but using this option now would
     789             :          * lead to incorrect results for them.
     790             :          */
     791           4 :         int         flags = GetConfigOptionFlags(output_config_variable, true);
     792             : 
     793           4 :         if ((flags & GUC_RUNTIME_COMPUTED) == 0)
     794             :         {
     795             :             /*
     796             :              * "-C guc" was specified, so print GUC's value and exit.  No
     797             :              * extra permission check is needed because the user is reading
     798             :              * inside the data dir.
     799             :              */
     800           2 :             const char *config_val = GetConfigOption(output_config_variable,
     801             :                                                      false, false);
     802             : 
     803           2 :             puts(config_val ? config_val : "");
     804           2 :             ExitPostmaster(0);
     805             :         }
     806             : 
     807             :         /*
     808             :          * A runtime-computed GUC will be printed later on.  As we initialize
     809             :          * a server startup sequence, silence any log messages that may show
     810             :          * up in the output generated.  FATAL and more severe messages are
     811             :          * useful to show, even if one would only expect at least PANIC.  LOG
     812             :          * entries are hidden.
     813             :          */
     814           2 :         SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
     815             :                         PGC_S_OVERRIDE);
     816             :     }
     817             : 
     818             :     /* Verify that DataDir looks reasonable */
     819        1552 :     checkDataDir();
     820             : 
     821             :     /* Check that pg_control exists */
     822        1552 :     checkControlFile();
     823             : 
     824             :     /* And switch working directory into it */
     825        1552 :     ChangeToDataDir();
     826             : 
     827             :     /*
     828             :      * Check for invalid combinations of GUC settings.
     829             :      */
     830        1552 :     if (SuperuserReservedConnections + ReservedConnections >= MaxConnections)
     831             :     {
     832           0 :         write_stderr("%s: \"superuser_reserved_connections\" (%d) plus \"reserved_connections\" (%d) must be less than \"max_connections\" (%d)\n",
     833             :                      progname,
     834             :                      SuperuserReservedConnections, ReservedConnections,
     835             :                      MaxConnections);
     836           0 :         ExitPostmaster(1);
     837             :     }
     838        1552 :     if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL)
     839           0 :         ereport(ERROR,
     840             :                 (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
     841        1552 :     if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
     842           0 :         ereport(ERROR,
     843             :                 (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
     844        1552 :     if (summarize_wal && wal_level == WAL_LEVEL_MINIMAL)
     845           0 :         ereport(ERROR,
     846             :                 (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
     847             : 
     848             :     /*
     849             :      * Other one-time internal sanity checks can go here, if they are fast.
     850             :      * (Put any slow processing further down, after postmaster.pid creation.)
     851             :      */
     852        1552 :     if (!CheckDateTokenTables())
     853             :     {
     854           0 :         write_stderr("%s: invalid datetoken tables, please fix\n", progname);
     855           0 :         ExitPostmaster(1);
     856             :     }
     857             : 
     858             :     /*
     859             :      * Now that we are done processing the postmaster arguments, reset
     860             :      * getopt(3) library so that it will work correctly in subprocesses.
     861             :      */
     862        1552 :     optind = 1;
     863             : #ifdef HAVE_INT_OPTRESET
     864             :     optreset = 1;               /* some systems need this too */
     865             : #endif
     866             : 
     867             :     /* For debugging: display postmaster environment */
     868        1552 :     if (message_level_is_interesting(DEBUG3))
     869             :     {
     870             : #if !defined(WIN32) || defined(_MSC_VER)
     871             :         extern char **environ;
     872             : #endif
     873             :         char      **p;
     874             :         StringInfoData si;
     875             : 
     876           0 :         initStringInfo(&si);
     877             : 
     878           0 :         appendStringInfoString(&si, "initial environment dump:");
     879           0 :         for (p = environ; *p; ++p)
     880           0 :             appendStringInfo(&si, "\n%s", *p);
     881             : 
     882           0 :         ereport(DEBUG3, errmsg_internal("%s", si.data));
     883           0 :         pfree(si.data);
     884             :     }
     885             : 
     886             :     /*
     887             :      * Create lockfile for data directory.
     888             :      *
     889             :      * We want to do this before we try to grab the input sockets, because the
     890             :      * data directory interlock is more reliable than the socket-file
     891             :      * interlock (thanks to whoever decided to put socket files in /tmp :-().
     892             :      * For the same reason, it's best to grab the TCP socket(s) before the
     893             :      * Unix socket(s).
     894             :      *
     895             :      * Also note that this internally sets up the on_proc_exit function that
     896             :      * is responsible for removing both data directory and socket lockfiles;
     897             :      * so it must happen before opening sockets so that at exit, the socket
     898             :      * lockfiles go away after CloseServerPorts runs.
     899             :      */
     900        1552 :     CreateDataDirLockFile(true);
     901             : 
     902             :     /*
     903             :      * Read the control file (for error checking and config info).
     904             :      *
     905             :      * Since we verify the control file's CRC, this has a useful side effect
     906             :      * on machines where we need a run-time test for CRC support instructions.
     907             :      * The postmaster will do the test once at startup, and then its child
     908             :      * processes will inherit the correct function pointer and not need to
     909             :      * repeat the test.
     910             :      */
     911        1550 :     LocalProcessControlFile(false);
     912             : 
     913             :     /*
     914             :      * Register the apply launcher.  It's probably a good idea to call this
     915             :      * before any modules had a chance to take the background worker slots.
     916             :      */
     917        1550 :     ApplyLauncherRegister();
     918             : 
     919             :     /*
     920             :      * process any libraries that should be preloaded at postmaster start
     921             :      */
     922        1550 :     process_shared_preload_libraries();
     923             : 
     924             :     /*
     925             :      * Initialize SSL library, if specified.
     926             :      */
     927             : #ifdef USE_SSL
     928        1550 :     if (EnableSSL)
     929             :     {
     930          62 :         (void) secure_initialize(true);
     931          52 :         LoadedSSL = true;
     932             :     }
     933             : #endif
     934             : 
     935             :     /*
     936             :      * Now that loadable modules have had their chance to alter any GUCs,
     937             :      * calculate MaxBackends and initialize the machinery to track child
     938             :      * processes.
     939             :      */
     940        1540 :     InitializeMaxBackends();
     941        1540 :     InitPostmasterChildSlots();
     942             : 
     943             :     /*
     944             :      * Calculate the size of the PGPROC fast-path lock arrays.
     945             :      */
     946        1540 :     InitializeFastPathLocks();
     947             : 
     948             :     /*
     949             :      * Give preloaded libraries a chance to request additional shared memory.
     950             :      */
     951        1540 :     process_shmem_requests();
     952             : 
     953             :     /*
     954             :      * Now that loadable modules have had their chance to request additional
     955             :      * shared memory, determine the value of any runtime-computed GUCs that
     956             :      * depend on the amount of shared memory required.
     957             :      */
     958        1540 :     InitializeShmemGUCs();
     959             : 
     960             :     /*
     961             :      * Now that modules have been loaded, we can process any custom resource
     962             :      * managers specified in the wal_consistency_checking GUC.
     963             :      */
     964        1540 :     InitializeWalConsistencyChecking();
     965             : 
     966             :     /*
     967             :      * If -C was specified with a runtime-computed GUC, we held off printing
     968             :      * the value earlier, as the GUC was not yet initialized.  We handle -C
     969             :      * for most GUCs before we lock the data directory so that the option may
     970             :      * be used on a running server.  However, a handful of GUCs are runtime-
     971             :      * computed and do not have meaningful values until after locking the data
     972             :      * directory, and we cannot safely calculate their values earlier on a
     973             :      * running server.  At this point, such GUCs should be properly
     974             :      * initialized, and we haven't yet set up shared memory, so this is a good
     975             :      * time to handle the -C option for these special GUCs.
     976             :      */
     977        1540 :     if (output_config_variable != NULL)
     978             :     {
     979           2 :         const char *config_val = GetConfigOption(output_config_variable,
     980             :                                                  false, false);
     981             : 
     982           2 :         puts(config_val ? config_val : "");
     983           2 :         ExitPostmaster(0);
     984             :     }
     985             : 
     986             :     /*
     987             :      * Set up shared memory and semaphores.
     988             :      *
     989             :      * Note: if using SysV shmem and/or semas, each postmaster startup will
     990             :      * normally choose the same IPC keys.  This helps ensure that we will
     991             :      * clean up dead IPC objects if the postmaster crashes and is restarted.
     992             :      */
     993        1538 :     CreateSharedMemoryAndSemaphores();
     994             : 
     995             :     /*
     996             :      * Estimate number of openable files.  This must happen after setting up
     997             :      * semaphores, because on some platforms semaphores count as open files.
     998             :      */
     999        1536 :     set_max_safe_fds();
    1000             : 
    1001             :     /*
    1002             :      * Initialize pipe (or process handle on Windows) that allows children to
    1003             :      * wake up from sleep on postmaster death.
    1004             :      */
    1005        1536 :     InitPostmasterDeathWatchHandle();
    1006             : 
    1007             : #ifdef WIN32
    1008             : 
    1009             :     /*
    1010             :      * Initialize I/O completion port used to deliver list of dead children.
    1011             :      */
    1012             :     win32ChildQueue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
    1013             :     if (win32ChildQueue == NULL)
    1014             :         ereport(FATAL,
    1015             :                 (errmsg("could not create I/O completion port for child queue")));
    1016             : #endif
    1017             : 
    1018             : #ifdef EXEC_BACKEND
    1019             :     /* Write out nondefault GUC settings for child processes to use */
    1020             :     write_nondefault_variables(PGC_POSTMASTER);
    1021             : 
    1022             :     /*
    1023             :      * Clean out the temp directory used to transmit parameters to child
    1024             :      * processes (see internal_forkexec).  We must do this before launching
    1025             :      * any child processes, else we have a race condition: we could remove a
    1026             :      * parameter file before the child can read it.  It should be safe to do
    1027             :      * so now, because we verified earlier that there are no conflicting
    1028             :      * Postgres processes in this data directory.
    1029             :      */
    1030             :     RemovePgTempFilesInDir(PG_TEMP_FILES_DIR, true, false);
    1031             : #endif
    1032             : 
    1033             :     /*
    1034             :      * Forcibly remove the files signaling a standby promotion request.
    1035             :      * Otherwise, the existence of those files triggers a promotion too early,
    1036             :      * whether a user wants that or not.
    1037             :      *
    1038             :      * This removal of files is usually unnecessary because they can exist
    1039             :      * only during a few moments during a standby promotion. However there is
    1040             :      * a race condition: if pg_ctl promote is executed and creates the files
    1041             :      * during a promotion, the files can stay around even after the server is
    1042             :      * brought up to be the primary.  Then, if a new standby starts by using
    1043             :      * the backup taken from the new primary, the files can exist at server
    1044             :      * startup and must be removed in order to avoid an unexpected promotion.
    1045             :      *
    1046             :      * Note that promotion signal files need to be removed before the startup
    1047             :      * process is invoked. Because, after that, they can be used by
    1048             :      * postmaster's SIGUSR1 signal handler.
    1049             :      */
    1050        1536 :     RemovePromoteSignalFiles();
    1051             : 
    1052             :     /* Do the same for logrotate signal file */
    1053        1536 :     RemoveLogrotateSignalFiles();
    1054             : 
    1055             :     /* Remove any outdated file holding the current log filenames. */
    1056        1536 :     if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
    1057           0 :         ereport(LOG,
    1058             :                 (errcode_for_file_access(),
    1059             :                  errmsg("could not remove file \"%s\": %m",
    1060             :                         LOG_METAINFO_DATAFILE)));
    1061             : 
    1062             :     /*
    1063             :      * If enabled, start up syslogger collection subprocess
    1064             :      */
    1065        1536 :     if (Logging_collector)
    1066           2 :         StartSysLogger();
    1067             : 
    1068             :     /*
    1069             :      * Reset whereToSendOutput from DestDebug (its starting state) to
    1070             :      * DestNone. This stops ereport from sending log messages to stderr unless
    1071             :      * Log_destination permits.  We don't do this until the postmaster is
    1072             :      * fully launched, since startup failures may as well be reported to
    1073             :      * stderr.
    1074             :      *
    1075             :      * If we are in fact disabling logging to stderr, first emit a log message
    1076             :      * saying so, to provide a breadcrumb trail for users who may not remember
    1077             :      * that their logging is configured to go somewhere else.
    1078             :      */
    1079        1536 :     if (!(Log_destination & LOG_DESTINATION_STDERR))
    1080           0 :         ereport(LOG,
    1081             :                 (errmsg("ending log output to stderr"),
    1082             :                  errhint("Future log output will go to log destination \"%s\".",
    1083             :                          Log_destination_string)));
    1084             : 
    1085        1536 :     whereToSendOutput = DestNone;
    1086             : 
    1087             :     /*
    1088             :      * Report server startup in log.  While we could emit this much earlier,
    1089             :      * it seems best to do so after starting the log collector, if we intend
    1090             :      * to use one.
    1091             :      */
    1092        1536 :     ereport(LOG,
    1093             :             (errmsg("starting %s", PG_VERSION_STR)));
    1094             : 
    1095             :     /*
    1096             :      * Establish input sockets.
    1097             :      *
    1098             :      * First set up an on_proc_exit function that's charged with closing the
    1099             :      * sockets again at postmaster shutdown.
    1100             :      */
    1101        1536 :     ListenSockets = palloc(MAXLISTEN * sizeof(pgsocket));
    1102        1536 :     on_proc_exit(CloseServerPorts, 0);
    1103             : 
    1104        1536 :     if (ListenAddresses)
    1105             :     {
    1106             :         char       *rawstring;
    1107             :         List       *elemlist;
    1108             :         ListCell   *l;
    1109        1536 :         int         success = 0;
    1110             : 
    1111             :         /* Need a modifiable copy of ListenAddresses */
    1112        1536 :         rawstring = pstrdup(ListenAddresses);
    1113             : 
    1114             :         /* Parse string into list of hostnames */
    1115        1536 :         if (!SplitGUCList(rawstring, ',', &elemlist))
    1116             :         {
    1117             :             /* syntax error in list */
    1118           0 :             ereport(FATAL,
    1119             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1120             :                      errmsg("invalid list syntax in parameter \"%s\"",
    1121             :                             "listen_addresses")));
    1122             :         }
    1123             : 
    1124        1594 :         foreach(l, elemlist)
    1125             :         {
    1126          58 :             char       *curhost = (char *) lfirst(l);
    1127             : 
    1128          58 :             if (strcmp(curhost, "*") == 0)
    1129           0 :                 status = ListenServerPort(AF_UNSPEC, NULL,
    1130           0 :                                           (unsigned short) PostPortNumber,
    1131             :                                           NULL,
    1132             :                                           ListenSockets,
    1133             :                                           &NumListenSockets,
    1134             :                                           MAXLISTEN);
    1135             :             else
    1136          58 :                 status = ListenServerPort(AF_UNSPEC, curhost,
    1137          58 :                                           (unsigned short) PostPortNumber,
    1138             :                                           NULL,
    1139             :                                           ListenSockets,
    1140             :                                           &NumListenSockets,
    1141             :                                           MAXLISTEN);
    1142             : 
    1143          58 :             if (status == STATUS_OK)
    1144             :             {
    1145          58 :                 success++;
    1146             :                 /* record the first successful host addr in lockfile */
    1147          58 :                 if (!listen_addr_saved)
    1148             :                 {
    1149          58 :                     AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
    1150          58 :                     listen_addr_saved = true;
    1151             :                 }
    1152             :             }
    1153             :             else
    1154           0 :                 ereport(WARNING,
    1155             :                         (errmsg("could not create listen socket for \"%s\"",
    1156             :                                 curhost)));
    1157             :         }
    1158             : 
    1159        1536 :         if (!success && elemlist != NIL)
    1160           0 :             ereport(FATAL,
    1161             :                     (errmsg("could not create any TCP/IP sockets")));
    1162             : 
    1163        1536 :         list_free(elemlist);
    1164        1536 :         pfree(rawstring);
    1165             :     }
    1166             : 
    1167             : #ifdef USE_BONJOUR
    1168             :     /* Register for Bonjour only if we opened TCP socket(s) */
    1169             :     if (enable_bonjour && NumListenSockets > 0)
    1170             :     {
    1171             :         DNSServiceErrorType err;
    1172             : 
    1173             :         /*
    1174             :          * We pass 0 for interface_index, which will result in registering on
    1175             :          * all "applicable" interfaces.  It's not entirely clear from the
    1176             :          * DNS-SD docs whether this would be appropriate if we have bound to
    1177             :          * just a subset of the available network interfaces.
    1178             :          */
    1179             :         err = DNSServiceRegister(&bonjour_sdref,
    1180             :                                  0,
    1181             :                                  0,
    1182             :                                  bonjour_name,
    1183             :                                  "_postgresql._tcp.",
    1184             :                                  NULL,
    1185             :                                  NULL,
    1186             :                                  pg_hton16(PostPortNumber),
    1187             :                                  0,
    1188             :                                  NULL,
    1189             :                                  NULL,
    1190             :                                  NULL);
    1191             :         if (err != kDNSServiceErr_NoError)
    1192             :             ereport(LOG,
    1193             :                     (errmsg("DNSServiceRegister() failed: error code %ld",
    1194             :                             (long) err)));
    1195             : 
    1196             :         /*
    1197             :          * We don't bother to read the mDNS daemon's reply, and we expect that
    1198             :          * it will automatically terminate our registration when the socket is
    1199             :          * closed at postmaster termination.  So there's nothing more to be
    1200             :          * done here.  However, the bonjour_sdref is kept around so that
    1201             :          * forked children can close their copies of the socket.
    1202             :          */
    1203             :     }
    1204             : #endif
    1205             : 
    1206        1536 :     if (Unix_socket_directories)
    1207             :     {
    1208             :         char       *rawstring;
    1209             :         List       *elemlist;
    1210             :         ListCell   *l;
    1211        1536 :         int         success = 0;
    1212             : 
    1213             :         /* Need a modifiable copy of Unix_socket_directories */
    1214        1536 :         rawstring = pstrdup(Unix_socket_directories);
    1215             : 
    1216             :         /* Parse string into list of directories */
    1217        1536 :         if (!SplitDirectoriesString(rawstring, ',', &elemlist))
    1218             :         {
    1219             :             /* syntax error in list */
    1220           0 :             ereport(FATAL,
    1221             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1222             :                      errmsg("invalid list syntax in parameter \"%s\"",
    1223             :                             "unix_socket_directories")));
    1224             :         }
    1225             : 
    1226        3070 :         foreach(l, elemlist)
    1227             :         {
    1228        1534 :             char       *socketdir = (char *) lfirst(l);
    1229             : 
    1230        1534 :             status = ListenServerPort(AF_UNIX, NULL,
    1231        1534 :                                       (unsigned short) PostPortNumber,
    1232             :                                       socketdir,
    1233             :                                       ListenSockets,
    1234             :                                       &NumListenSockets,
    1235             :                                       MAXLISTEN);
    1236             : 
    1237        1534 :             if (status == STATUS_OK)
    1238             :             {
    1239        1534 :                 success++;
    1240             :                 /* record the first successful Unix socket in lockfile */
    1241        1534 :                 if (success == 1)
    1242        1534 :                     AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
    1243             :             }
    1244             :             else
    1245           0 :                 ereport(WARNING,
    1246             :                         (errmsg("could not create Unix-domain socket in directory \"%s\"",
    1247             :                                 socketdir)));
    1248             :         }
    1249             : 
    1250        1536 :         if (!success && elemlist != NIL)
    1251           0 :             ereport(FATAL,
    1252             :                     (errmsg("could not create any Unix-domain sockets")));
    1253             : 
    1254        1536 :         list_free_deep(elemlist);
    1255        1536 :         pfree(rawstring);
    1256             :     }
    1257             : 
    1258             :     /*
    1259             :      * check that we have some socket to listen on
    1260             :      */
    1261        1536 :     if (NumListenSockets == 0)
    1262           0 :         ereport(FATAL,
    1263             :                 (errmsg("no socket created for listening")));
    1264             : 
    1265             :     /*
    1266             :      * If no valid TCP ports, write an empty line for listen address,
    1267             :      * indicating the Unix socket must be used.  Note that this line is not
    1268             :      * added to the lock file until there is a socket backing it.
    1269             :      */
    1270        1536 :     if (!listen_addr_saved)
    1271        1478 :         AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, "");
    1272             : 
    1273             :     /*
    1274             :      * Record postmaster options.  We delay this till now to avoid recording
    1275             :      * bogus options (eg, unusable port number).
    1276             :      */
    1277        1536 :     if (!CreateOptsFile(argc, argv, my_exec_path))
    1278           0 :         ExitPostmaster(1);
    1279             : 
    1280             :     /*
    1281             :      * Write the external PID file if requested
    1282             :      */
    1283        1536 :     if (external_pid_file)
    1284             :     {
    1285           0 :         FILE       *fpidfile = fopen(external_pid_file, "w");
    1286             : 
    1287           0 :         if (fpidfile)
    1288             :         {
    1289           0 :             fprintf(fpidfile, "%d\n", MyProcPid);
    1290           0 :             fclose(fpidfile);
    1291             : 
    1292             :             /* Make PID file world readable */
    1293           0 :             if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
    1294           0 :                 write_stderr("%s: could not change permissions of external PID file \"%s\": %m\n",
    1295             :                              progname, external_pid_file);
    1296             :         }
    1297             :         else
    1298           0 :             write_stderr("%s: could not write external PID file \"%s\": %m\n",
    1299             :                          progname, external_pid_file);
    1300             : 
    1301           0 :         on_proc_exit(unlink_external_pid_file, 0);
    1302             :     }
    1303             : 
    1304             :     /*
    1305             :      * Remove old temporary files.  At this point there can be no other
    1306             :      * Postgres processes running in this directory, so this should be safe.
    1307             :      */
    1308        1536 :     RemovePgTempFiles();
    1309             : 
    1310             :     /*
    1311             :      * Initialize the autovacuum subsystem (again, no process start yet)
    1312             :      */
    1313        1536 :     autovac_init();
    1314             : 
    1315             :     /*
    1316             :      * Load configuration files for client authentication.
    1317             :      */
    1318        1536 :     if (!load_hba())
    1319             :     {
    1320             :         /*
    1321             :          * It makes no sense to continue if we fail to load the HBA file,
    1322             :          * since there is no way to connect to the database in this case.
    1323             :          */
    1324           0 :         ereport(FATAL,
    1325             :         /* translator: %s is a configuration file */
    1326             :                 (errmsg("could not load %s", HbaFileName)));
    1327             :     }
    1328        1536 :     if (!load_ident())
    1329             :     {
    1330             :         /*
    1331             :          * We can start up without the IDENT file, although it means that you
    1332             :          * cannot log in using any of the authentication methods that need a
    1333             :          * user name mapping. load_ident() already logged the details of error
    1334             :          * to the log.
    1335             :          */
    1336             :     }
    1337             : 
    1338             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
    1339             : 
    1340             :     /*
    1341             :      * On macOS, libintl replaces setlocale() with a version that calls
    1342             :      * CFLocaleCopyCurrent() when its second argument is "" and every relevant
    1343             :      * environment variable is unset or empty.  CFLocaleCopyCurrent() makes
    1344             :      * the process multithreaded.  The postmaster calls sigprocmask() and
    1345             :      * calls fork() without an immediate exec(), both of which have undefined
    1346             :      * behavior in a multithreaded program.  A multithreaded postmaster is the
    1347             :      * normal case on Windows, which offers neither fork() nor sigprocmask().
    1348             :      * Currently, macOS is the only platform having pthread_is_threaded_np(),
    1349             :      * so we need not worry whether this HINT is appropriate elsewhere.
    1350             :      */
    1351             :     if (pthread_is_threaded_np() != 0)
    1352             :         ereport(FATAL,
    1353             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1354             :                  errmsg("postmaster became multithreaded during startup"),
    1355             :                  errhint("Set the LC_ALL environment variable to a valid locale.")));
    1356             : #endif
    1357             : 
    1358             :     /*
    1359             :      * Remember postmaster startup time
    1360             :      */
    1361        1536 :     PgStartTime = GetCurrentTimestamp();
    1362             : 
    1363             :     /*
    1364             :      * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
    1365             :      * see what's happening.
    1366             :      */
    1367        1536 :     AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STARTING);
    1368             : 
    1369             :     /* Start bgwriter and checkpointer so they can help with recovery */
    1370        1536 :     if (CheckpointerPMChild == NULL)
    1371        1536 :         CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
    1372        1536 :     if (BgWriterPMChild == NULL)
    1373        1536 :         BgWriterPMChild = StartChildProcess(B_BG_WRITER);
    1374             : 
    1375             :     /*
    1376             :      * We're ready to rock and roll...
    1377             :      */
    1378        1536 :     StartupPMChild = StartChildProcess(B_STARTUP);
    1379             :     Assert(StartupPMChild != NULL);
    1380        1536 :     StartupStatus = STARTUP_RUNNING;
    1381        1536 :     UpdatePMState(PM_STARTUP);
    1382             : 
    1383             :     /* Some workers may be scheduled to start now */
    1384        1536 :     maybe_start_bgworkers();
    1385             : 
    1386        1536 :     status = ServerLoop();
    1387             : 
    1388             :     /*
    1389             :      * ServerLoop probably shouldn't ever return, but if it does, close down.
    1390             :      */
    1391           0 :     ExitPostmaster(status != STATUS_OK);
    1392             : 
    1393             :     abort();                    /* not reached */
    1394             : }
    1395             : 
    1396             : 
    1397             : /*
    1398             :  * on_proc_exit callback to close server's listen sockets
    1399             :  */
    1400             : static void
    1401        1530 : CloseServerPorts(int status, Datum arg)
    1402             : {
    1403             :     int         i;
    1404             : 
    1405             :     /*
    1406             :      * First, explicitly close all the socket FDs.  We used to just let this
    1407             :      * happen implicitly at postmaster exit, but it's better to close them
    1408             :      * before we remove the postmaster.pid lockfile; otherwise there's a race
    1409             :      * condition if a new postmaster wants to re-use the TCP port number.
    1410             :      */
    1411        3118 :     for (i = 0; i < NumListenSockets; i++)
    1412             :     {
    1413        1588 :         if (closesocket(ListenSockets[i]) != 0)
    1414           0 :             elog(LOG, "could not close listen socket: %m");
    1415             :     }
    1416        1530 :     NumListenSockets = 0;
    1417             : 
    1418             :     /*
    1419             :      * Next, remove any filesystem entries for Unix sockets.  To avoid race
    1420             :      * conditions against incoming postmasters, this must happen after closing
    1421             :      * the sockets and before removing lock files.
    1422             :      */
    1423        1530 :     RemoveSocketFiles();
    1424             : 
    1425             :     /*
    1426             :      * We don't do anything about socket lock files here; those will be
    1427             :      * removed in a later on_proc_exit callback.
    1428             :      */
    1429        1530 : }
    1430             : 
    1431             : /*
    1432             :  * on_proc_exit callback to delete external_pid_file
    1433             :  */
    1434             : static void
    1435           0 : unlink_external_pid_file(int status, Datum arg)
    1436             : {
    1437           0 :     if (external_pid_file)
    1438           0 :         unlink(external_pid_file);
    1439           0 : }
    1440             : 
    1441             : 
    1442             : /*
    1443             :  * Compute and check the directory paths to files that are part of the
    1444             :  * installation (as deduced from the postgres executable's own location)
    1445             :  */
    1446             : static void
    1447        1558 : getInstallationPaths(const char *argv0)
    1448             : {
    1449             :     DIR        *pdir;
    1450             : 
    1451             :     /* Locate the postgres executable itself */
    1452        1558 :     if (find_my_exec(argv0, my_exec_path) < 0)
    1453           0 :         ereport(FATAL,
    1454             :                 (errmsg("%s: could not locate my own executable path", argv0)));
    1455             : 
    1456             : #ifdef EXEC_BACKEND
    1457             :     /* Locate executable backend before we change working directory */
    1458             :     if (find_other_exec(argv0, "postgres", PG_BACKEND_VERSIONSTR,
    1459             :                         postgres_exec_path) < 0)
    1460             :         ereport(FATAL,
    1461             :                 (errmsg("%s: could not locate matching postgres executable",
    1462             :                         argv0)));
    1463             : #endif
    1464             : 
    1465             :     /*
    1466             :      * Locate the pkglib directory --- this has to be set early in case we try
    1467             :      * to load any modules from it in response to postgresql.conf entries.
    1468             :      */
    1469        1558 :     get_pkglib_path(my_exec_path, pkglib_path);
    1470             : 
    1471             :     /*
    1472             :      * Verify that there's a readable directory there; otherwise the Postgres
    1473             :      * installation is incomplete or corrupt.  (A typical cause of this
    1474             :      * failure is that the postgres executable has been moved or hardlinked to
    1475             :      * some directory that's not a sibling of the installation lib/
    1476             :      * directory.)
    1477             :      */
    1478        1558 :     pdir = AllocateDir(pkglib_path);
    1479        1558 :     if (pdir == NULL)
    1480           0 :         ereport(ERROR,
    1481             :                 (errcode_for_file_access(),
    1482             :                  errmsg("could not open directory \"%s\": %m",
    1483             :                         pkglib_path),
    1484             :                  errhint("This may indicate an incomplete PostgreSQL installation, or that the file \"%s\" has been moved away from its proper location.",
    1485             :                          my_exec_path)));
    1486        1558 :     FreeDir(pdir);
    1487             : 
    1488             :     /*
    1489             :      * It's not worth checking the share/ directory.  If the lib/ directory is
    1490             :      * there, then share/ probably is too.
    1491             :      */
    1492        1558 : }
    1493             : 
    1494             : /*
    1495             :  * Check that pg_control exists in the correct location in the data directory.
    1496             :  *
    1497             :  * No attempt is made to validate the contents of pg_control here.  This is
    1498             :  * just a sanity check to see if we are looking at a real data directory.
    1499             :  */
    1500             : static void
    1501        1552 : checkControlFile(void)
    1502             : {
    1503             :     char        path[MAXPGPATH];
    1504             :     FILE       *fp;
    1505             : 
    1506        1552 :     snprintf(path, sizeof(path), "%s/global/pg_control", DataDir);
    1507             : 
    1508        1552 :     fp = AllocateFile(path, PG_BINARY_R);
    1509        1552 :     if (fp == NULL)
    1510             :     {
    1511           0 :         write_stderr("%s: could not find the database system\n"
    1512             :                      "Expected to find it in the directory \"%s\",\n"
    1513             :                      "but could not open file \"%s\": %m\n",
    1514             :                      progname, DataDir, path);
    1515           0 :         ExitPostmaster(2);
    1516             :     }
    1517        1552 :     FreeFile(fp);
    1518        1552 : }
    1519             : 
    1520             : /*
    1521             :  * Determine how long should we let ServerLoop sleep, in milliseconds.
    1522             :  *
    1523             :  * In normal conditions we wait at most one minute, to ensure that the other
    1524             :  * background tasks handled by ServerLoop get done even when no requests are
    1525             :  * arriving.  However, if there are background workers waiting to be started,
    1526             :  * we don't actually sleep so that they are quickly serviced.  Other exception
    1527             :  * cases are as shown in the code.
    1528             :  */
    1529             : static int
    1530      245204 : DetermineSleepTime(void)
    1531             : {
    1532      245204 :     TimestampTz next_wakeup = 0;
    1533             : 
    1534             :     /*
    1535             :      * Normal case: either there are no background workers at all, or we're in
    1536             :      * a shutdown sequence (during which we ignore bgworkers altogether).
    1537             :      */
    1538      245204 :     if (Shutdown > NoShutdown ||
    1539      237440 :         (!StartWorkerNeeded && !HaveCrashedWorker))
    1540             :     {
    1541      245204 :         if (AbortStartTime != 0)
    1542             :         {
    1543             :             int         seconds;
    1544             : 
    1545             :             /* time left to abort; clamp to 0 in case it already expired */
    1546        2110 :             seconds = SIGKILL_CHILDREN_AFTER_SECS -
    1547        2110 :                 (time(NULL) - AbortStartTime);
    1548             : 
    1549        2110 :             return Max(seconds * 1000, 0);
    1550             :         }
    1551             :         else
    1552      243094 :             return 60 * 1000;
    1553             :     }
    1554             : 
    1555           0 :     if (StartWorkerNeeded)
    1556           0 :         return 0;
    1557             : 
    1558           0 :     if (HaveCrashedWorker)
    1559             :     {
    1560             :         dlist_mutable_iter iter;
    1561             : 
    1562             :         /*
    1563             :          * When there are crashed bgworkers, we sleep just long enough that
    1564             :          * they are restarted when they request to be.  Scan the list to
    1565             :          * determine the minimum of all wakeup times according to most recent
    1566             :          * crash time and requested restart interval.
    1567             :          */
    1568           0 :         dlist_foreach_modify(iter, &BackgroundWorkerList)
    1569             :         {
    1570             :             RegisteredBgWorker *rw;
    1571             :             TimestampTz this_wakeup;
    1572             : 
    1573           0 :             rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
    1574             : 
    1575           0 :             if (rw->rw_crashed_at == 0)
    1576           0 :                 continue;
    1577             : 
    1578           0 :             if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
    1579           0 :                 || rw->rw_terminate)
    1580             :             {
    1581           0 :                 ForgetBackgroundWorker(rw);
    1582           0 :                 continue;
    1583             :             }
    1584             : 
    1585           0 :             this_wakeup = TimestampTzPlusMilliseconds(rw->rw_crashed_at,
    1586             :                                                       1000L * rw->rw_worker.bgw_restart_time);
    1587           0 :             if (next_wakeup == 0 || this_wakeup < next_wakeup)
    1588           0 :                 next_wakeup = this_wakeup;
    1589             :         }
    1590             :     }
    1591             : 
    1592           0 :     if (next_wakeup != 0)
    1593             :     {
    1594             :         int         ms;
    1595             : 
    1596             :         /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
    1597           0 :         ms = (int) TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
    1598             :                                                    next_wakeup);
    1599           0 :         return Min(60 * 1000, ms);
    1600             :     }
    1601             : 
    1602           0 :     return 60 * 1000;
    1603             : }
    1604             : 
    1605             : /*
    1606             :  * Activate or deactivate notifications of server socket events.  Since we
    1607             :  * don't currently have a way to remove events from an existing WaitEventSet,
    1608             :  * we'll just destroy and recreate the whole thing.  This is called during
    1609             :  * shutdown so we can wait for backends to exit without accepting new
    1610             :  * connections, and during crash reinitialization when we need to start
    1611             :  * listening for new connections again.  The WaitEventSet will be freed in fork
    1612             :  * children by ClosePostmasterPorts().
    1613             :  */
    1614             : static void
    1615        3086 : ConfigurePostmasterWaitSet(bool accept_connections)
    1616             : {
    1617        3086 :     if (pm_wait_set)
    1618        1550 :         FreeWaitEventSet(pm_wait_set);
    1619        3086 :     pm_wait_set = NULL;
    1620             : 
    1621        4632 :     pm_wait_set = CreateWaitEventSet(NULL,
    1622        1546 :                                      accept_connections ? (1 + NumListenSockets) : 1);
    1623        3086 :     AddWaitEventToSet(pm_wait_set, WL_LATCH_SET, PGINVALID_SOCKET, MyLatch,
    1624             :                       NULL);
    1625             : 
    1626        3086 :     if (accept_connections)
    1627             :     {
    1628        3150 :         for (int i = 0; i < NumListenSockets; i++)
    1629        1604 :             AddWaitEventToSet(pm_wait_set, WL_SOCKET_ACCEPT, ListenSockets[i],
    1630             :                               NULL, NULL);
    1631             :     }
    1632        3086 : }
    1633             : 
    1634             : /*
    1635             :  * Main idle loop of postmaster
    1636             :  */
    1637             : static int
    1638        1536 : ServerLoop(void)
    1639             : {
    1640             :     time_t      last_lockfile_recheck_time,
    1641             :                 last_touch_time;
    1642             :     WaitEvent   events[MAXLISTEN];
    1643             :     int         nevents;
    1644             : 
    1645        1536 :     ConfigurePostmasterWaitSet(true);
    1646        1536 :     last_lockfile_recheck_time = last_touch_time = time(NULL);
    1647             : 
    1648             :     for (;;)
    1649      243668 :     {
    1650             :         time_t      now;
    1651             : 
    1652      245204 :         nevents = WaitEventSetWait(pm_wait_set,
    1653      245204 :                                    DetermineSleepTime(),
    1654             :                                    events,
    1655             :                                    lengthof(events),
    1656             :                                    0 /* postmaster posts no wait_events */ );
    1657             : 
    1658             :         /*
    1659             :          * Latch set by signal handler, or new connection pending on any of
    1660             :          * our sockets? If the latter, fork a child process to deal with it.
    1661             :          */
    1662      489718 :         for (int i = 0; i < nevents; i++)
    1663             :         {
    1664      246046 :             if (events[i].events & WL_LATCH_SET)
    1665      222522 :                 ResetLatch(MyLatch);
    1666             : 
    1667             :             /*
    1668             :              * The following requests are handled unconditionally, even if we
    1669             :              * didn't see WL_LATCH_SET.  This gives high priority to shutdown
    1670             :              * and reload requests where the latch happens to appear later in
    1671             :              * events[] or will be reported by a later call to
    1672             :              * WaitEventSetWait().
    1673             :              */
    1674      246046 :             if (pending_pm_shutdown_request)
    1675        1524 :                 process_pm_shutdown_request();
    1676      246046 :             if (pending_pm_reload_request)
    1677         250 :                 process_pm_reload_request();
    1678      246046 :             if (pending_pm_child_exit)
    1679       35802 :                 process_pm_child_exit();
    1680      244516 :             if (pending_pm_pmsignal)
    1681      185324 :                 process_pm_pmsignal();
    1682             : 
    1683      244516 :             if (events[i].events & WL_SOCKET_ACCEPT)
    1684             :             {
    1685             :                 ClientSocket s;
    1686             : 
    1687       23524 :                 if (AcceptConnection(events[i].fd, &s) == STATUS_OK)
    1688       23524 :                     BackendStartup(&s);
    1689             : 
    1690             :                 /* We no longer need the open socket in this process */
    1691       23522 :                 if (s.sock != PGINVALID_SOCKET)
    1692             :                 {
    1693       23522 :                     if (closesocket(s.sock) != 0)
    1694           0 :                         elog(LOG, "could not close client socket: %m");
    1695             :                 }
    1696             :             }
    1697             :         }
    1698             : 
    1699             :         /*
    1700             :          * If we need to launch any background processes after changing state
    1701             :          * or because some exited, do so now.
    1702             :          */
    1703      243672 :         LaunchMissingBackgroundProcesses();
    1704             : 
    1705             :         /* If we need to signal the autovacuum launcher, do so now */
    1706      243668 :         if (avlauncher_needs_signal)
    1707             :         {
    1708           0 :             avlauncher_needs_signal = false;
    1709           0 :             if (AutoVacLauncherPMChild != NULL)
    1710           0 :                 signal_child(AutoVacLauncherPMChild, SIGUSR2);
    1711             :         }
    1712             : 
    1713             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
    1714             : 
    1715             :         /*
    1716             :          * With assertions enabled, check regularly for appearance of
    1717             :          * additional threads.  All builds check at start and exit.
    1718             :          */
    1719             :         Assert(pthread_is_threaded_np() == 0);
    1720             : #endif
    1721             : 
    1722             :         /*
    1723             :          * Lastly, check to see if it's time to do some things that we don't
    1724             :          * want to do every single time through the loop, because they're a
    1725             :          * bit expensive.  Note that there's up to a minute of slop in when
    1726             :          * these tasks will be performed, since DetermineSleepTime() will let
    1727             :          * us sleep at most that long; except for SIGKILL timeout which has
    1728             :          * special-case logic there.
    1729             :          */
    1730      243668 :         now = time(NULL);
    1731             : 
    1732             :         /*
    1733             :          * If we already sent SIGQUIT to children and they are slow to shut
    1734             :          * down, it's time to send them SIGKILL (or SIGABRT if requested).
    1735             :          * This doesn't happen normally, but under certain conditions backends
    1736             :          * can get stuck while shutting down.  This is a last measure to get
    1737             :          * them unwedged.
    1738             :          *
    1739             :          * Note we also do this during recovery from a process crash.
    1740             :          */
    1741      243668 :         if ((Shutdown >= ImmediateShutdown || FatalError) &&
    1742        2120 :             AbortStartTime != 0 &&
    1743        2110 :             (now - AbortStartTime) >= SIGKILL_CHILDREN_AFTER_SECS)
    1744             :         {
    1745             :             /* We were gentle with them before. Not anymore */
    1746           0 :             ereport(LOG,
    1747             :             /* translator: %s is SIGKILL or SIGABRT */
    1748             :                     (errmsg("issuing %s to recalcitrant children",
    1749             :                             send_abort_for_kill ? "SIGABRT" : "SIGKILL")));
    1750           0 :             TerminateChildren(send_abort_for_kill ? SIGABRT : SIGKILL);
    1751             :             /* reset flag so we don't SIGKILL again */
    1752           0 :             AbortStartTime = 0;
    1753             :         }
    1754             : 
    1755             :         /*
    1756             :          * Once a minute, verify that postmaster.pid hasn't been removed or
    1757             :          * overwritten.  If it has, we force a shutdown.  This avoids having
    1758             :          * postmasters and child processes hanging around after their database
    1759             :          * is gone, and maybe causing problems if a new database cluster is
    1760             :          * created in the same place.  It also provides some protection
    1761             :          * against a DBA foolishly removing postmaster.pid and manually
    1762             :          * starting a new postmaster.  Data corruption is likely to ensue from
    1763             :          * that anyway, but we can minimize the damage by aborting ASAP.
    1764             :          */
    1765      243668 :         if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
    1766             :         {
    1767          26 :             if (!RecheckDataDirLockFile())
    1768             :             {
    1769           0 :                 ereport(LOG,
    1770             :                         (errmsg("performing immediate shutdown because data directory lock file is invalid")));
    1771           0 :                 kill(MyProcPid, SIGQUIT);
    1772             :             }
    1773          26 :             last_lockfile_recheck_time = now;
    1774             :         }
    1775             : 
    1776             :         /*
    1777             :          * Touch Unix socket and lock files every 58 minutes, to ensure that
    1778             :          * they are not removed by overzealous /tmp-cleaning tasks.  We assume
    1779             :          * no one runs cleaners with cutoff times of less than an hour ...
    1780             :          */
    1781      243668 :         if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
    1782             :         {
    1783           0 :             TouchSocketFiles();
    1784           0 :             TouchSocketLockFiles();
    1785           0 :             last_touch_time = now;
    1786             :         }
    1787             :     }
    1788             : }
    1789             : 
    1790             : /*
    1791             :  * canAcceptConnections --- check to see if database state allows connections
    1792             :  * of the specified type.  backend_type can be B_BACKEND or B_AUTOVAC_WORKER.
    1793             :  * (Note that we don't yet know whether a normal B_BACKEND connection might
    1794             :  * turn into a walsender.)
    1795             :  */
    1796             : static CAC_state
    1797       25768 : canAcceptConnections(BackendType backend_type)
    1798             : {
    1799       25768 :     CAC_state   result = CAC_OK;
    1800             : 
    1801             :     Assert(backend_type == B_BACKEND || backend_type == B_AUTOVAC_WORKER);
    1802             : 
    1803             :     /*
    1804             :      * Can't start backends when in startup/shutdown/inconsistent recovery
    1805             :      * state.  We treat autovac workers the same as user backends for this
    1806             :      * purpose.
    1807             :      */
    1808       25768 :     if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
    1809             :     {
    1810         220 :         if (Shutdown > NoShutdown)
    1811          10 :             return CAC_SHUTDOWN;    /* shutdown is pending */
    1812         210 :         else if (!FatalError && pmState == PM_STARTUP)
    1813         198 :             return CAC_STARTUP; /* normal startup */
    1814          12 :         else if (!FatalError && pmState == PM_RECOVERY)
    1815          12 :             return CAC_NOTCONSISTENT;   /* not yet at consistent recovery
    1816             :                                          * state */
    1817             :         else
    1818           0 :             return CAC_RECOVERY;    /* else must be crash recovery */
    1819             :     }
    1820             : 
    1821             :     /*
    1822             :      * "Smart shutdown" restrictions are applied only to normal connections,
    1823             :      * not to autovac workers.
    1824             :      */
    1825       25548 :     if (!connsAllowed && backend_type == B_BACKEND)
    1826           0 :         return CAC_SHUTDOWN;    /* shutdown is pending */
    1827             : 
    1828       25548 :     return result;
    1829             : }
    1830             : 
    1831             : /*
    1832             :  * ClosePostmasterPorts -- close all the postmaster's open sockets
    1833             :  *
    1834             :  * This is called during child process startup to release file descriptors
    1835             :  * that are not needed by that child process.  The postmaster still has
    1836             :  * them open, of course.
    1837             :  *
    1838             :  * Note: we pass am_syslogger as a boolean because we don't want to set
    1839             :  * the global variable yet when this is called.
    1840             :  */
    1841             : void
    1842       34822 : ClosePostmasterPorts(bool am_syslogger)
    1843             : {
    1844             :     /* Release resources held by the postmaster's WaitEventSet. */
    1845       34822 :     if (pm_wait_set)
    1846             :     {
    1847       31582 :         FreeWaitEventSetAfterFork(pm_wait_set);
    1848       31582 :         pm_wait_set = NULL;
    1849             :     }
    1850             : 
    1851             : #ifndef WIN32
    1852             : 
    1853             :     /*
    1854             :      * Close the write end of postmaster death watch pipe. It's important to
    1855             :      * do this as early as possible, so that if postmaster dies, others won't
    1856             :      * think that it's still running because we're holding the pipe open.
    1857             :      */
    1858       34822 :     if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]) != 0)
    1859           0 :         ereport(FATAL,
    1860             :                 (errcode_for_file_access(),
    1861             :                  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
    1862       34822 :     postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
    1863             :     /* Notify fd.c that we released one pipe FD. */
    1864       34822 :     ReleaseExternalFD();
    1865             : #endif
    1866             : 
    1867             :     /*
    1868             :      * Close the postmaster's listen sockets.  These aren't tracked by fd.c,
    1869             :      * so we don't call ReleaseExternalFD() here.
    1870             :      *
    1871             :      * The listen sockets are marked as FD_CLOEXEC, so this isn't needed in
    1872             :      * EXEC_BACKEND mode.
    1873             :      */
    1874             : #ifndef EXEC_BACKEND
    1875       34822 :     if (ListenSockets)
    1876             :     {
    1877       70554 :         for (int i = 0; i < NumListenSockets; i++)
    1878             :         {
    1879       35734 :             if (closesocket(ListenSockets[i]) != 0)
    1880           0 :                 elog(LOG, "could not close listen socket: %m");
    1881             :         }
    1882       34820 :         pfree(ListenSockets);
    1883             :     }
    1884       34822 :     NumListenSockets = 0;
    1885       34822 :     ListenSockets = NULL;
    1886             : #endif
    1887             : 
    1888             :     /*
    1889             :      * If using syslogger, close the read side of the pipe.  We don't bother
    1890             :      * tracking this in fd.c, either.
    1891             :      */
    1892       34822 :     if (!am_syslogger)
    1893             :     {
    1894             : #ifndef WIN32
    1895       34820 :         if (syslogPipe[0] >= 0)
    1896          28 :             close(syslogPipe[0]);
    1897       34820 :         syslogPipe[0] = -1;
    1898             : #else
    1899             :         if (syslogPipe[0])
    1900             :             CloseHandle(syslogPipe[0]);
    1901             :         syslogPipe[0] = 0;
    1902             : #endif
    1903             :     }
    1904             : 
    1905             : #ifdef USE_BONJOUR
    1906             :     /* If using Bonjour, close the connection to the mDNS daemon */
    1907             :     if (bonjour_sdref)
    1908             :         close(DNSServiceRefSockFD(bonjour_sdref));
    1909             : #endif
    1910       34822 : }
    1911             : 
    1912             : 
    1913             : /*
    1914             :  * InitProcessGlobals -- set MyStartTime[stamp], random seeds
    1915             :  *
    1916             :  * Called early in the postmaster and every backend.
    1917             :  */
    1918             : void
    1919       36812 : InitProcessGlobals(void)
    1920             : {
    1921       36812 :     MyStartTimestamp = GetCurrentTimestamp();
    1922       36812 :     MyStartTime = timestamptz_to_time_t(MyStartTimestamp);
    1923             : 
    1924             :     /*
    1925             :      * Set a different global seed in every process.  We want something
    1926             :      * unpredictable, so if possible, use high-quality random bits for the
    1927             :      * seed.  Otherwise, fall back to a seed based on timestamp and PID.
    1928             :      */
    1929       36812 :     if (unlikely(!pg_prng_strong_seed(&pg_global_prng_state)))
    1930             :     {
    1931             :         uint64      rseed;
    1932             : 
    1933             :         /*
    1934             :          * Since PIDs and timestamps tend to change more frequently in their
    1935             :          * least significant bits, shift the timestamp left to allow a larger
    1936             :          * total number of seeds in a given time period.  Since that would
    1937             :          * leave only 20 bits of the timestamp that cycle every ~1 second,
    1938             :          * also mix in some higher bits.
    1939             :          */
    1940           0 :         rseed = ((uint64) MyProcPid) ^
    1941           0 :             ((uint64) MyStartTimestamp << 12) ^
    1942           0 :             ((uint64) MyStartTimestamp >> 20);
    1943             : 
    1944           0 :         pg_prng_seed(&pg_global_prng_state, rseed);
    1945             :     }
    1946             : 
    1947             :     /*
    1948             :      * Also make sure that we've set a good seed for random(3).  Use of that
    1949             :      * is deprecated in core Postgres, but extensions might use it.
    1950             :      */
    1951             : #ifndef WIN32
    1952       36812 :     srandom(pg_prng_uint32(&pg_global_prng_state));
    1953             : #endif
    1954       36812 : }
    1955             : 
    1956             : /*
    1957             :  * Child processes use SIGUSR1 to notify us of 'pmsignals'.  pg_ctl uses
    1958             :  * SIGUSR1 to ask postmaster to check for logrotate and promote files.
    1959             :  */
    1960             : static void
    1961      185722 : handle_pm_pmsignal_signal(SIGNAL_ARGS)
    1962             : {
    1963      185722 :     pending_pm_pmsignal = true;
    1964      185722 :     SetLatch(MyLatch);
    1965      185722 : }
    1966             : 
    1967             : /*
    1968             :  * pg_ctl uses SIGHUP to request a reload of the configuration files.
    1969             :  */
    1970             : static void
    1971         250 : handle_pm_reload_request_signal(SIGNAL_ARGS)
    1972             : {
    1973         250 :     pending_pm_reload_request = true;
    1974         250 :     SetLatch(MyLatch);
    1975         250 : }
    1976             : 
    1977             : /*
    1978             :  * Re-read config files, and tell children to do same.
    1979             :  */
    1980             : static void
    1981         250 : process_pm_reload_request(void)
    1982             : {
    1983         250 :     pending_pm_reload_request = false;
    1984             : 
    1985         250 :     ereport(DEBUG2,
    1986             :             (errmsg_internal("postmaster received reload request signal")));
    1987             : 
    1988         250 :     if (Shutdown <= SmartShutdown)
    1989             :     {
    1990         250 :         ereport(LOG,
    1991             :                 (errmsg("received SIGHUP, reloading configuration files")));
    1992         250 :         ProcessConfigFile(PGC_SIGHUP);
    1993         250 :         SignalChildren(SIGHUP, btmask_all_except(B_DEAD_END_BACKEND));
    1994             : 
    1995             :         /* Reload authentication config files too */
    1996         250 :         if (!load_hba())
    1997           0 :             ereport(LOG,
    1998             :             /* translator: %s is a configuration file */
    1999             :                     (errmsg("%s was not reloaded", HbaFileName)));
    2000             : 
    2001         250 :         if (!load_ident())
    2002           0 :             ereport(LOG,
    2003             :                     (errmsg("%s was not reloaded", IdentFileName)));
    2004             : 
    2005             : #ifdef USE_SSL
    2006             :         /* Reload SSL configuration as well */
    2007         250 :         if (EnableSSL)
    2008             :         {
    2009           2 :             if (secure_initialize(false) == 0)
    2010           2 :                 LoadedSSL = true;
    2011             :             else
    2012           0 :                 ereport(LOG,
    2013             :                         (errmsg("SSL configuration was not reloaded")));
    2014             :         }
    2015             :         else
    2016             :         {
    2017         248 :             secure_destroy();
    2018         248 :             LoadedSSL = false;
    2019             :         }
    2020             : #endif
    2021             : 
    2022             : #ifdef EXEC_BACKEND
    2023             :         /* Update the starting-point file for future children */
    2024             :         write_nondefault_variables(PGC_SIGHUP);
    2025             : #endif
    2026             :     }
    2027         250 : }
    2028             : 
    2029             : /*
    2030             :  * pg_ctl uses SIGTERM, SIGINT and SIGQUIT to request different types of
    2031             :  * shutdown.
    2032             :  */
    2033             : static void
    2034        1524 : handle_pm_shutdown_request_signal(SIGNAL_ARGS)
    2035             : {
    2036        1524 :     switch (postgres_signal_arg)
    2037             :     {
    2038          34 :         case SIGTERM:
    2039             :             /* smart is implied if the other two flags aren't set */
    2040          34 :             pending_pm_shutdown_request = true;
    2041          34 :             break;
    2042         860 :         case SIGINT:
    2043         860 :             pending_pm_fast_shutdown_request = true;
    2044         860 :             pending_pm_shutdown_request = true;
    2045         860 :             break;
    2046         630 :         case SIGQUIT:
    2047         630 :             pending_pm_immediate_shutdown_request = true;
    2048         630 :             pending_pm_shutdown_request = true;
    2049         630 :             break;
    2050             :     }
    2051        1524 :     SetLatch(MyLatch);
    2052        1524 : }
    2053             : 
    2054             : /*
    2055             :  * Process shutdown request.
    2056             :  */
    2057             : static void
    2058        1524 : process_pm_shutdown_request(void)
    2059             : {
    2060             :     int         mode;
    2061             : 
    2062        1524 :     ereport(DEBUG2,
    2063             :             (errmsg_internal("postmaster received shutdown request signal")));
    2064             : 
    2065        1524 :     pending_pm_shutdown_request = false;
    2066             : 
    2067             :     /*
    2068             :      * If more than one shutdown request signal arrived since the last server
    2069             :      * loop, take the one that is the most immediate.  That matches the
    2070             :      * priority that would apply if we processed them one by one in any order.
    2071             :      */
    2072        1524 :     if (pending_pm_immediate_shutdown_request)
    2073             :     {
    2074         630 :         pending_pm_immediate_shutdown_request = false;
    2075         630 :         pending_pm_fast_shutdown_request = false;
    2076         630 :         mode = ImmediateShutdown;
    2077             :     }
    2078         894 :     else if (pending_pm_fast_shutdown_request)
    2079             :     {
    2080         860 :         pending_pm_fast_shutdown_request = false;
    2081         860 :         mode = FastShutdown;
    2082             :     }
    2083             :     else
    2084          34 :         mode = SmartShutdown;
    2085             : 
    2086        1524 :     switch (mode)
    2087             :     {
    2088          34 :         case SmartShutdown:
    2089             : 
    2090             :             /*
    2091             :              * Smart Shutdown:
    2092             :              *
    2093             :              * Wait for children to end their work, then shut down.
    2094             :              */
    2095          34 :             if (Shutdown >= SmartShutdown)
    2096           0 :                 break;
    2097          34 :             Shutdown = SmartShutdown;
    2098          34 :             ereport(LOG,
    2099             :                     (errmsg("received smart shutdown request")));
    2100             : 
    2101             :             /* Report status */
    2102          34 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
    2103             : #ifdef USE_SYSTEMD
    2104             :             sd_notify(0, "STOPPING=1");
    2105             : #endif
    2106             : 
    2107             :             /*
    2108             :              * If we reached normal running, we go straight to waiting for
    2109             :              * client backends to exit.  If already in PM_STOP_BACKENDS or a
    2110             :              * later state, do not change it.
    2111             :              */
    2112          34 :             if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
    2113          34 :                 connsAllowed = false;
    2114           0 :             else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
    2115             :             {
    2116             :                 /* There should be no clients, so proceed to stop children */
    2117           0 :                 UpdatePMState(PM_STOP_BACKENDS);
    2118             :             }
    2119             : 
    2120             :             /*
    2121             :              * Now wait for online backup mode to end and backends to exit. If
    2122             :              * that is already the case, PostmasterStateMachine will take the
    2123             :              * next step.
    2124             :              */
    2125          34 :             PostmasterStateMachine();
    2126          34 :             break;
    2127             : 
    2128         860 :         case FastShutdown:
    2129             : 
    2130             :             /*
    2131             :              * Fast Shutdown:
    2132             :              *
    2133             :              * Abort all children with SIGTERM (rollback active transactions
    2134             :              * and exit) and shut down when they are gone.
    2135             :              */
    2136         860 :             if (Shutdown >= FastShutdown)
    2137           0 :                 break;
    2138         860 :             Shutdown = FastShutdown;
    2139         860 :             ereport(LOG,
    2140             :                     (errmsg("received fast shutdown request")));
    2141             : 
    2142             :             /* Report status */
    2143         860 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
    2144             : #ifdef USE_SYSTEMD
    2145             :             sd_notify(0, "STOPPING=1");
    2146             : #endif
    2147             : 
    2148         860 :             if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
    2149             :             {
    2150             :                 /* Just shut down background processes silently */
    2151           0 :                 UpdatePMState(PM_STOP_BACKENDS);
    2152             :             }
    2153         860 :             else if (pmState == PM_RUN ||
    2154         100 :                      pmState == PM_HOT_STANDBY)
    2155             :             {
    2156             :                 /* Report that we're about to zap live client sessions */
    2157         860 :                 ereport(LOG,
    2158             :                         (errmsg("aborting any active transactions")));
    2159         860 :                 UpdatePMState(PM_STOP_BACKENDS);
    2160             :             }
    2161             : 
    2162             :             /*
    2163             :              * PostmasterStateMachine will issue any necessary signals, or
    2164             :              * take the next step if no child processes need to be killed.
    2165             :              */
    2166         860 :             PostmasterStateMachine();
    2167         860 :             break;
    2168             : 
    2169         630 :         case ImmediateShutdown:
    2170             : 
    2171             :             /*
    2172             :              * Immediate Shutdown:
    2173             :              *
    2174             :              * abort all children with SIGQUIT, wait for them to exit,
    2175             :              * terminate remaining ones with SIGKILL, then exit without
    2176             :              * attempt to properly shut down the data base system.
    2177             :              */
    2178         630 :             if (Shutdown >= ImmediateShutdown)
    2179           0 :                 break;
    2180         630 :             Shutdown = ImmediateShutdown;
    2181         630 :             ereport(LOG,
    2182             :                     (errmsg("received immediate shutdown request")));
    2183             : 
    2184             :             /* Report status */
    2185         630 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
    2186             : #ifdef USE_SYSTEMD
    2187             :             sd_notify(0, "STOPPING=1");
    2188             : #endif
    2189             : 
    2190             :             /* tell children to shut down ASAP */
    2191             :             /* (note we don't apply send_abort_for_crash here) */
    2192         630 :             SetQuitSignalReason(PMQUIT_FOR_STOP);
    2193         630 :             TerminateChildren(SIGQUIT);
    2194         630 :             UpdatePMState(PM_WAIT_BACKENDS);
    2195             : 
    2196             :             /* set stopwatch for them to die */
    2197         630 :             AbortStartTime = time(NULL);
    2198             : 
    2199             :             /*
    2200             :              * Now wait for backends to exit.  If there are none,
    2201             :              * PostmasterStateMachine will take the next step.
    2202             :              */
    2203         630 :             PostmasterStateMachine();
    2204         630 :             break;
    2205             :     }
    2206        1524 : }
    2207             : 
    2208             : static void
    2209       36050 : handle_pm_child_exit_signal(SIGNAL_ARGS)
    2210             : {
    2211       36050 :     pending_pm_child_exit = true;
    2212       36050 :     SetLatch(MyLatch);
    2213       36050 : }
    2214             : 
    2215             : /*
    2216             :  * Cleanup after a child process dies.
    2217             :  */
    2218             : static void
    2219       35802 : process_pm_child_exit(void)
    2220             : {
    2221             :     int         pid;            /* process id of dead child process */
    2222             :     int         exitstatus;     /* its exit status */
    2223             : 
    2224       35802 :     pending_pm_child_exit = false;
    2225             : 
    2226       35802 :     ereport(DEBUG4,
    2227             :             (errmsg_internal("reaping dead processes")));
    2228             : 
    2229       74172 :     while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
    2230             :     {
    2231             :         PMChild    *pmchild;
    2232             : 
    2233             :         /*
    2234             :          * Check if this child was a startup process.
    2235             :          */
    2236       38370 :         if (StartupPMChild && pid == StartupPMChild->pid)
    2237             :         {
    2238        1546 :             ReleasePostmasterChildSlot(StartupPMChild);
    2239        1546 :             StartupPMChild = NULL;
    2240             : 
    2241             :             /*
    2242             :              * Startup process exited in response to a shutdown request (or it
    2243             :              * completed normally regardless of the shutdown request).
    2244             :              */
    2245        1546 :             if (Shutdown > NoShutdown &&
    2246         190 :                 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
    2247             :             {
    2248         100 :                 StartupStatus = STARTUP_NOT_RUNNING;
    2249         100 :                 UpdatePMState(PM_WAIT_BACKENDS);
    2250             :                 /* PostmasterStateMachine logic does the rest */
    2251         100 :                 continue;
    2252             :             }
    2253             : 
    2254        1446 :             if (EXIT_STATUS_3(exitstatus))
    2255             :             {
    2256           0 :                 ereport(LOG,
    2257             :                         (errmsg("shutdown at recovery target")));
    2258           0 :                 StartupStatus = STARTUP_NOT_RUNNING;
    2259           0 :                 Shutdown = Max(Shutdown, SmartShutdown);
    2260           0 :                 TerminateChildren(SIGTERM);
    2261           0 :                 UpdatePMState(PM_WAIT_BACKENDS);
    2262             :                 /* PostmasterStateMachine logic does the rest */
    2263           0 :                 continue;
    2264             :             }
    2265             : 
    2266             :             /*
    2267             :              * Unexpected exit of startup process (including FATAL exit)
    2268             :              * during PM_STARTUP is treated as catastrophic. There are no
    2269             :              * other processes running yet, so we can just exit.
    2270             :              */
    2271        1446 :             if (pmState == PM_STARTUP &&
    2272        1062 :                 StartupStatus != STARTUP_SIGNALED &&
    2273        1062 :                 !EXIT_STATUS_0(exitstatus))
    2274             :             {
    2275           0 :                 LogChildExit(LOG, _("startup process"),
    2276             :                              pid, exitstatus);
    2277           0 :                 ereport(LOG,
    2278             :                         (errmsg("aborting startup due to startup process failure")));
    2279           0 :                 ExitPostmaster(1);
    2280             :             }
    2281             : 
    2282             :             /*
    2283             :              * After PM_STARTUP, any unexpected exit (including FATAL exit) of
    2284             :              * the startup process is catastrophic, so kill other children,
    2285             :              * and set StartupStatus so we don't try to reinitialize after
    2286             :              * they're gone.  Exception: if StartupStatus is STARTUP_SIGNALED,
    2287             :              * then we previously sent the startup process a SIGQUIT; so
    2288             :              * that's probably the reason it died, and we do want to try to
    2289             :              * restart in that case.
    2290             :              *
    2291             :              * This stanza also handles the case where we sent a SIGQUIT
    2292             :              * during PM_STARTUP due to some dead-end child crashing: in that
    2293             :              * situation, if the startup process dies on the SIGQUIT, we need
    2294             :              * to transition to PM_WAIT_BACKENDS state which will allow
    2295             :              * PostmasterStateMachine to restart the startup process.  (On the
    2296             :              * other hand, the startup process might complete normally, if we
    2297             :              * were too late with the SIGQUIT.  In that case we'll fall
    2298             :              * through and commence normal operations.)
    2299             :              */
    2300        1446 :             if (!EXIT_STATUS_0(exitstatus))
    2301             :             {
    2302          96 :                 if (StartupStatus == STARTUP_SIGNALED)
    2303             :                 {
    2304          90 :                     StartupStatus = STARTUP_NOT_RUNNING;
    2305          90 :                     if (pmState == PM_STARTUP)
    2306           0 :                         UpdatePMState(PM_WAIT_BACKENDS);
    2307             :                 }
    2308             :                 else
    2309           6 :                     StartupStatus = STARTUP_CRASHED;
    2310          96 :                 HandleChildCrash(pid, exitstatus,
    2311          96 :                                  _("startup process"));
    2312          96 :                 continue;
    2313             :             }
    2314             : 
    2315             :             /*
    2316             :              * Startup succeeded, commence normal operations
    2317             :              */
    2318        1350 :             StartupStatus = STARTUP_NOT_RUNNING;
    2319        1350 :             FatalError = false;
    2320        1350 :             AbortStartTime = 0;
    2321        1350 :             ReachedNormalRunning = true;
    2322        1350 :             UpdatePMState(PM_RUN);
    2323        1350 :             connsAllowed = true;
    2324             : 
    2325             :             /*
    2326             :              * At the next iteration of the postmaster's main loop, we will
    2327             :              * crank up the background tasks like the autovacuum launcher and
    2328             :              * background workers that were not started earlier already.
    2329             :              */
    2330        1350 :             StartWorkerNeeded = true;
    2331             : 
    2332             :             /* at this point we are really open for business */
    2333        1350 :             ereport(LOG,
    2334             :                     (errmsg("database system is ready to accept connections")));
    2335             : 
    2336             :             /* Report status */
    2337        1350 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
    2338             : #ifdef USE_SYSTEMD
    2339             :             sd_notify(0, "READY=1");
    2340             : #endif
    2341             : 
    2342        1350 :             continue;
    2343             :         }
    2344             : 
    2345             :         /*
    2346             :          * Was it the bgwriter?  Normal exit can be ignored; we'll start a new
    2347             :          * one at the next iteration of the postmaster's main loop, if
    2348             :          * necessary.  Any other exit condition is treated as a crash.
    2349             :          */
    2350       36824 :         if (BgWriterPMChild && pid == BgWriterPMChild->pid)
    2351             :         {
    2352        1540 :             ReleasePostmasterChildSlot(BgWriterPMChild);
    2353        1540 :             BgWriterPMChild = NULL;
    2354        1540 :             if (!EXIT_STATUS_0(exitstatus))
    2355         646 :                 HandleChildCrash(pid, exitstatus,
    2356         646 :                                  _("background writer process"));
    2357        1540 :             continue;
    2358             :         }
    2359             : 
    2360             :         /*
    2361             :          * Was it the checkpointer?
    2362             :          */
    2363       35284 :         if (CheckpointerPMChild && pid == CheckpointerPMChild->pid)
    2364             :         {
    2365        1540 :             ReleasePostmasterChildSlot(CheckpointerPMChild);
    2366        1540 :             CheckpointerPMChild = NULL;
    2367        1540 :             if (EXIT_STATUS_0(exitstatus) && pmState == PM_WAIT_CHECKPOINTER)
    2368         894 :             {
    2369             :                 /*
    2370             :                  * OK, we saw normal exit of the checkpointer after it's been
    2371             :                  * told to shut down.  We know checkpointer wrote a shutdown
    2372             :                  * checkpoint, otherwise we'd still be in
    2373             :                  * PM_WAIT_XLOG_SHUTDOWN state.
    2374             :                  *
    2375             :                  * At this point only dead-end children and logger should be
    2376             :                  * left.
    2377             :                  */
    2378         894 :                 UpdatePMState(PM_WAIT_DEAD_END);
    2379         894 :                 ConfigurePostmasterWaitSet(false);
    2380         894 :                 SignalChildren(SIGTERM, btmask_all_except(B_LOGGER));
    2381             :             }
    2382             :             else
    2383             :             {
    2384             :                 /*
    2385             :                  * Any unexpected exit of the checkpointer (including FATAL
    2386             :                  * exit) is treated as a crash.
    2387             :                  */
    2388         646 :                 HandleChildCrash(pid, exitstatus,
    2389         646 :                                  _("checkpointer process"));
    2390             :             }
    2391             : 
    2392        1540 :             continue;
    2393             :         }
    2394             : 
    2395             :         /*
    2396             :          * Was it the wal writer?  Normal exit can be ignored; we'll start a
    2397             :          * new one at the next iteration of the postmaster's main loop, if
    2398             :          * necessary.  Any other exit condition is treated as a crash.
    2399             :          */
    2400       33744 :         if (WalWriterPMChild && pid == WalWriterPMChild->pid)
    2401             :         {
    2402        1344 :             ReleasePostmasterChildSlot(WalWriterPMChild);
    2403        1344 :             WalWriterPMChild = NULL;
    2404        1344 :             if (!EXIT_STATUS_0(exitstatus))
    2405         550 :                 HandleChildCrash(pid, exitstatus,
    2406         550 :                                  _("WAL writer process"));
    2407        1344 :             continue;
    2408             :         }
    2409             : 
    2410             :         /*
    2411             :          * Was it the wal receiver?  If exit status is zero (normal) or one
    2412             :          * (FATAL exit), we assume everything is all right just like normal
    2413             :          * backends.  (If we need a new wal receiver, we'll start one at the
    2414             :          * next iteration of the postmaster's main loop.)
    2415             :          */
    2416       32400 :         if (WalReceiverPMChild && pid == WalReceiverPMChild->pid)
    2417             :         {
    2418         462 :             ReleasePostmasterChildSlot(WalReceiverPMChild);
    2419         462 :             WalReceiverPMChild = NULL;
    2420         462 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    2421          34 :                 HandleChildCrash(pid, exitstatus,
    2422          34 :                                  _("WAL receiver process"));
    2423         462 :             continue;
    2424             :         }
    2425             : 
    2426             :         /*
    2427             :          * Was it the wal summarizer? Normal exit can be ignored; we'll start
    2428             :          * a new one at the next iteration of the postmaster's main loop, if
    2429             :          * necessary.  Any other exit condition is treated as a crash.
    2430             :          */
    2431       31938 :         if (WalSummarizerPMChild && pid == WalSummarizerPMChild->pid)
    2432             :         {
    2433          36 :             ReleasePostmasterChildSlot(WalSummarizerPMChild);
    2434          36 :             WalSummarizerPMChild = NULL;
    2435          36 :             if (!EXIT_STATUS_0(exitstatus))
    2436          34 :                 HandleChildCrash(pid, exitstatus,
    2437          34 :                                  _("WAL summarizer process"));
    2438          36 :             continue;
    2439             :         }
    2440             : 
    2441             :         /*
    2442             :          * Was it the autovacuum launcher?  Normal exit can be ignored; we'll
    2443             :          * start a new one at the next iteration of the postmaster's main
    2444             :          * loop, if necessary.  Any other exit condition is treated as a
    2445             :          * crash.
    2446             :          */
    2447       31902 :         if (AutoVacLauncherPMChild && pid == AutoVacLauncherPMChild->pid)
    2448             :         {
    2449        1162 :             ReleasePostmasterChildSlot(AutoVacLauncherPMChild);
    2450        1162 :             AutoVacLauncherPMChild = NULL;
    2451        1162 :             if (!EXIT_STATUS_0(exitstatus))
    2452         468 :                 HandleChildCrash(pid, exitstatus,
    2453         468 :                                  _("autovacuum launcher process"));
    2454        1162 :             continue;
    2455             :         }
    2456             : 
    2457             :         /*
    2458             :          * Was it the archiver?  If exit status is zero (normal) or one (FATAL
    2459             :          * exit), we assume everything is all right just like normal backends
    2460             :          * and just try to start a new one on the next cycle of the
    2461             :          * postmaster's main loop, to retry archiving remaining files.
    2462             :          */
    2463       30740 :         if (PgArchPMChild && pid == PgArchPMChild->pid)
    2464             :         {
    2465         106 :             ReleasePostmasterChildSlot(PgArchPMChild);
    2466         106 :             PgArchPMChild = NULL;
    2467         106 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    2468          78 :                 HandleChildCrash(pid, exitstatus,
    2469          78 :                                  _("archiver process"));
    2470         106 :             continue;
    2471             :         }
    2472             : 
    2473             :         /* Was it the system logger?  If so, try to start a new one */
    2474       30634 :         if (SysLoggerPMChild && pid == SysLoggerPMChild->pid)
    2475             :         {
    2476           0 :             ReleasePostmasterChildSlot(SysLoggerPMChild);
    2477           0 :             SysLoggerPMChild = NULL;
    2478             : 
    2479             :             /* for safety's sake, launch new logger *first* */
    2480           0 :             if (Logging_collector)
    2481           0 :                 StartSysLogger();
    2482             : 
    2483           0 :             if (!EXIT_STATUS_0(exitstatus))
    2484           0 :                 LogChildExit(LOG, _("system logger process"),
    2485             :                              pid, exitstatus);
    2486           0 :             continue;
    2487             :         }
    2488             : 
    2489             :         /*
    2490             :          * Was it the slot sync worker? Normal exit or FATAL exit can be
    2491             :          * ignored (FATAL can be caused by libpqwalreceiver on receiving
    2492             :          * shutdown request by the startup process during promotion); we'll
    2493             :          * start a new one at the next iteration of the postmaster's main
    2494             :          * loop, if necessary. Any other exit condition is treated as a crash.
    2495             :          */
    2496       30634 :         if (SlotSyncWorkerPMChild && pid == SlotSyncWorkerPMChild->pid)
    2497             :         {
    2498           8 :             ReleasePostmasterChildSlot(SlotSyncWorkerPMChild);
    2499           8 :             SlotSyncWorkerPMChild = NULL;
    2500           8 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    2501           0 :                 HandleChildCrash(pid, exitstatus,
    2502           0 :                                  _("slot sync worker process"));
    2503           8 :             continue;
    2504             :         }
    2505             : 
    2506             :         /*
    2507             :          * Was it a backend or a background worker?
    2508             :          */
    2509       30626 :         pmchild = FindPostmasterChildByPid(pid);
    2510       30626 :         if (pmchild)
    2511             :         {
    2512       30626 :             CleanupBackend(pmchild, exitstatus);
    2513             :         }
    2514             : 
    2515             :         /*
    2516             :          * We don't know anything about this child process.  That's highly
    2517             :          * unexpected, as we do track all the child processes that we fork.
    2518             :          */
    2519             :         else
    2520             :         {
    2521           0 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    2522           0 :                 HandleChildCrash(pid, exitstatus, _("untracked child process"));
    2523             :             else
    2524           0 :                 LogChildExit(LOG, _("untracked child process"), pid, exitstatus);
    2525             :         }
    2526             :     }                           /* loop over pending child-death reports */
    2527             : 
    2528             :     /*
    2529             :      * After cleaning out the SIGCHLD queue, see if we have any state changes
    2530             :      * or actions to make.
    2531             :      */
    2532       35802 :     PostmasterStateMachine();
    2533       34272 : }
    2534             : 
    2535             : /*
    2536             :  * CleanupBackend -- cleanup after terminated backend or background worker.
    2537             :  *
    2538             :  * Remove all local state associated with the child process and release its
    2539             :  * PMChild slot.
    2540             :  */
    2541             : static void
    2542       30626 : CleanupBackend(PMChild *bp,
    2543             :                int exitstatus)  /* child's exit status. */
    2544             : {
    2545             :     char        namebuf[MAXPGPATH];
    2546             :     const char *procname;
    2547       30626 :     bool        crashed = false;
    2548       30626 :     bool        logged = false;
    2549             :     pid_t       bp_pid;
    2550             :     bool        bp_bgworker_notify;
    2551             :     BackendType bp_bkend_type;
    2552             :     RegisteredBgWorker *rw;
    2553             : 
    2554             :     /* Construct a process name for the log message */
    2555       30626 :     if (bp->bkend_type == B_BG_WORKER)
    2556             :     {
    2557        4864 :         snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
    2558        4864 :                  bp->rw->rw_worker.bgw_type);
    2559        4864 :         procname = namebuf;
    2560             :     }
    2561             :     else
    2562       25762 :         procname = _(GetBackendTypeDesc(bp->bkend_type));
    2563             : 
    2564             :     /*
    2565             :      * If a backend dies in an ugly way then we must signal all other backends
    2566             :      * to quickdie.  If exit status is zero (normal) or one (FATAL exit), we
    2567             :      * assume everything is all right and proceed to remove the backend from
    2568             :      * the active child list.
    2569             :      */
    2570       30626 :     if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
    2571        1054 :         crashed = true;
    2572             : 
    2573             : #ifdef WIN32
    2574             : 
    2575             :     /*
    2576             :      * On win32, also treat ERROR_WAIT_NO_CHILDREN (128) as nonfatal case,
    2577             :      * since that sometimes happens under load when the process fails to start
    2578             :      * properly (long before it starts using shared memory). Microsoft reports
    2579             :      * it is related to mutex failure:
    2580             :      * http://archives.postgresql.org/pgsql-hackers/2010-09/msg00790.php
    2581             :      */
    2582             :     if (exitstatus == ERROR_WAIT_NO_CHILDREN)
    2583             :     {
    2584             :         LogChildExit(LOG, procname, bp->pid, exitstatus);
    2585             :         logged = true;
    2586             :         crashed = false;
    2587             :     }
    2588             : #endif
    2589             : 
    2590             :     /*
    2591             :      * Release the PMChild entry.
    2592             :      *
    2593             :      * If the process attached to shared memory, this also checks that it
    2594             :      * detached cleanly.
    2595             :      */
    2596       30626 :     bp_pid = bp->pid;
    2597       30626 :     bp_bgworker_notify = bp->bgworker_notify;
    2598       30626 :     bp_bkend_type = bp->bkend_type;
    2599       30626 :     rw = bp->rw;
    2600       30626 :     if (!ReleasePostmasterChildSlot(bp))
    2601             :     {
    2602             :         /*
    2603             :          * Uh-oh, the child failed to clean itself up.  Treat as a crash after
    2604             :          * all.
    2605             :          */
    2606         690 :         crashed = true;
    2607             :     }
    2608       30626 :     bp = NULL;
    2609             : 
    2610       30626 :     if (crashed)
    2611             :     {
    2612        1054 :         HandleChildCrash(bp_pid, exitstatus, procname);
    2613        1054 :         return;
    2614             :     }
    2615             : 
    2616             :     /*
    2617             :      * This backend may have been slated to receive SIGUSR1 when some
    2618             :      * background worker started or stopped.  Cancel those notifications, as
    2619             :      * we don't want to signal PIDs that are not PostgreSQL backends.  This
    2620             :      * gets skipped in the (probably very common) case where the backend has
    2621             :      * never requested any such notifications.
    2622             :      */
    2623       29572 :     if (bp_bgworker_notify)
    2624         472 :         BackgroundWorkerStopNotifications(bp_pid);
    2625             : 
    2626             :     /*
    2627             :      * If it was a background worker, also update its RegisteredBgWorker
    2628             :      * entry.
    2629             :      */
    2630       29572 :     if (bp_bkend_type == B_BG_WORKER)
    2631             :     {
    2632        4284 :         if (!EXIT_STATUS_0(exitstatus))
    2633             :         {
    2634             :             /* Record timestamp, so we know when to restart the worker. */
    2635        1128 :             rw->rw_crashed_at = GetCurrentTimestamp();
    2636             :         }
    2637             :         else
    2638             :         {
    2639             :             /* Zero exit status means terminate */
    2640        3156 :             rw->rw_crashed_at = 0;
    2641        3156 :             rw->rw_terminate = true;
    2642             :         }
    2643             : 
    2644        4284 :         rw->rw_pid = 0;
    2645        4284 :         ReportBackgroundWorkerExit(rw); /* report child death */
    2646             : 
    2647        4284 :         if (!logged)
    2648             :         {
    2649        4284 :             LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
    2650             :                          procname, bp_pid, exitstatus);
    2651        4284 :             logged = true;
    2652             :         }
    2653             : 
    2654             :         /* have it be restarted */
    2655        4284 :         HaveCrashedWorker = true;
    2656             :     }
    2657             : 
    2658       29572 :     if (!logged)
    2659       25288 :         LogChildExit(DEBUG2, procname, bp_pid, exitstatus);
    2660             : }
    2661             : 
    2662             : /*
    2663             :  * Transition into FatalError state, in response to something bad having
    2664             :  * happened. Commonly the caller will have logged the reason for entering
    2665             :  * FatalError state.
    2666             :  *
    2667             :  * This should only be called when not already in FatalError or
    2668             :  * ImmediateShutdown state.
    2669             :  */
    2670             : static void
    2671          16 : HandleFatalError(QuitSignalReason reason, bool consider_sigabrt)
    2672             : {
    2673             :     int         sigtosend;
    2674             : 
    2675             :     Assert(!FatalError);
    2676             :     Assert(Shutdown != ImmediateShutdown);
    2677             : 
    2678          16 :     SetQuitSignalReason(reason);
    2679             : 
    2680          16 :     if (consider_sigabrt && send_abort_for_crash)
    2681           0 :         sigtosend = SIGABRT;
    2682             :     else
    2683          16 :         sigtosend = SIGQUIT;
    2684             : 
    2685             :     /*
    2686             :      * Signal all other child processes to exit.
    2687             :      *
    2688             :      * We could exclude dead-end children here, but at least when sending
    2689             :      * SIGABRT it seems better to include them.
    2690             :      */
    2691          16 :     TerminateChildren(sigtosend);
    2692             : 
    2693          16 :     FatalError = true;
    2694             : 
    2695             :     /*
    2696             :      * Choose the appropriate new state to react to the fatal error. Unless we
    2697             :      * were already in the process of shutting down, we go through
    2698             :      * PM_WAIT_BACKEND. For errors during the shutdown sequence, we directly
    2699             :      * switch to PM_WAIT_DEAD_END.
    2700             :      */
    2701          16 :     switch (pmState)
    2702             :     {
    2703           0 :         case PM_INIT:
    2704             :             /* shouldn't have any children */
    2705             :             Assert(false);
    2706           0 :             break;
    2707           0 :         case PM_STARTUP:
    2708             :             /* should have been handled in process_pm_child_exit */
    2709             :             Assert(false);
    2710           0 :             break;
    2711             : 
    2712             :             /* wait for children to die */
    2713          16 :         case PM_RECOVERY:
    2714             :         case PM_HOT_STANDBY:
    2715             :         case PM_RUN:
    2716             :         case PM_STOP_BACKENDS:
    2717          16 :             UpdatePMState(PM_WAIT_BACKENDS);
    2718          16 :             break;
    2719             : 
    2720           0 :         case PM_WAIT_BACKENDS:
    2721             :             /* there might be more backends to wait for */
    2722           0 :             break;
    2723             : 
    2724           0 :         case PM_WAIT_XLOG_SHUTDOWN:
    2725             :         case PM_WAIT_XLOG_ARCHIVAL:
    2726             :         case PM_WAIT_CHECKPOINTER:
    2727             : 
    2728             :             /*
    2729             :              * NB: Similar code exists in PostmasterStateMachine()'s handling
    2730             :              * of FatalError in PM_STOP_BACKENDS/PM_WAIT_BACKENDS states.
    2731             :              */
    2732           0 :             ConfigurePostmasterWaitSet(false);
    2733           0 :             UpdatePMState(PM_WAIT_DEAD_END);
    2734           0 :             break;
    2735             : 
    2736           0 :         case PM_WAIT_DEAD_END:
    2737             :         case PM_NO_CHILDREN:
    2738           0 :             break;
    2739             :     }
    2740             : 
    2741             :     /*
    2742             :      * .. and if this doesn't happen quickly enough, now the clock is ticking
    2743             :      * for us to kill them without mercy.
    2744             :      */
    2745          16 :     if (AbortStartTime == 0)
    2746          16 :         AbortStartTime = time(NULL);
    2747          16 : }
    2748             : 
    2749             : /*
    2750             :  * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
    2751             :  * walwriter, autovacuum, archiver, slot sync worker, or background worker.
    2752             :  *
    2753             :  * The objectives here are to clean up our local state about the child
    2754             :  * process, and to signal all other remaining children to quickdie.
    2755             :  *
    2756             :  * The caller has already released its PMChild slot.
    2757             :  */
    2758             : static void
    2759        3606 : HandleChildCrash(int pid, int exitstatus, const char *procname)
    2760             : {
    2761             :     /*
    2762             :      * We only log messages and send signals if this is the first process
    2763             :      * crash and we're not doing an immediate shutdown; otherwise, we're only
    2764             :      * here to update postmaster's idea of live processes.  If we have already
    2765             :      * signaled children, nonzero exit status is to be expected, so don't
    2766             :      * clutter log.
    2767             :      */
    2768        3606 :     if (FatalError || Shutdown == ImmediateShutdown)
    2769        3590 :         return;
    2770             : 
    2771          16 :     LogChildExit(LOG, procname, pid, exitstatus);
    2772          16 :     ereport(LOG,
    2773             :             (errmsg("terminating any other active server processes")));
    2774             : 
    2775             :     /*
    2776             :      * Switch into error state. The crashed process has already been removed
    2777             :      * from ActiveChildList.
    2778             :      */
    2779          16 :     HandleFatalError(PMQUIT_FOR_CRASH, true);
    2780             : }
    2781             : 
    2782             : /*
    2783             :  * Log the death of a child process.
    2784             :  */
    2785             : static void
    2786       29588 : LogChildExit(int lev, const char *procname, int pid, int exitstatus)
    2787             : {
    2788             :     /*
    2789             :      * size of activity_buffer is arbitrary, but set equal to default
    2790             :      * track_activity_query_size
    2791             :      */
    2792             :     char        activity_buffer[1024];
    2793       29588 :     const char *activity = NULL;
    2794             : 
    2795       29588 :     if (!EXIT_STATUS_0(exitstatus))
    2796        1646 :         activity = pgstat_get_crashed_backend_activity(pid,
    2797             :                                                        activity_buffer,
    2798             :                                                        sizeof(activity_buffer));
    2799             : 
    2800       29588 :     if (WIFEXITED(exitstatus))
    2801       29580 :         ereport(lev,
    2802             : 
    2803             :         /*------
    2804             :           translator: %s is a noun phrase describing a child process, such as
    2805             :           "server process" */
    2806             :                 (errmsg("%s (PID %d) exited with exit code %d",
    2807             :                         procname, pid, WEXITSTATUS(exitstatus)),
    2808             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    2809           8 :     else if (WIFSIGNALED(exitstatus))
    2810             :     {
    2811             : #if defined(WIN32)
    2812             :         ereport(lev,
    2813             : 
    2814             :         /*------
    2815             :           translator: %s is a noun phrase describing a child process, such as
    2816             :           "server process" */
    2817             :                 (errmsg("%s (PID %d) was terminated by exception 0x%X",
    2818             :                         procname, pid, WTERMSIG(exitstatus)),
    2819             :                  errhint("See C include file \"ntstatus.h\" for a description of the hexadecimal value."),
    2820             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    2821             : #else
    2822           8 :         ereport(lev,
    2823             : 
    2824             :         /*------
    2825             :           translator: %s is a noun phrase describing a child process, such as
    2826             :           "server process" */
    2827             :                 (errmsg("%s (PID %d) was terminated by signal %d: %s",
    2828             :                         procname, pid, WTERMSIG(exitstatus),
    2829             :                         pg_strsignal(WTERMSIG(exitstatus))),
    2830             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    2831             : #endif
    2832             :     }
    2833             :     else
    2834           0 :         ereport(lev,
    2835             : 
    2836             :         /*------
    2837             :           translator: %s is a noun phrase describing a child process, such as
    2838             :           "server process" */
    2839             :                 (errmsg("%s (PID %d) exited with unrecognized status %d",
    2840             :                         procname, pid, exitstatus),
    2841             :                  activity ? errdetail("Failed process was running: %s", activity) : 0));
    2842       29588 : }
    2843             : 
    2844             : /*
    2845             :  * Advance the postmaster's state machine and take actions as appropriate
    2846             :  *
    2847             :  * This is common code for process_pm_shutdown_request(),
    2848             :  * process_pm_child_exit() and process_pm_pmsignal(), which process the signals
    2849             :  * that might mean we need to change state.
    2850             :  */
    2851             : static void
    2852       40444 : PostmasterStateMachine(void)
    2853             : {
    2854             :     /* If we're doing a smart shutdown, try to advance that state. */
    2855       40444 :     if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
    2856             :     {
    2857       31136 :         if (!connsAllowed)
    2858             :         {
    2859             :             /*
    2860             :              * This state ends when we have no normal client backends running.
    2861             :              * Then we're ready to stop other children.
    2862             :              */
    2863          68 :             if (CountChildren(btmask(B_BACKEND)) == 0)
    2864          34 :                 UpdatePMState(PM_STOP_BACKENDS);
    2865             :         }
    2866             :     }
    2867             : 
    2868             :     /*
    2869             :      * In the PM_WAIT_BACKENDS state, wait for all the regular backends and
    2870             :      * processes like autovacuum and background workers that are comparable to
    2871             :      * backends to exit.
    2872             :      *
    2873             :      * PM_STOP_BACKENDS is a transient state that means the same as
    2874             :      * PM_WAIT_BACKENDS, but we signal the processes first, before waiting for
    2875             :      * them.  Treating it as a distinct pmState allows us to share this code
    2876             :      * across multiple shutdown code paths.
    2877             :      */
    2878       40444 :     if (pmState == PM_STOP_BACKENDS || pmState == PM_WAIT_BACKENDS)
    2879             :     {
    2880        7396 :         BackendTypeMask targetMask = BTYPE_MASK_NONE;
    2881             : 
    2882             :         /*
    2883             :          * PM_WAIT_BACKENDS state ends when we have no regular backends, no
    2884             :          * autovac launcher or workers, and no bgworkers (including
    2885             :          * unconnected ones).
    2886             :          */
    2887        7396 :         targetMask = btmask_add(targetMask,
    2888             :                                 B_BACKEND,
    2889             :                                 B_AUTOVAC_LAUNCHER,
    2890             :                                 B_AUTOVAC_WORKER,
    2891             :                                 B_BG_WORKER);
    2892             : 
    2893             :         /*
    2894             :          * No walwriter, bgwriter, slot sync worker, or WAL summarizer either.
    2895             :          */
    2896        7396 :         targetMask = btmask_add(targetMask,
    2897             :                                 B_WAL_WRITER,
    2898             :                                 B_BG_WRITER,
    2899             :                                 B_SLOTSYNC_WORKER,
    2900             :                                 B_WAL_SUMMARIZER);
    2901             : 
    2902             :         /* If we're in recovery, also stop startup and walreceiver procs */
    2903        7396 :         targetMask = btmask_add(targetMask,
    2904             :                                 B_STARTUP,
    2905             :                                 B_WAL_RECEIVER);
    2906             : 
    2907             :         /*
    2908             :          * If we are doing crash recovery or an immediate shutdown then we
    2909             :          * expect archiver, checkpointer and walsender to exit as well,
    2910             :          * otherwise not.
    2911             :          */
    2912        7396 :         if (FatalError || Shutdown >= ImmediateShutdown)
    2913        2764 :             targetMask = btmask_add(targetMask,
    2914             :                                     B_CHECKPOINTER,
    2915             :                                     B_ARCHIVER,
    2916             :                                     B_WAL_SENDER);
    2917             : 
    2918             :         /*
    2919             :          * Normally walsenders and archiver will continue running; they will
    2920             :          * be terminated later after writing the checkpoint record.  We also
    2921             :          * let dead-end children to keep running for now.  The syslogger
    2922             :          * process exits last.
    2923             :          *
    2924             :          * This assertion checks that we have covered all backend types,
    2925             :          * either by including them in targetMask, or by noting here that they
    2926             :          * are allowed to continue running.
    2927             :          */
    2928             : #ifdef USE_ASSERT_CHECKING
    2929             :         {
    2930             :             BackendTypeMask remainMask = BTYPE_MASK_NONE;
    2931             : 
    2932             :             remainMask = btmask_add(remainMask,
    2933             :                                     B_DEAD_END_BACKEND,
    2934             :                                     B_LOGGER);
    2935             : 
    2936             :             /*
    2937             :              * Archiver, checkpointer and walsender may or may not be in
    2938             :              * targetMask already.
    2939             :              */
    2940             :             remainMask = btmask_add(remainMask,
    2941             :                                     B_ARCHIVER,
    2942             :                                     B_CHECKPOINTER,
    2943             :                                     B_WAL_SENDER);
    2944             : 
    2945             :             /* these are not real postmaster children */
    2946             :             remainMask = btmask_add(remainMask,
    2947             :                                     B_INVALID,
    2948             :                                     B_STANDALONE_BACKEND);
    2949             : 
    2950             :             /* All types should be included in targetMask or remainMask */
    2951             :             Assert((remainMask.mask | targetMask.mask) == BTYPE_MASK_ALL.mask);
    2952             :         }
    2953             : #endif
    2954             : 
    2955             :         /* If we had not yet signaled the processes to exit, do so now */
    2956        7396 :         if (pmState == PM_STOP_BACKENDS)
    2957             :         {
    2958             :             /*
    2959             :              * Forget any pending requests for background workers, since we're
    2960             :              * no longer willing to launch any new workers.  (If additional
    2961             :              * requests arrive, BackgroundWorkerStateChange will reject them.)
    2962             :              */
    2963         894 :             ForgetUnstartedBackgroundWorkers();
    2964             : 
    2965         894 :             SignalChildren(SIGTERM, targetMask);
    2966             : 
    2967         894 :             UpdatePMState(PM_WAIT_BACKENDS);
    2968             :         }
    2969             : 
    2970             :         /* Are any of the target processes still running? */
    2971        7396 :         if (CountChildren(targetMask) == 0)
    2972             :         {
    2973        1540 :             if (Shutdown >= ImmediateShutdown || FatalError)
    2974             :             {
    2975             :                 /*
    2976             :                  * Stop any dead-end children and stop creating new ones.
    2977             :                  *
    2978             :                  * NB: Similar code exists in HandleFatalErrors(), when the
    2979             :                  * error happens in pmState > PM_WAIT_BACKENDS.
    2980             :                  */
    2981         646 :                 UpdatePMState(PM_WAIT_DEAD_END);
    2982         646 :                 ConfigurePostmasterWaitSet(false);
    2983         646 :                 SignalChildren(SIGQUIT, btmask(B_DEAD_END_BACKEND));
    2984             : 
    2985             :                 /*
    2986             :                  * We already SIGQUIT'd auxiliary processes (other than
    2987             :                  * logger), if any, when we started immediate shutdown or
    2988             :                  * entered FatalError state.
    2989             :                  */
    2990             :             }
    2991             :             else
    2992             :             {
    2993             :                 /*
    2994             :                  * If we get here, we are proceeding with normal shutdown. All
    2995             :                  * the regular children are gone, and it's time to tell the
    2996             :                  * checkpointer to do a shutdown checkpoint.
    2997             :                  */
    2998             :                 Assert(Shutdown > NoShutdown);
    2999             :                 /* Start the checkpointer if not running */
    3000         894 :                 if (CheckpointerPMChild == NULL)
    3001           0 :                     CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
    3002             :                 /* And tell it to write the shutdown checkpoint */
    3003         894 :                 if (CheckpointerPMChild != NULL)
    3004             :                 {
    3005         894 :                     signal_child(CheckpointerPMChild, SIGINT);
    3006         894 :                     UpdatePMState(PM_WAIT_XLOG_SHUTDOWN);
    3007             :                 }
    3008             :                 else
    3009             :                 {
    3010             :                     /*
    3011             :                      * If we failed to fork a checkpointer, just shut down.
    3012             :                      * Any required cleanup will happen at next restart. We
    3013             :                      * set FatalError so that an "abnormal shutdown" message
    3014             :                      * gets logged when we exit.
    3015             :                      *
    3016             :                      * We don't consult send_abort_for_crash here, as it's
    3017             :                      * unlikely that dumping cores would illuminate the reason
    3018             :                      * for checkpointer fork failure.
    3019             :                      *
    3020             :                      * XXX: It may be worth to introduce a different PMQUIT
    3021             :                      * value that signals that the cluster is in a bad state,
    3022             :                      * without a process having crashed. But right now this
    3023             :                      * path is very unlikely to be reached, so it isn't
    3024             :                      * obviously worthwhile adding a distinct error message in
    3025             :                      * quickdie().
    3026             :                      */
    3027           0 :                     HandleFatalError(PMQUIT_FOR_CRASH, false);
    3028             :                 }
    3029             :             }
    3030             :         }
    3031             :     }
    3032             : 
    3033             :     /*
    3034             :      * The state transition from PM_WAIT_XLOG_SHUTDOWN to
    3035             :      * PM_WAIT_XLOG_ARCHIVAL is in process_pm_pmsignal(), in response to
    3036             :      * PMSIGNAL_XLOG_IS_SHUTDOWN.
    3037             :      */
    3038             : 
    3039       40444 :     if (pmState == PM_WAIT_XLOG_ARCHIVAL)
    3040             :     {
    3041             :         /*
    3042             :          * PM_WAIT_XLOG_ARCHIVAL state ends when there are no children other
    3043             :          * than checkpointer, dead-end children and logger left. There
    3044             :          * shouldn't be any regular backends left by now anyway; what we're
    3045             :          * really waiting for is for walsenders and archiver to exit.
    3046             :          */
    3047         984 :         if (CountChildren(btmask_all_except(B_CHECKPOINTER, B_LOGGER, B_DEAD_END_BACKEND)) == 0)
    3048             :         {
    3049         894 :             UpdatePMState(PM_WAIT_CHECKPOINTER);
    3050             : 
    3051             :             /*
    3052             :              * Now that the processes mentioned above are gone, tell
    3053             :              * checkpointer to shut down too. That allows checkpointer to
    3054             :              * perform some last bits of cleanup without other processes
    3055             :              * interfering.
    3056             :              */
    3057         894 :             if (CheckpointerPMChild != NULL)
    3058         894 :                 signal_child(CheckpointerPMChild, SIGUSR2);
    3059             :         }
    3060             :     }
    3061             : 
    3062             :     /*
    3063             :      * The state transition from PM_WAIT_CHECKPOINTER to PM_WAIT_DEAD_END is
    3064             :      * in process_pm_child_exit().
    3065             :      */
    3066             : 
    3067       40444 :     if (pmState == PM_WAIT_DEAD_END)
    3068             :     {
    3069             :         /*
    3070             :          * PM_WAIT_DEAD_END state ends when all other children are gone except
    3071             :          * for the logger.  During normal shutdown, all that remains are
    3072             :          * dead-end backends, but in FatalError processing we jump straight
    3073             :          * here with more processes remaining.  Note that they have already
    3074             :          * been sent appropriate shutdown signals, either during a normal
    3075             :          * state transition leading up to PM_WAIT_DEAD_END, or during
    3076             :          * FatalError processing.
    3077             :          *
    3078             :          * The reason we wait is to protect against a new postmaster starting
    3079             :          * conflicting subprocesses; this isn't an ironclad protection, but it
    3080             :          * at least helps in the shutdown-and-immediately-restart scenario.
    3081             :          */
    3082        1556 :         if (CountChildren(btmask_all_except(B_LOGGER)) == 0)
    3083             :         {
    3084             :             /* These other guys should be dead already */
    3085             :             Assert(StartupPMChild == NULL);
    3086             :             Assert(WalReceiverPMChild == NULL);
    3087             :             Assert(WalSummarizerPMChild == NULL);
    3088             :             Assert(BgWriterPMChild == NULL);
    3089             :             Assert(CheckpointerPMChild == NULL);
    3090             :             Assert(WalWriterPMChild == NULL);
    3091             :             Assert(AutoVacLauncherPMChild == NULL);
    3092             :             Assert(SlotSyncWorkerPMChild == NULL);
    3093             :             /* syslogger is not considered here */
    3094        1540 :             UpdatePMState(PM_NO_CHILDREN);
    3095             :         }
    3096             :     }
    3097             : 
    3098             :     /*
    3099             :      * If we've been told to shut down, we exit as soon as there are no
    3100             :      * remaining children.  If there was a crash, cleanup will occur at the
    3101             :      * next startup.  (Before PostgreSQL 8.3, we tried to recover from the
    3102             :      * crash before exiting, but that seems unwise if we are quitting because
    3103             :      * we got SIGTERM from init --- there may well not be time for recovery
    3104             :      * before init decides to SIGKILL us.)
    3105             :      *
    3106             :      * Note that the syslogger continues to run.  It will exit when it sees
    3107             :      * EOF on its input pipe, which happens when there are no more upstream
    3108             :      * processes.
    3109             :      */
    3110       40444 :     if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
    3111             :     {
    3112        1524 :         if (FatalError)
    3113             :         {
    3114           0 :             ereport(LOG, (errmsg("abnormal database system shutdown")));
    3115           0 :             ExitPostmaster(1);
    3116             :         }
    3117             :         else
    3118             :         {
    3119             :             /*
    3120             :              * Normal exit from the postmaster is here.  We don't need to log
    3121             :              * anything here, since the UnlinkLockFiles proc_exit callback
    3122             :              * will do so, and that should be the last user-visible action.
    3123             :              */
    3124        1524 :             ExitPostmaster(0);
    3125             :         }
    3126             :     }
    3127             : 
    3128             :     /*
    3129             :      * If the startup process failed, or the user does not want an automatic
    3130             :      * restart after backend crashes, wait for all non-syslogger children to
    3131             :      * exit, and then exit postmaster.  We don't try to reinitialize when the
    3132             :      * startup process fails, because more than likely it will just fail again
    3133             :      * and we will keep trying forever.
    3134             :      */
    3135       38920 :     if (pmState == PM_NO_CHILDREN)
    3136             :     {
    3137          16 :         if (StartupStatus == STARTUP_CRASHED)
    3138             :         {
    3139           6 :             ereport(LOG,
    3140             :                     (errmsg("shutting down due to startup process failure")));
    3141           6 :             ExitPostmaster(1);
    3142             :         }
    3143          10 :         if (!restart_after_crash)
    3144             :         {
    3145           0 :             ereport(LOG,
    3146             :                     (errmsg("shutting down because \"restart_after_crash\" is off")));
    3147           0 :             ExitPostmaster(1);
    3148             :         }
    3149             :     }
    3150             : 
    3151             :     /*
    3152             :      * If we need to recover from a crash, wait for all non-syslogger children
    3153             :      * to exit, then reset shmem and start the startup process.
    3154             :      */
    3155       38914 :     if (FatalError && pmState == PM_NO_CHILDREN)
    3156             :     {
    3157          10 :         ereport(LOG,
    3158             :                 (errmsg("all server processes terminated; reinitializing")));
    3159             : 
    3160             :         /* remove leftover temporary files after a crash */
    3161          10 :         if (remove_temp_files_after_crash)
    3162           8 :             RemovePgTempFiles();
    3163             : 
    3164             :         /* allow background workers to immediately restart */
    3165          10 :         ResetBackgroundWorkerCrashTimes();
    3166             : 
    3167          10 :         shmem_exit(1);
    3168             : 
    3169             :         /* re-read control file into local memory */
    3170          10 :         LocalProcessControlFile(true);
    3171             : 
    3172             :         /* re-create shared memory and semaphores */
    3173          10 :         CreateSharedMemoryAndSemaphores();
    3174             : 
    3175          10 :         StartupPMChild = StartChildProcess(B_STARTUP);
    3176             :         Assert(StartupPMChild != NULL);
    3177          10 :         StartupStatus = STARTUP_RUNNING;
    3178          10 :         UpdatePMState(PM_STARTUP);
    3179             :         /* crash recovery started, reset SIGKILL flag */
    3180          10 :         AbortStartTime = 0;
    3181             : 
    3182             :         /* start accepting server socket connection events again */
    3183          10 :         ConfigurePostmasterWaitSet(true);
    3184             :     }
    3185       38914 : }
    3186             : 
    3187             : static const char *
    3188         456 : pmstate_name(PMState state)
    3189             : {
    3190             : #define PM_TOSTR_CASE(sym) case sym: return #sym
    3191         456 :     switch (state)
    3192             :     {
    3193          30 :             PM_TOSTR_CASE(PM_INIT);
    3194          60 :             PM_TOSTR_CASE(PM_STARTUP);
    3195          32 :             PM_TOSTR_CASE(PM_RECOVERY);
    3196          24 :             PM_TOSTR_CASE(PM_HOT_STANDBY);
    3197          46 :             PM_TOSTR_CASE(PM_RUN);
    3198          24 :             PM_TOSTR_CASE(PM_STOP_BACKENDS);
    3199          72 :             PM_TOSTR_CASE(PM_WAIT_BACKENDS);
    3200          24 :             PM_TOSTR_CASE(PM_WAIT_XLOG_SHUTDOWN);
    3201          24 :             PM_TOSTR_CASE(PM_WAIT_XLOG_ARCHIVAL);
    3202          64 :             PM_TOSTR_CASE(PM_WAIT_DEAD_END);
    3203          24 :             PM_TOSTR_CASE(PM_WAIT_CHECKPOINTER);
    3204          32 :             PM_TOSTR_CASE(PM_NO_CHILDREN);
    3205             :     }
    3206             : #undef PM_TOSTR_CASE
    3207             : 
    3208           0 :     pg_unreachable();
    3209             :     return "";                    /* silence compiler */
    3210             : }
    3211             : 
    3212             : /*
    3213             :  * Simple wrapper for updating pmState. The main reason to have this wrapper
    3214             :  * is that it makes it easy to log all state transitions.
    3215             :  */
    3216             : static void
    3217       11966 : UpdatePMState(PMState newState)
    3218             : {
    3219       11966 :     elog(DEBUG1, "updating PMState from %s to %s",
    3220             :          pmstate_name(pmState), pmstate_name(newState));
    3221       11966 :     pmState = newState;
    3222       11966 : }
    3223             : 
    3224             : /*
    3225             :  * Launch background processes after state change, or relaunch after an
    3226             :  * existing process has exited.
    3227             :  *
    3228             :  * Check the current pmState and the status of any background processes.  If
    3229             :  * there are any background processes missing that should be running in the
    3230             :  * current state, but are not, launch them.
    3231             :  */
    3232             : static void
    3233      243672 : LaunchMissingBackgroundProcesses(void)
    3234             : {
    3235             :     /* Syslogger is active in all states */
    3236      243672 :     if (SysLoggerPMChild == NULL && Logging_collector)
    3237           0 :         StartSysLogger();
    3238             : 
    3239             :     /*
    3240             :      * The checkpointer and the background writer are active from the start,
    3241             :      * until shutdown is initiated.
    3242             :      *
    3243             :      * (If the checkpointer is not running when we enter the
    3244             :      * PM_WAIT_XLOG_SHUTDOWN state, it is launched one more time to perform
    3245             :      * the shutdown checkpoint.  That's done in PostmasterStateMachine(), not
    3246             :      * here.)
    3247             :      */
    3248      243672 :     if (pmState == PM_RUN || pmState == PM_RECOVERY ||
    3249       11278 :         pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
    3250             :     {
    3251      235902 :         if (CheckpointerPMChild == NULL)
    3252          10 :             CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
    3253      235902 :         if (BgWriterPMChild == NULL)
    3254          10 :             BgWriterPMChild = StartChildProcess(B_BG_WRITER);
    3255             :     }
    3256             : 
    3257             :     /*
    3258             :      * WAL writer is needed only in normal operation (else we cannot be
    3259             :      * writing any new WAL).
    3260             :      */
    3261      243672 :     if (WalWriterPMChild == NULL && pmState == PM_RUN)
    3262        1350 :         WalWriterPMChild = StartChildProcess(B_WAL_WRITER);
    3263             : 
    3264             :     /*
    3265             :      * We don't want autovacuum to run in binary upgrade mode because
    3266             :      * autovacuum might update relfrozenxid for empty tables before the
    3267             :      * physical files are put in place.
    3268             :      */
    3269      257638 :     if (!IsBinaryUpgrade && AutoVacLauncherPMChild == NULL &&
    3270       20358 :         (AutoVacuumingActive() || start_autovac_launcher) &&
    3271        7574 :         pmState == PM_RUN)
    3272             :     {
    3273        1168 :         AutoVacLauncherPMChild = StartChildProcess(B_AUTOVAC_LAUNCHER);
    3274        1168 :         if (AutoVacLauncherPMChild != NULL)
    3275        1168 :             start_autovac_launcher = false; /* signal processed */
    3276             :     }
    3277             : 
    3278             :     /*
    3279             :      * If WAL archiving is enabled always, we are allowed to start archiver
    3280             :      * even during recovery.
    3281             :      */
    3282      243672 :     if (PgArchPMChild == NULL &&
    3283      241640 :         ((XLogArchivingActive() && pmState == PM_RUN) ||
    3284      241640 :          (XLogArchivingAlways() && (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) &&
    3285         100 :         PgArchCanRestart())
    3286         100 :         PgArchPMChild = StartChildProcess(B_ARCHIVER);
    3287             : 
    3288             :     /*
    3289             :      * If we need to start a slot sync worker, try to do that now
    3290             :      *
    3291             :      * We allow to start the slot sync worker when we are on a hot standby,
    3292             :      * fast or immediate shutdown is not in progress, slot sync parameters are
    3293             :      * configured correctly, and it is the first time of worker's launch, or
    3294             :      * enough time has passed since the worker was launched last.
    3295             :      */
    3296      243672 :     if (SlotSyncWorkerPMChild == NULL && pmState == PM_HOT_STANDBY &&
    3297        3272 :         Shutdown <= SmartShutdown && sync_replication_slots &&
    3298          22 :         ValidateSlotSyncParams(LOG) && SlotSyncWorkerCanRestart())
    3299           8 :         SlotSyncWorkerPMChild = StartChildProcess(B_SLOTSYNC_WORKER);
    3300             : 
    3301             :     /*
    3302             :      * If we need to start a WAL receiver, try to do that now
    3303             :      *
    3304             :      * Note: if a walreceiver process is already running, it might seem that
    3305             :      * we should clear WalReceiverRequested.  However, there's a race
    3306             :      * condition if the walreceiver terminates and the startup process
    3307             :      * immediately requests a new one: it's quite possible to get the signal
    3308             :      * for the request before reaping the dead walreceiver process.  Better to
    3309             :      * risk launching an extra walreceiver than to miss launching one we need.
    3310             :      * (The walreceiver code has logic to recognize that it should go away if
    3311             :      * not needed.)
    3312             :      */
    3313      243672 :     if (WalReceiverRequested)
    3314             :     {
    3315         620 :         if (WalReceiverPMChild == NULL &&
    3316         462 :             (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
    3317         460 :              pmState == PM_HOT_STANDBY) &&
    3318         462 :             Shutdown <= SmartShutdown)
    3319             :         {
    3320         462 :             WalReceiverPMChild = StartChildProcess(B_WAL_RECEIVER);
    3321         462 :             if (WalReceiverPMChild != 0)
    3322         462 :                 WalReceiverRequested = false;
    3323             :             /* else leave the flag set, so we'll try again later */
    3324             :         }
    3325             :     }
    3326             : 
    3327             :     /* If we need to start a WAL summarizer, try to do that now */
    3328      243672 :     if (summarize_wal && WalSummarizerPMChild == NULL &&
    3329         120 :         (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
    3330          36 :         Shutdown <= SmartShutdown)
    3331          36 :         WalSummarizerPMChild = StartChildProcess(B_WAL_SUMMARIZER);
    3332             : 
    3333             :     /* Get other worker processes running, if needed */
    3334      243672 :     if (StartWorkerNeeded || HaveCrashedWorker)
    3335        9866 :         maybe_start_bgworkers();
    3336      243668 : }
    3337             : 
    3338             : /*
    3339             :  * Return string representation of signal.
    3340             :  *
    3341             :  * Because this is only implemented for signals we already rely on in this
    3342             :  * file we don't need to deal with unimplemented or same-numeric-value signals
    3343             :  * (as we'd e.g. have to for EWOULDBLOCK / EAGAIN).
    3344             :  */
    3345             : static const char *
    3346           0 : pm_signame(int signal)
    3347             : {
    3348             : #define PM_TOSTR_CASE(sym) case sym: return #sym
    3349           0 :     switch (signal)
    3350             :     {
    3351           0 :             PM_TOSTR_CASE(SIGABRT);
    3352           0 :             PM_TOSTR_CASE(SIGCHLD);
    3353           0 :             PM_TOSTR_CASE(SIGHUP);
    3354           0 :             PM_TOSTR_CASE(SIGINT);
    3355           0 :             PM_TOSTR_CASE(SIGKILL);
    3356           0 :             PM_TOSTR_CASE(SIGQUIT);
    3357           0 :             PM_TOSTR_CASE(SIGTERM);
    3358           0 :             PM_TOSTR_CASE(SIGUSR1);
    3359           0 :             PM_TOSTR_CASE(SIGUSR2);
    3360           0 :         default:
    3361             :             /* all signals sent by postmaster should be listed here */
    3362             :             Assert(false);
    3363           0 :             return "(unknown)";
    3364             :     }
    3365             : #undef PM_TOSTR_CASE
    3366             : 
    3367             :     return "";                    /* silence compiler */
    3368             : }
    3369             : 
    3370             : /*
    3371             :  * Send a signal to a postmaster child process
    3372             :  *
    3373             :  * On systems that have setsid(), each child process sets itself up as a
    3374             :  * process group leader.  For signals that are generally interpreted in the
    3375             :  * appropriate fashion, we signal the entire process group not just the
    3376             :  * direct child process.  This allows us to, for example, SIGQUIT a blocked
    3377             :  * archive_recovery script, or SIGINT a script being run by a backend via
    3378             :  * system().
    3379             :  *
    3380             :  * There is a race condition for recently-forked children: they might not
    3381             :  * have executed setsid() yet.  So we signal the child directly as well as
    3382             :  * the group.  We assume such a child will handle the signal before trying
    3383             :  * to spawn any grandchild processes.  We also assume that signaling the
    3384             :  * child twice will not cause any problems.
    3385             :  */
    3386             : static void
    3387       11026 : signal_child(PMChild *pmchild, int signal)
    3388             : {
    3389       11026 :     pid_t       pid = pmchild->pid;
    3390             : 
    3391       11026 :     ereport(DEBUG3,
    3392             :             (errmsg_internal("sending signal %d/%s to %s process with pid %d",
    3393             :                              signal, pm_signame(signal),
    3394             :                              GetBackendTypeDesc(pmchild->bkend_type),
    3395             :                              (int) pmchild->pid)));
    3396             : 
    3397       11026 :     if (kill(pid, signal) < 0)
    3398           0 :         elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
    3399             : #ifdef HAVE_SETSID
    3400       11026 :     switch (signal)
    3401             :     {
    3402        8442 :         case SIGINT:
    3403             :         case SIGTERM:
    3404             :         case SIGQUIT:
    3405             :         case SIGKILL:
    3406             :         case SIGABRT:
    3407        8442 :             if (kill(-pid, signal) < 0)
    3408          70 :                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
    3409        8442 :             break;
    3410        2584 :         default:
    3411        2584 :             break;
    3412             :     }
    3413             : #endif
    3414       11026 : }
    3415             : 
    3416             : /*
    3417             :  * Send a signal to the targeted children.
    3418             :  */
    3419             : static bool
    3420        4224 : SignalChildren(int signal, BackendTypeMask targetMask)
    3421             : {
    3422             :     dlist_iter  iter;
    3423        4224 :     bool        signaled = false;
    3424             : 
    3425       15320 :     dlist_foreach(iter, &ActiveChildList)
    3426             :     {
    3427       11096 :         PMChild    *bp = dlist_container(PMChild, elem, iter.cur);
    3428             : 
    3429             :         /*
    3430             :          * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
    3431             :          * if any B_BACKEND backends have recently announced that they are
    3432             :          * actually WAL senders.
    3433             :          */
    3434       11096 :         if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
    3435        5942 :             bp->bkend_type == B_BACKEND)
    3436             :         {
    3437         600 :             if (IsPostmasterChildWalSender(bp->child_slot))
    3438          70 :                 bp->bkend_type = B_WAL_SENDER;
    3439             :         }
    3440             : 
    3441       11096 :         if (!btmask_contains(targetMask, bp->bkend_type))
    3442        1972 :             continue;
    3443             : 
    3444        9124 :         signal_child(bp, signal);
    3445        9124 :         signaled = true;
    3446             :     }
    3447        4224 :     return signaled;
    3448             : }
    3449             : 
    3450             : /*
    3451             :  * Send a termination signal to children.  This considers all of our children
    3452             :  * processes, except syslogger.
    3453             :  */
    3454             : static void
    3455         646 : TerminateChildren(int signal)
    3456             : {
    3457         646 :     SignalChildren(signal, btmask_all_except(B_LOGGER));
    3458         646 :     if (StartupPMChild != NULL)
    3459             :     {
    3460          90 :         if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
    3461          90 :             StartupStatus = STARTUP_SIGNALED;
    3462             :     }
    3463         646 : }
    3464             : 
    3465             : /*
    3466             :  * BackendStartup -- start backend process
    3467             :  *
    3468             :  * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
    3469             :  *
    3470             :  * Note: if you change this code, also consider StartAutovacuumWorker and
    3471             :  * StartBackgroundWorker.
    3472             :  */
    3473             : static int
    3474       23524 : BackendStartup(ClientSocket *client_sock)
    3475             : {
    3476       23524 :     PMChild    *bn = NULL;
    3477             :     pid_t       pid;
    3478             :     BackendStartupData startup_data;
    3479             :     CAC_state   cac;
    3480             : 
    3481             :     /*
    3482             :      * Allocate and assign the child slot.  Note we must do this before
    3483             :      * forking, so that we can handle failures (out of memory or child-process
    3484             :      * slots) cleanly.
    3485             :      */
    3486       23524 :     cac = canAcceptConnections(B_BACKEND);
    3487       23524 :     if (cac == CAC_OK)
    3488             :     {
    3489             :         /* Can change later to B_WAL_SENDER */
    3490       23304 :         bn = AssignPostmasterChildSlot(B_BACKEND);
    3491       23304 :         if (!bn)
    3492             :         {
    3493             :             /*
    3494             :              * Too many regular child processes; launch a dead-end child
    3495             :              * process instead.
    3496             :              */
    3497          56 :             cac = CAC_TOOMANY;
    3498             :         }
    3499             :     }
    3500       23524 :     if (!bn)
    3501             :     {
    3502         276 :         bn = AllocDeadEndChild();
    3503         276 :         if (!bn)
    3504             :         {
    3505           0 :             ereport(LOG,
    3506             :                     (errcode(ERRCODE_OUT_OF_MEMORY),
    3507             :                      errmsg("out of memory")));
    3508           0 :             return STATUS_ERROR;
    3509             :         }
    3510             :     }
    3511             : 
    3512             :     /* Pass down canAcceptConnections state */
    3513       23524 :     startup_data.canAcceptConnections = cac;
    3514       23524 :     bn->rw = NULL;
    3515             : 
    3516             :     /* Hasn't asked to be notified about any bgworkers yet */
    3517       23524 :     bn->bgworker_notify = false;
    3518             : 
    3519       23524 :     pid = postmaster_child_launch(bn->bkend_type, bn->child_slot,
    3520             :                                   (char *) &startup_data, sizeof(startup_data),
    3521             :                                   client_sock);
    3522       23522 :     if (pid < 0)
    3523             :     {
    3524             :         /* in parent, fork failed */
    3525           0 :         int         save_errno = errno;
    3526             : 
    3527           0 :         (void) ReleasePostmasterChildSlot(bn);
    3528           0 :         errno = save_errno;
    3529           0 :         ereport(LOG,
    3530             :                 (errmsg("could not fork new process for connection: %m")));
    3531           0 :         report_fork_failure_to_client(client_sock, save_errno);
    3532           0 :         return STATUS_ERROR;
    3533             :     }
    3534             : 
    3535             :     /* in parent, successful fork */
    3536       23522 :     ereport(DEBUG2,
    3537             :             (errmsg_internal("forked new %s, pid=%d socket=%d",
    3538             :                              GetBackendTypeDesc(bn->bkend_type),
    3539             :                              (int) pid, (int) client_sock->sock)));
    3540             : 
    3541             :     /*
    3542             :      * Everything's been successful, it's safe to add this backend to our list
    3543             :      * of backends.
    3544             :      */
    3545       23522 :     bn->pid = pid;
    3546       23522 :     return STATUS_OK;
    3547             : }
    3548             : 
    3549             : /*
    3550             :  * Try to report backend fork() failure to client before we close the
    3551             :  * connection.  Since we do not care to risk blocking the postmaster on
    3552             :  * this connection, we set the connection to non-blocking and try only once.
    3553             :  *
    3554             :  * This is grungy special-purpose code; we cannot use backend libpq since
    3555             :  * it's not up and running.
    3556             :  */
    3557             : static void
    3558           0 : report_fork_failure_to_client(ClientSocket *client_sock, int errnum)
    3559             : {
    3560             :     char        buffer[1000];
    3561             :     int         rc;
    3562             : 
    3563             :     /* Format the error message packet (always V2 protocol) */
    3564           0 :     snprintf(buffer, sizeof(buffer), "E%s%s\n",
    3565             :              _("could not fork new process for connection: "),
    3566             :              strerror(errnum));
    3567             : 
    3568             :     /* Set port to non-blocking.  Don't do send() if this fails */
    3569           0 :     if (!pg_set_noblock(client_sock->sock))
    3570           0 :         return;
    3571             : 
    3572             :     /* We'll retry after EINTR, but ignore all other failures */
    3573             :     do
    3574             :     {
    3575           0 :         rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
    3576           0 :     } while (rc < 0 && errno == EINTR);
    3577             : }
    3578             : 
    3579             : /*
    3580             :  * ExitPostmaster -- cleanup
    3581             :  *
    3582             :  * Do NOT call exit() directly --- always go through here!
    3583             :  */
    3584             : static void
    3585        1534 : ExitPostmaster(int status)
    3586             : {
    3587             : #ifdef HAVE_PTHREAD_IS_THREADED_NP
    3588             : 
    3589             :     /*
    3590             :      * There is no known cause for a postmaster to become multithreaded after
    3591             :      * startup.  However, we might reach here via an error exit before
    3592             :      * reaching the test in PostmasterMain, so provide the same hint as there.
    3593             :      * This message uses LOG level, because an unclean shutdown at this point
    3594             :      * would usually not look much different from a clean shutdown.
    3595             :      */
    3596             :     if (pthread_is_threaded_np() != 0)
    3597             :         ereport(LOG,
    3598             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3599             :                  errmsg("postmaster became multithreaded"),
    3600             :                  errhint("Set the LC_ALL environment variable to a valid locale.")));
    3601             : #endif
    3602             : 
    3603             :     /* should cleanup shared memory and kill all backends */
    3604             : 
    3605             :     /*
    3606             :      * Not sure of the semantics here.  When the Postmaster dies, should the
    3607             :      * backends all be killed? probably not.
    3608             :      *
    3609             :      * MUST     -- vadim 05-10-1999
    3610             :      */
    3611             : 
    3612        1534 :     proc_exit(status);
    3613             : }
    3614             : 
    3615             : /*
    3616             :  * Handle pmsignal conditions representing requests from backends,
    3617             :  * and check for promote and logrotate requests from pg_ctl.
    3618             :  */
    3619             : static void
    3620      185324 : process_pm_pmsignal(void)
    3621             : {
    3622      185324 :     bool        request_state_update = false;
    3623             : 
    3624      185324 :     pending_pm_pmsignal = false;
    3625             : 
    3626      185324 :     ereport(DEBUG2,
    3627             :             (errmsg_internal("postmaster received pmsignal signal")));
    3628             : 
    3629             :     /*
    3630             :      * RECOVERY_STARTED and BEGIN_HOT_STANDBY signals are ignored in
    3631             :      * unexpected states. If the startup process quickly starts up, completes
    3632             :      * recovery, exits, we might process the death of the startup process
    3633             :      * first. We don't want to go back to recovery in that case.
    3634             :      */
    3635      185324 :     if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
    3636         484 :         pmState == PM_STARTUP && Shutdown == NoShutdown)
    3637             :     {
    3638             :         /* WAL redo has started. We're out of reinitialization. */
    3639         484 :         FatalError = false;
    3640         484 :         AbortStartTime = 0;
    3641             : 
    3642             :         /*
    3643             :          * Start the archiver if we're responsible for (re-)archiving received
    3644             :          * files.
    3645             :          */
    3646             :         Assert(PgArchPMChild == NULL);
    3647         484 :         if (XLogArchivingAlways())
    3648           6 :             PgArchPMChild = StartChildProcess(B_ARCHIVER);
    3649             : 
    3650             :         /*
    3651             :          * If we aren't planning to enter hot standby mode later, treat
    3652             :          * RECOVERY_STARTED as meaning we're out of startup, and report status
    3653             :          * accordingly.
    3654             :          */
    3655         484 :         if (!EnableHotStandby)
    3656             :         {
    3657           4 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STANDBY);
    3658             : #ifdef USE_SYSTEMD
    3659             :             sd_notify(0, "READY=1");
    3660             : #endif
    3661             :         }
    3662             : 
    3663         484 :         UpdatePMState(PM_RECOVERY);
    3664             :     }
    3665             : 
    3666      185324 :     if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
    3667         290 :         pmState == PM_RECOVERY && Shutdown == NoShutdown)
    3668             :     {
    3669         290 :         ereport(LOG,
    3670             :                 (errmsg("database system is ready to accept read-only connections")));
    3671             : 
    3672             :         /* Report status */
    3673         290 :         AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
    3674             : #ifdef USE_SYSTEMD
    3675             :         sd_notify(0, "READY=1");
    3676             : #endif
    3677             : 
    3678         290 :         UpdatePMState(PM_HOT_STANDBY);
    3679         290 :         connsAllowed = true;
    3680             : 
    3681             :         /* Some workers may be scheduled to start now */
    3682         290 :         StartWorkerNeeded = true;
    3683             :     }
    3684             : 
    3685             :     /* Process background worker state changes. */
    3686      185324 :     if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE))
    3687             :     {
    3688             :         /* Accept new worker requests only if not stopping. */
    3689        2096 :         BackgroundWorkerStateChange(pmState < PM_STOP_BACKENDS);
    3690        2096 :         StartWorkerNeeded = true;
    3691             :     }
    3692             : 
    3693             :     /* Tell syslogger to rotate logfile if requested */
    3694      185324 :     if (SysLoggerPMChild != NULL)
    3695             :     {
    3696           4 :         if (CheckLogrotateSignal())
    3697             :         {
    3698           2 :             signal_child(SysLoggerPMChild, SIGUSR1);
    3699           2 :             RemoveLogrotateSignalFiles();
    3700             :         }
    3701           2 :         else if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE))
    3702             :         {
    3703           0 :             signal_child(SysLoggerPMChild, SIGUSR1);
    3704             :         }
    3705             :     }
    3706             : 
    3707      185324 :     if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) &&
    3708      176976 :         Shutdown <= SmartShutdown && pmState < PM_STOP_BACKENDS)
    3709             :     {
    3710             :         /*
    3711             :          * Start one iteration of the autovacuum daemon, even if autovacuuming
    3712             :          * is nominally not enabled.  This is so we can have an active defense
    3713             :          * against transaction ID wraparound.  We set a flag for the main loop
    3714             :          * to do it rather than trying to do it here --- this is because the
    3715             :          * autovac process itself may send the signal, and we want to handle
    3716             :          * that by launching another iteration as soon as the current one
    3717             :          * completes.
    3718             :          */
    3719      176976 :         start_autovac_launcher = true;
    3720             :     }
    3721             : 
    3722      185324 :     if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) &&
    3723        2244 :         Shutdown <= SmartShutdown && pmState < PM_STOP_BACKENDS)
    3724             :     {
    3725             :         /* The autovacuum launcher wants us to start a worker process. */
    3726        2244 :         StartAutovacuumWorker();
    3727             :     }
    3728             : 
    3729      185324 :     if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER))
    3730             :     {
    3731             :         /* Startup Process wants us to start the walreceiver process. */
    3732         462 :         WalReceiverRequested = true;
    3733             :     }
    3734             : 
    3735      185324 :     if (CheckPostmasterSignal(PMSIGNAL_XLOG_IS_SHUTDOWN))
    3736             :     {
    3737             :         /* Checkpointer completed the shutdown checkpoint */
    3738         894 :         if (pmState == PM_WAIT_XLOG_SHUTDOWN)
    3739             :         {
    3740             :             /*
    3741             :              * If we have an archiver subprocess, tell it to do a last archive
    3742             :              * cycle and quit. Likewise, if we have walsender processes, tell
    3743             :              * them to send any remaining WAL and quit.
    3744             :              */
    3745             :             Assert(Shutdown > NoShutdown);
    3746             : 
    3747             :             /* Waken archiver for the last time */
    3748         894 :             if (PgArchPMChild != NULL)
    3749          28 :                 signal_child(PgArchPMChild, SIGUSR2);
    3750             : 
    3751             :             /*
    3752             :              * Waken walsenders for the last time. No regular backends should
    3753             :              * be around anymore.
    3754             :              */
    3755         894 :             SignalChildren(SIGUSR2, btmask(B_WAL_SENDER));
    3756             : 
    3757         894 :             UpdatePMState(PM_WAIT_XLOG_ARCHIVAL);
    3758             :         }
    3759           0 :         else if (!FatalError && Shutdown != ImmediateShutdown)
    3760             :         {
    3761             :             /*
    3762             :              * Checkpointer only ought to perform the shutdown checkpoint
    3763             :              * during shutdown.  If somehow checkpointer did so in another
    3764             :              * situation, we have no choice but to crash-restart.
    3765             :              *
    3766             :              * It's possible however that we get PMSIGNAL_XLOG_IS_SHUTDOWN
    3767             :              * outside of PM_WAIT_XLOG_SHUTDOWN if an orderly shutdown was
    3768             :              * "interrupted" by a crash or an immediate shutdown.
    3769             :              */
    3770           0 :             ereport(LOG,
    3771             :                     (errmsg("WAL was shut down unexpectedly")));
    3772             : 
    3773             :             /*
    3774             :              * Doesn't seem likely to help to take send_abort_for_crash into
    3775             :              * account here.
    3776             :              */
    3777           0 :             HandleFatalError(PMQUIT_FOR_CRASH, false);
    3778             :         }
    3779             : 
    3780             :         /*
    3781             :          * Need to run PostmasterStateMachine() to check if we already can go
    3782             :          * to the next state.
    3783             :          */
    3784         894 :         request_state_update = true;
    3785             :     }
    3786             : 
    3787             :     /*
    3788             :      * Try to advance postmaster's state machine, if a child requests it.
    3789             :      */
    3790      185324 :     if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE))
    3791             :     {
    3792        2224 :         request_state_update = true;
    3793             :     }
    3794             : 
    3795             :     /*
    3796             :      * Be careful about the order of this action relative to this function's
    3797             :      * other actions.  Generally, this should be after other actions, in case
    3798             :      * they have effects PostmasterStateMachine would need to know about.
    3799             :      * However, we should do it before the CheckPromoteSignal step, which
    3800             :      * cannot have any (immediate) effect on the state machine, but does
    3801             :      * depend on what state we're in now.
    3802             :      */
    3803      185324 :     if (request_state_update)
    3804             :     {
    3805        3118 :         PostmasterStateMachine();
    3806             :     }
    3807             : 
    3808      185324 :     if (StartupPMChild != NULL &&
    3809        1352 :         (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
    3810        2268 :          pmState == PM_HOT_STANDBY) &&
    3811        1350 :         CheckPromoteSignal())
    3812             :     {
    3813             :         /*
    3814             :          * Tell startup process to finish recovery.
    3815             :          *
    3816             :          * Leave the promote signal file in place and let the Startup process
    3817             :          * do the unlink.
    3818             :          */
    3819          84 :         signal_child(StartupPMChild, SIGUSR2);
    3820             :     }
    3821      185324 : }
    3822             : 
    3823             : /*
    3824             :  * Dummy signal handler
    3825             :  *
    3826             :  * We use this for signals that we don't actually use in the postmaster,
    3827             :  * but we do use in backends.  If we were to SIG_IGN such signals in the
    3828             :  * postmaster, then a newly started backend might drop a signal that arrives
    3829             :  * before it's able to reconfigure its signal processing.  (See notes in
    3830             :  * tcop/postgres.c.)
    3831             :  */
    3832             : static void
    3833           0 : dummy_handler(SIGNAL_ARGS)
    3834             : {
    3835           0 : }
    3836             : 
    3837             : /*
    3838             :  * Count up number of child processes of specified types.
    3839             :  */
    3840             : static int
    3841       10004 : CountChildren(BackendTypeMask targetMask)
    3842             : {
    3843             :     dlist_iter  iter;
    3844       10004 :     int         cnt = 0;
    3845             : 
    3846       34856 :     dlist_foreach(iter, &ActiveChildList)
    3847             :     {
    3848       24852 :         PMChild    *bp = dlist_container(PMChild, elem, iter.cur);
    3849             : 
    3850             :         /*
    3851             :          * If we need to distinguish between B_BACKEND and B_WAL_SENDER, check
    3852             :          * if any B_BACKEND backends have recently announced that they are
    3853             :          * actually WAL senders.
    3854             :          */
    3855       24852 :         if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
    3856       16154 :             bp->bkend_type == B_BACKEND)
    3857             :         {
    3858         852 :             if (IsPostmasterChildWalSender(bp->child_slot))
    3859           0 :                 bp->bkend_type = B_WAL_SENDER;
    3860             :         }
    3861             : 
    3862       24852 :         if (!btmask_contains(targetMask, bp->bkend_type))
    3863        6740 :             continue;
    3864             : 
    3865       18112 :         ereport(DEBUG4,
    3866             :                 (errmsg_internal("%s process %d is still running",
    3867             :                                  GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
    3868             : 
    3869       18112 :         cnt++;
    3870             :     }
    3871       10004 :     return cnt;
    3872             : }
    3873             : 
    3874             : 
    3875             : /*
    3876             :  * StartChildProcess -- start an auxiliary process for the postmaster
    3877             :  *
    3878             :  * "type" determines what kind of child will be started.  All child types
    3879             :  * initially go to AuxiliaryProcessMain, which will handle common setup.
    3880             :  *
    3881             :  * Return value of StartChildProcess is subprocess' PMChild entry, or NULL on
    3882             :  * failure.
    3883             :  */
    3884             : static PMChild *
    3885       10012 : StartChildProcess(BackendType type)
    3886             : {
    3887             :     PMChild    *pmchild;
    3888             :     pid_t       pid;
    3889             : 
    3890       10012 :     pmchild = AssignPostmasterChildSlot(type);
    3891       10012 :     if (!pmchild)
    3892             :     {
    3893           0 :         if (type == B_AUTOVAC_WORKER)
    3894           0 :             ereport(LOG,
    3895             :                     (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
    3896             :                      errmsg("no slot available for new autovacuum worker process")));
    3897             :         else
    3898             :         {
    3899             :             /* shouldn't happen because we allocate enough slots */
    3900           0 :             elog(LOG, "no postmaster child slot available for aux process");
    3901             :         }
    3902           0 :         return NULL;
    3903             :     }
    3904             : 
    3905       10012 :     pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
    3906       10012 :     if (pid < 0)
    3907             :     {
    3908             :         /* in parent, fork failed */
    3909           0 :         ReleasePostmasterChildSlot(pmchild);
    3910           0 :         ereport(LOG,
    3911             :                 (errmsg("could not fork \"%s\" process: %m", PostmasterChildName(type))));
    3912             : 
    3913             :         /*
    3914             :          * fork failure is fatal during startup, but there's no need to choke
    3915             :          * immediately if starting other child types fails.
    3916             :          */
    3917           0 :         if (type == B_STARTUP)
    3918           0 :             ExitPostmaster(1);
    3919           0 :         return NULL;
    3920             :     }
    3921             : 
    3922             :     /* in parent, successful fork */
    3923       10012 :     pmchild->pid = pid;
    3924       10012 :     return pmchild;
    3925             : }
    3926             : 
    3927             : /*
    3928             :  * StartSysLogger -- start the syslogger process
    3929             :  */
    3930             : void
    3931           2 : StartSysLogger(void)
    3932             : {
    3933             :     Assert(SysLoggerPMChild == NULL);
    3934             : 
    3935           2 :     SysLoggerPMChild = AssignPostmasterChildSlot(B_LOGGER);
    3936           2 :     if (!SysLoggerPMChild)
    3937           0 :         elog(PANIC, "no postmaster child slot available for syslogger");
    3938           2 :     SysLoggerPMChild->pid = SysLogger_Start(SysLoggerPMChild->child_slot);
    3939           2 :     if (SysLoggerPMChild->pid == 0)
    3940             :     {
    3941           0 :         ReleasePostmasterChildSlot(SysLoggerPMChild);
    3942           0 :         SysLoggerPMChild = NULL;
    3943             :     }
    3944           2 : }
    3945             : 
    3946             : /*
    3947             :  * StartAutovacuumWorker
    3948             :  *      Start an autovac worker process.
    3949             :  *
    3950             :  * This function is here because it enters the resulting PID into the
    3951             :  * postmaster's private backends list.
    3952             :  *
    3953             :  * NB -- this code very roughly matches BackendStartup.
    3954             :  */
    3955             : static void
    3956        2244 : StartAutovacuumWorker(void)
    3957             : {
    3958             :     PMChild    *bn;
    3959             : 
    3960             :     /*
    3961             :      * If not in condition to run a process, don't try, but handle it like a
    3962             :      * fork failure.  This does not normally happen, since the signal is only
    3963             :      * supposed to be sent by autovacuum launcher when it's OK to do it, but
    3964             :      * we have to check to avoid race-condition problems during DB state
    3965             :      * changes.
    3966             :      */
    3967        2244 :     if (canAcceptConnections(B_AUTOVAC_WORKER) == CAC_OK)
    3968             :     {
    3969        2244 :         bn = StartChildProcess(B_AUTOVAC_WORKER);
    3970        2244 :         if (bn)
    3971             :         {
    3972        2244 :             bn->bgworker_notify = false;
    3973        2244 :             bn->rw = NULL;
    3974        2244 :             return;
    3975             :         }
    3976             :         else
    3977             :         {
    3978             :             /*
    3979             :              * fork failed, fall through to report -- actual error message was
    3980             :              * logged by StartChildProcess
    3981             :              */
    3982             :         }
    3983             :     }
    3984             : 
    3985             :     /*
    3986             :      * Report the failure to the launcher, if it's running.  (If it's not, we
    3987             :      * might not even be connected to shared memory, so don't try to call
    3988             :      * AutoVacWorkerFailed.)  Note that we also need to signal it so that it
    3989             :      * responds to the condition, but we don't do that here, instead waiting
    3990             :      * for ServerLoop to do it.  This way we avoid a ping-pong signaling in
    3991             :      * quick succession between the autovac launcher and postmaster in case
    3992             :      * things get ugly.
    3993             :      */
    3994           0 :     if (AutoVacLauncherPMChild != NULL)
    3995             :     {
    3996           0 :         AutoVacWorkerFailed();
    3997           0 :         avlauncher_needs_signal = true;
    3998             :     }
    3999             : }
    4000             : 
    4001             : 
    4002             : /*
    4003             :  * Create the opts file
    4004             :  */
    4005             : static bool
    4006        1536 : CreateOptsFile(int argc, char *argv[], char *fullprogname)
    4007             : {
    4008             :     FILE       *fp;
    4009             :     int         i;
    4010             : 
    4011             : #define OPTS_FILE   "postmaster.opts"
    4012             : 
    4013        1536 :     if ((fp = fopen(OPTS_FILE, "w")) == NULL)
    4014             :     {
    4015           0 :         ereport(LOG,
    4016             :                 (errcode_for_file_access(),
    4017             :                  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
    4018           0 :         return false;
    4019             :     }
    4020             : 
    4021        1536 :     fprintf(fp, "%s", fullprogname);
    4022        7620 :     for (i = 1; i < argc; i++)
    4023        6084 :         fprintf(fp, " \"%s\"", argv[i]);
    4024        1536 :     fputs("\n", fp);
    4025             : 
    4026        1536 :     if (fclose(fp))
    4027             :     {
    4028           0 :         ereport(LOG,
    4029             :                 (errcode_for_file_access(),
    4030             :                  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
    4031           0 :         return false;
    4032             :     }
    4033             : 
    4034        1536 :     return true;
    4035             : }
    4036             : 
    4037             : 
    4038             : /*
    4039             :  * Start a new bgworker.
    4040             :  * Starting time conditions must have been checked already.
    4041             :  *
    4042             :  * Returns true on success, false on failure.
    4043             :  * In either case, update the RegisteredBgWorker's state appropriately.
    4044             :  *
    4045             :  * NB -- this code very roughly matches BackendStartup.
    4046             :  */
    4047             : static bool
    4048        4870 : StartBackgroundWorker(RegisteredBgWorker *rw)
    4049             : {
    4050             :     PMChild    *bn;
    4051             :     pid_t       worker_pid;
    4052             : 
    4053             :     Assert(rw->rw_pid == 0);
    4054             : 
    4055             :     /*
    4056             :      * Allocate and assign the child slot.  Note we must do this before
    4057             :      * forking, so that we can handle failures (out of memory or child-process
    4058             :      * slots) cleanly.
    4059             :      *
    4060             :      * Treat failure as though the worker had crashed.  That way, the
    4061             :      * postmaster will wait a bit before attempting to start it again; if we
    4062             :      * tried again right away, most likely we'd find ourselves hitting the
    4063             :      * same resource-exhaustion condition.
    4064             :      */
    4065        4870 :     bn = AssignPostmasterChildSlot(B_BG_WORKER);
    4066        4870 :     if (bn == NULL)
    4067             :     {
    4068           0 :         ereport(LOG,
    4069             :                 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
    4070             :                  errmsg("no slot available for new background worker process")));
    4071           0 :         rw->rw_crashed_at = GetCurrentTimestamp();
    4072           0 :         return false;
    4073             :     }
    4074        4870 :     bn->rw = rw;
    4075        4870 :     bn->bkend_type = B_BG_WORKER;
    4076        4870 :     bn->bgworker_notify = false;
    4077             : 
    4078        4870 :     ereport(DEBUG1,
    4079             :             (errmsg_internal("starting background worker process \"%s\"",
    4080             :                              rw->rw_worker.bgw_name)));
    4081             : 
    4082        4870 :     worker_pid = postmaster_child_launch(B_BG_WORKER, bn->child_slot,
    4083        4870 :                                          (char *) &rw->rw_worker, sizeof(BackgroundWorker), NULL);
    4084        4866 :     if (worker_pid == -1)
    4085             :     {
    4086             :         /* in postmaster, fork failed ... */
    4087           0 :         ereport(LOG,
    4088             :                 (errmsg("could not fork background worker process: %m")));
    4089             :         /* undo what AssignPostmasterChildSlot did */
    4090           0 :         ReleasePostmasterChildSlot(bn);
    4091             : 
    4092             :         /* mark entry as crashed, so we'll try again later */
    4093           0 :         rw->rw_crashed_at = GetCurrentTimestamp();
    4094           0 :         return false;
    4095             :     }
    4096             : 
    4097             :     /* in postmaster, fork successful ... */
    4098        4866 :     rw->rw_pid = worker_pid;
    4099        4866 :     bn->pid = rw->rw_pid;
    4100        4866 :     ReportBackgroundWorkerPID(rw);
    4101        4866 :     return true;
    4102             : }
    4103             : 
    4104             : /*
    4105             :  * Does the current postmaster state require starting a worker with the
    4106             :  * specified start_time?
    4107             :  */
    4108             : static bool
    4109        6646 : bgworker_should_start_now(BgWorkerStartTime start_time)
    4110             : {
    4111        6646 :     switch (pmState)
    4112             :     {
    4113           0 :         case PM_NO_CHILDREN:
    4114             :         case PM_WAIT_CHECKPOINTER:
    4115             :         case PM_WAIT_DEAD_END:
    4116             :         case PM_WAIT_XLOG_ARCHIVAL:
    4117             :         case PM_WAIT_XLOG_SHUTDOWN:
    4118             :         case PM_WAIT_BACKENDS:
    4119             :         case PM_STOP_BACKENDS:
    4120           0 :             break;
    4121             : 
    4122        4870 :         case PM_RUN:
    4123        4870 :             if (start_time == BgWorkerStart_RecoveryFinished)
    4124        2136 :                 return true;
    4125             :             /* fall through */
    4126             : 
    4127             :         case PM_HOT_STANDBY:
    4128        3018 :             if (start_time == BgWorkerStart_ConsistentState)
    4129        2734 :                 return true;
    4130             :             /* fall through */
    4131             : 
    4132             :         case PM_RECOVERY:
    4133             :         case PM_STARTUP:
    4134             :         case PM_INIT:
    4135        1776 :             if (start_time == BgWorkerStart_PostmasterStart)
    4136           0 :                 return true;
    4137             :             /* fall through */
    4138             :     }
    4139             : 
    4140        1776 :     return false;
    4141             : }
    4142             : 
    4143             : /*
    4144             :  * If the time is right, start background worker(s).
    4145             :  *
    4146             :  * As a side effect, the bgworker control variables are set or reset
    4147             :  * depending on whether more workers may need to be started.
    4148             :  *
    4149             :  * We limit the number of workers started per call, to avoid consuming the
    4150             :  * postmaster's attention for too long when many such requests are pending.
    4151             :  * As long as StartWorkerNeeded is true, ServerLoop will not block and will
    4152             :  * call this function again after dealing with any other issues.
    4153             :  */
    4154             : static void
    4155       11402 : maybe_start_bgworkers(void)
    4156             : {
    4157             : #define MAX_BGWORKERS_TO_LAUNCH 100
    4158       11402 :     int         num_launched = 0;
    4159       11402 :     TimestampTz now = 0;
    4160             :     dlist_mutable_iter iter;
    4161             : 
    4162             :     /*
    4163             :      * During crash recovery, we have no need to be called until the state
    4164             :      * transition out of recovery.
    4165             :      */
    4166       11402 :     if (FatalError)
    4167             :     {
    4168           0 :         StartWorkerNeeded = false;
    4169           0 :         HaveCrashedWorker = false;
    4170           0 :         return;
    4171             :     }
    4172             : 
    4173             :     /* Don't need to be called again unless we find a reason for it below */
    4174       11402 :     StartWorkerNeeded = false;
    4175       11402 :     HaveCrashedWorker = false;
    4176             : 
    4177       30968 :     dlist_foreach_modify(iter, &BackgroundWorkerList)
    4178             :     {
    4179             :         RegisteredBgWorker *rw;
    4180             : 
    4181       19570 :         rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
    4182             : 
    4183             :         /* ignore if already running */
    4184       19570 :         if (rw->rw_pid != 0)
    4185       10090 :             continue;
    4186             : 
    4187             :         /* if marked for death, clean up and remove from list */
    4188        9480 :         if (rw->rw_terminate)
    4189             :         {
    4190           0 :             ForgetBackgroundWorker(rw);
    4191           0 :             continue;
    4192             :         }
    4193             : 
    4194             :         /*
    4195             :          * If this worker has crashed previously, maybe it needs to be
    4196             :          * restarted (unless on registration it specified it doesn't want to
    4197             :          * be restarted at all).  Check how long ago did a crash last happen.
    4198             :          * If the last crash is too recent, don't start it right away; let it
    4199             :          * be restarted once enough time has passed.
    4200             :          */
    4201        9480 :         if (rw->rw_crashed_at != 0)
    4202             :         {
    4203        2834 :             if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
    4204             :             {
    4205             :                 int         notify_pid;
    4206             : 
    4207           0 :                 notify_pid = rw->rw_worker.bgw_notify_pid;
    4208             : 
    4209           0 :                 ForgetBackgroundWorker(rw);
    4210             : 
    4211             :                 /* Report worker is gone now. */
    4212           0 :                 if (notify_pid != 0)
    4213           0 :                     kill(notify_pid, SIGUSR1);
    4214             : 
    4215           0 :                 continue;
    4216             :             }
    4217             : 
    4218             :             /* read system time only when needed */
    4219        2834 :             if (now == 0)
    4220        2834 :                 now = GetCurrentTimestamp();
    4221             : 
    4222        2834 :             if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now,
    4223        2834 :                                             rw->rw_worker.bgw_restart_time * 1000))
    4224             :             {
    4225             :                 /* Set flag to remember that we have workers to start later */
    4226        2834 :                 HaveCrashedWorker = true;
    4227        2834 :                 continue;
    4228             :             }
    4229             :         }
    4230             : 
    4231        6646 :         if (bgworker_should_start_now(rw->rw_worker.bgw_start_time))
    4232             :         {
    4233             :             /* reset crash time before trying to start worker */
    4234        4870 :             rw->rw_crashed_at = 0;
    4235             : 
    4236             :             /*
    4237             :              * Try to start the worker.
    4238             :              *
    4239             :              * On failure, give up processing workers for now, but set
    4240             :              * StartWorkerNeeded so we'll come back here on the next iteration
    4241             :              * of ServerLoop to try again.  (We don't want to wait, because
    4242             :              * there might be additional ready-to-run workers.)  We could set
    4243             :              * HaveCrashedWorker as well, since this worker is now marked
    4244             :              * crashed, but there's no need because the next run of this
    4245             :              * function will do that.
    4246             :              */
    4247        4870 :             if (!StartBackgroundWorker(rw))
    4248             :             {
    4249           0 :                 StartWorkerNeeded = true;
    4250           0 :                 return;
    4251             :             }
    4252             : 
    4253             :             /*
    4254             :              * If we've launched as many workers as allowed, quit, but have
    4255             :              * ServerLoop call us again to look for additional ready-to-run
    4256             :              * workers.  There might not be any, but we'll find out the next
    4257             :              * time we run.
    4258             :              */
    4259        4866 :             if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
    4260             :             {
    4261           0 :                 StartWorkerNeeded = true;
    4262           0 :                 return;
    4263             :             }
    4264             :         }
    4265             :     }
    4266             : }
    4267             : 
    4268             : /*
    4269             :  * When a backend asks to be notified about worker state changes, we
    4270             :  * set a flag in its backend entry.  The background worker machinery needs
    4271             :  * to know when such backends exit.
    4272             :  */
    4273             : bool
    4274        3570 : PostmasterMarkPIDForWorkerNotify(int pid)
    4275             : {
    4276             :     dlist_iter  iter;
    4277             :     PMChild    *bp;
    4278             : 
    4279        7368 :     dlist_foreach(iter, &ActiveChildList)
    4280             :     {
    4281        7368 :         bp = dlist_container(PMChild, elem, iter.cur);
    4282        7368 :         if (bp->pid == pid)
    4283             :         {
    4284        3570 :             bp->bgworker_notify = true;
    4285        3570 :             return true;
    4286             :         }
    4287             :     }
    4288           0 :     return false;
    4289             : }
    4290             : 
    4291             : #ifdef WIN32
    4292             : 
    4293             : /*
    4294             :  * Subset implementation of waitpid() for Windows.  We assume pid is -1
    4295             :  * (that is, check all child processes) and options is WNOHANG (don't wait).
    4296             :  */
    4297             : static pid_t
    4298             : waitpid(pid_t pid, int *exitstatus, int options)
    4299             : {
    4300             :     win32_deadchild_waitinfo *childinfo;
    4301             :     DWORD       exitcode;
    4302             :     DWORD       dwd;
    4303             :     ULONG_PTR   key;
    4304             :     OVERLAPPED *ovl;
    4305             : 
    4306             :     /* Try to consume one win32_deadchild_waitinfo from the queue. */
    4307             :     if (!GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
    4308             :     {
    4309             :         errno = EAGAIN;
    4310             :         return -1;
    4311             :     }
    4312             : 
    4313             :     childinfo = (win32_deadchild_waitinfo *) key;
    4314             :     pid = childinfo->procId;
    4315             : 
    4316             :     /*
    4317             :      * Remove handle from wait - required even though it's set to wait only
    4318             :      * once
    4319             :      */
    4320             :     UnregisterWaitEx(childinfo->waitHandle, NULL);
    4321             : 
    4322             :     if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
    4323             :     {
    4324             :         /*
    4325             :          * Should never happen. Inform user and set a fixed exitcode.
    4326             :          */
    4327             :         write_stderr("could not read exit code for process\n");
    4328             :         exitcode = 255;
    4329             :     }
    4330             :     *exitstatus = exitcode;
    4331             : 
    4332             :     /*
    4333             :      * Close the process handle.  Only after this point can the PID can be
    4334             :      * recycled by the kernel.
    4335             :      */
    4336             :     CloseHandle(childinfo->procHandle);
    4337             : 
    4338             :     /*
    4339             :      * Free struct that was allocated before the call to
    4340             :      * RegisterWaitForSingleObject()
    4341             :      */
    4342             :     pfree(childinfo);
    4343             : 
    4344             :     return pid;
    4345             : }
    4346             : 
    4347             : /*
    4348             :  * Note! Code below executes on a thread pool! All operations must
    4349             :  * be thread safe! Note that elog() and friends must *not* be used.
    4350             :  */
    4351             : static void WINAPI
    4352             : pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
    4353             : {
    4354             :     /* Should never happen, since we use INFINITE as timeout value. */
    4355             :     if (TimerOrWaitFired)
    4356             :         return;
    4357             : 
    4358             :     /*
    4359             :      * Post the win32_deadchild_waitinfo object for waitpid() to deal with. If
    4360             :      * that fails, we leak the object, but we also leak a whole process and
    4361             :      * get into an unrecoverable state, so there's not much point in worrying
    4362             :      * about that.  We'd like to panic, but we can't use that infrastructure
    4363             :      * from this thread.
    4364             :      */
    4365             :     if (!PostQueuedCompletionStatus(win32ChildQueue,
    4366             :                                     0,
    4367             :                                     (ULONG_PTR) lpParameter,
    4368             :                                     NULL))
    4369             :         write_stderr("could not post child completion status\n");
    4370             : 
    4371             :     /* Queue SIGCHLD signal. */
    4372             :     pg_queue_signal(SIGCHLD);
    4373             : }
    4374             : 
    4375             : /*
    4376             :  * Queue a waiter to signal when this child dies.  The wait will be handled
    4377             :  * automatically by an operating system thread pool.  The memory and the
    4378             :  * process handle will be freed by a later call to waitpid().
    4379             :  */
    4380             : void
    4381             : pgwin32_register_deadchild_callback(HANDLE procHandle, DWORD procId)
    4382             : {
    4383             :     win32_deadchild_waitinfo *childinfo;
    4384             : 
    4385             :     childinfo = palloc(sizeof(win32_deadchild_waitinfo));
    4386             :     childinfo->procHandle = procHandle;
    4387             :     childinfo->procId = procId;
    4388             : 
    4389             :     if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
    4390             :                                      procHandle,
    4391             :                                      pgwin32_deadchild_callback,
    4392             :                                      childinfo,
    4393             :                                      INFINITE,
    4394             :                                      WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
    4395             :         ereport(FATAL,
    4396             :                 (errmsg_internal("could not register process for wait: error code %lu",
    4397             :                                  GetLastError())));
    4398             : }
    4399             : 
    4400             : #endif                          /* WIN32 */
    4401             : 
    4402             : /*
    4403             :  * Initialize one and only handle for monitoring postmaster death.
    4404             :  *
    4405             :  * Called once in the postmaster, so that child processes can subsequently
    4406             :  * monitor if their parent is dead.
    4407             :  */
    4408             : static void
    4409        1536 : InitPostmasterDeathWatchHandle(void)
    4410             : {
    4411             : #ifndef WIN32
    4412             : 
    4413             :     /*
    4414             :      * Create a pipe. Postmaster holds the write end of the pipe open
    4415             :      * (POSTMASTER_FD_OWN), and children hold the read end. Children can pass
    4416             :      * the read file descriptor to select() to wake up in case postmaster
    4417             :      * dies, or check for postmaster death with a (read() == 0). Children must
    4418             :      * close the write end as soon as possible after forking, because EOF
    4419             :      * won't be signaled in the read end until all processes have closed the
    4420             :      * write fd. That is taken care of in ClosePostmasterPorts().
    4421             :      */
    4422             :     Assert(MyProcPid == PostmasterPid);
    4423        1536 :     if (pipe(postmaster_alive_fds) < 0)
    4424           0 :         ereport(FATAL,
    4425             :                 (errcode_for_file_access(),
    4426             :                  errmsg_internal("could not create pipe to monitor postmaster death: %m")));
    4427             : 
    4428             :     /* Notify fd.c that we've eaten two FDs for the pipe. */
    4429        1536 :     ReserveExternalFD();
    4430        1536 :     ReserveExternalFD();
    4431             : 
    4432             :     /*
    4433             :      * Set O_NONBLOCK to allow testing for the fd's presence with a read()
    4434             :      * call.
    4435             :      */
    4436        1536 :     if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
    4437           0 :         ereport(FATAL,
    4438             :                 (errcode_for_socket_access(),
    4439             :                  errmsg_internal("could not set postmaster death monitoring pipe to nonblocking mode: %m")));
    4440             : #else
    4441             : 
    4442             :     /*
    4443             :      * On Windows, we use a process handle for the same purpose.
    4444             :      */
    4445             :     if (DuplicateHandle(GetCurrentProcess(),
    4446             :                         GetCurrentProcess(),
    4447             :                         GetCurrentProcess(),
    4448             :                         &PostmasterHandle,
    4449             :                         0,
    4450             :                         TRUE,
    4451             :                         DUPLICATE_SAME_ACCESS) == 0)
    4452             :         ereport(FATAL,
    4453             :                 (errmsg_internal("could not duplicate postmaster handle: error code %lu",
    4454             :                                  GetLastError())));
    4455             : #endif                          /* WIN32 */
    4456        1536 : }

Generated by: LCOV version 1.14