LCOV - code coverage report
Current view: top level - src/backend/postmaster - postmaster.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 77.7 % 1207 938
Test Date: 2026-08-25 19:15:52 Functions: 94.3 % 53 50
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 64.8 % 1042 675

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

Generated by: LCOV version 2.0-1