LCOV - differential code coverage report
Current view: top level - src/backend/postmaster - postmaster.c (source / functions) Coverage Total Hit UBC GBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 78.0 % 1232 961 271 1 960 1
Current Date: 2026-08-27 14:31:44 +0300 Functions: 94.3 % 53 50 3 1 49
Baseline: lcov-20260827-baseline Branches: 63.8 % 1096 699 397 1 698
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 42.9 % 7 3 4 3
(7,30] days: 100.0 % 1 1 1
(30,360] days: 85.7 % 77 66 11 66
(360..) days: 77.7 % 1147 891 256 891
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 94.1 % 51 48 3 1 47
Branch coverage date bins:
(1,7] days: 37.5 % 8 3 5 3
(30,360] days: 74.0 % 50 37 13 37
(360..) days: 63.5 % 1038 659 379 1 658

 Age         Owner                    Branch data    TLA  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
  651 heikki.linnakangas@i      150                 :CBC        1725 : btmask(BackendType t)
                                151                 :                : {
                                152                 :           1725 :     BackendTypeMask mask = {.mask = 1 << t};
                                153                 :                : 
                                154                 :           1725 :     return mask;
                                155                 :                : }
                                156                 :                : 
                                157                 :                : static inline BackendTypeMask
  594 andres@anarazel.de        158                 :          39061 : btmask_add_n(BackendTypeMask mask, int nargs, BackendType *t)
                                159                 :                : {
                                160         [ +  + ]:         152881 :     for (int i = 0; i < nargs; i++)
                                161                 :         113820 :         mask.mask |= 1 << t[i];
  651 heikki.linnakangas@i      162                 :          39061 :     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                 :           4956 : btmask_del(BackendTypeMask mask, BackendType t)
                                173                 :                : {
                                174                 :           4956 :     mask.mask &= ~(1 << t);
                                175                 :           4956 :     return mask;
                                176                 :                : }
                                177                 :                : 
                                178                 :                : static inline BackendTypeMask
  594 andres@anarazel.de        179                 :           2883 : btmask_all_except_n(int nargs, BackendType *t)
                                180                 :                : {
  651 heikki.linnakangas@i      181                 :           2883 :     BackendTypeMask mask = BTYPE_MASK_ALL;
                                182                 :                : 
  594 andres@anarazel.de        183         [ +  + ]:           7839 :     for (int i = 0; i < nargs; i++)
                                184                 :           4956 :         mask = btmask_del(mask, t[i]);
  651 heikki.linnakangas@i      185                 :           2883 :     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                 :         128550 : btmask_contains(BackendTypeMask mask, BackendType t)
                                196                 :                : {
                                197                 :         128550 :     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
11006 scrappy@hub.org           498                 :           1012 : PostmasterMain(int argc, char *argv[])
                                499                 :                : {
                                500                 :                :     pg_getopt_ctx optctx;
                                501                 :                :     int         opt;
                                502                 :                :     int         status;
 7993 tgl@sss.pgh.pa.us         503                 :           1012 :     char       *userDoption = NULL;
 5705                           504                 :           1012 :     bool        listen_addr_saved = false;
 4583 peter_e@gmx.net           505                 :           1012 :     char       *output_config_variable = NULL;
                                506                 :                : 
 2869 tmunro@postgresql.or      507                 :           1012 :     InitProcessGlobals();
                                508                 :                : 
                                509                 :           1012 :     PostmasterPid = MyProcPid;
                                510                 :                : 
 8492 tgl@sss.pgh.pa.us         511                 :           1012 :     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                 :                :      */
 3064 sfrost@snowman.net        528                 :           1012 :     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                 :                :      */
 9556 tgl@sss.pgh.pa.us         536                 :           1012 :     PostmasterContext = AllocSetContextCreate(TopMemoryContext,
                                537                 :                :                                               "Postmaster",
                                538                 :                :                                               ALLOCSET_DEFAULT_SIZES);
                                539                 :           1012 :     MemoryContextSwitchTo(PostmasterContext);
                                540                 :                : 
                                541                 :                :     /* Initialize paths to installation files */
 6326                           542                 :           1012 :     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                 :                :      */
 4527                           553                 :           1012 :     pqinitmask();
 1301 tmunro@postgresql.or      554                 :           1012 :     sigprocmask(SIG_SETMASK, &BlockSig, NULL);
                                555                 :                : 
 1323                           556                 :           1012 :     pqsignal(SIGHUP, handle_pm_reload_request_signal);
                                557                 :           1012 :     pqsignal(SIGINT, handle_pm_shutdown_request_signal);
                                558                 :           1012 :     pqsignal(SIGQUIT, handle_pm_shutdown_request_signal);
                                559                 :           1012 :     pqsignal(SIGTERM, handle_pm_shutdown_request_signal);
  135 andrew@dunslane.net       560                 :           1012 :     pqsignal(SIGALRM, PG_SIG_IGN);  /* ignored */
                                561                 :           1012 :     pqsignal(SIGPIPE, PG_SIG_IGN);  /* ignored */
 1323 tmunro@postgresql.or      562                 :           1012 :     pqsignal(SIGUSR1, handle_pm_pmsignal_signal);
                                563                 :           1012 :     pqsignal(SIGUSR2, dummy_handler);   /* unused, reserve for children */
                                564                 :           1012 :     pqsignal(SIGCHLD, handle_pm_child_exit_signal);
                                565                 :                : 
                                566                 :                :     /* This may configure SIGURG, depending on platform. */
  539 heikki.linnakangas@i      567                 :           1012 :     InitializeWaitEventSupport();
 1323 tmunro@postgresql.or      568                 :           1012 :     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
  135 andrew@dunslane.net       578                 :           1012 :     pqsignal(SIGTTIN, PG_SIG_IGN);  /* ignored */
                                579                 :                : #endif
                                580                 :                : #ifdef SIGTTOU
                                581                 :           1012 :     pqsignal(SIGTTOU, PG_SIG_IGN);  /* ignored */
                                582                 :                : #endif
                                583                 :                : 
                                584                 :                :     /* ignore SIGXFSZ, so that ulimit violations work like disk full */
                                585                 :                : #ifdef SIGXFSZ
                                586                 :           1012 :     pqsignal(SIGXFSZ, PG_SIG_IGN);  /* ignored */
                                587                 :                : #endif
                                588                 :                : 
                                589                 :                :     /* Begin accepting signals. */
 1301 tmunro@postgresql.or      590                 :           1012 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
                                591                 :                : 
                                592                 :                :     /*
                                593                 :                :      * Options setup
                                594                 :                :      */
 8868 tgl@sss.pgh.pa.us         595                 :           1012 :     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                 :                :      */
  150 heikki.linnakangas@i      602                 :           1012 :     pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:OPp:r:S:sTt:W:-:");
                                603                 :           1012 :     optctx.opterr = 1;
                                604         [ +  + ]:           3635 :     while ((opt = pg_getopt_next(&optctx)) != -1)
                                605                 :                :     {
10581 bruce@momjian.us          606   [ -  +  +  +  :           2627 :         switch (opt)
                                     +  +  -  -  -  
                                     +  -  -  -  -  
                                     +  -  -  -  -  
                                     +  -  -  -  -  
                                           -  -  - ]
                                607                 :                :         {
10580 bruce@momjian.us          608                 :UBC           0 :             case 'B':
  150 heikki.linnakangas@i      609                 :              0 :                 SetConfigOption("shared_buffers", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
10580 bruce@momjian.us          610                 :              0 :                 break;
                                611                 :                : 
 5603 bruce@momjian.us          612                 :CBC          57 :             case 'b':
                                613                 :                :                 /* Undocumented flag used for binary upgrades */
                                614                 :             57 :                 IsBinaryUpgrade = true;
                                615                 :             57 :                 break;
                                616                 :                : 
 5439                           617                 :              5 :             case 'C':
  150 heikki.linnakangas@i      618                 :              5 :                 output_config_variable = strdup(optctx.optarg);
 5439 bruce@momjian.us          619                 :              5 :                 break;
                                620                 :                : 
 1354 peter@eisentraut.org      621                 :            820 :             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                 :                :                  */
  150 heikki.linnakangas@i      629         [ -  + ]:            820 :                 if (parse_dispatch_option(optctx.optarg) != DISPATCH_POSTMASTER)
  631 nathan@postgresql.or      630         [ #  # ]:UBC           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                 :                : 
  150 heikki.linnakangas@i      640                 :CBC        1282 :                     ParseLongOption(optctx.optarg, &name, &value);
 1354 peter@eisentraut.org      641         [ +  + ]:           1282 :                     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
 1354 peter@eisentraut.org      649         [ #  # ]:UBC           0 :                             ereport(ERROR,
                                650                 :                :                                     (errcode(ERRCODE_SYNTAX_ERROR),
                                651                 :                :                                      errmsg("-c %s requires a value",
                                652                 :                :                                             optctx.optarg)));
                                653                 :                :                     }
                                654                 :                : 
 1354 peter@eisentraut.org      655                 :CBC        1281 :                     SetConfigOption(name, value, PGC_POSTMASTER, PGC_S_ARGV);
                                656                 :           1278 :                     pfree(name);
                                657                 :           1278 :                     pfree(value);
                                658                 :           1278 :                     break;
                                659                 :                :                 }
                                660                 :                : 
10580 bruce@momjian.us          661                 :           1008 :             case 'D':
  150 heikki.linnakangas@i      662                 :           1008 :                 userDoption = strdup(optctx.optarg);
10580 bruce@momjian.us          663                 :           1008 :                 break;
                                664                 :                : 
10580 bruce@momjian.us          665                 :UBC           0 :             case 'd':
  150 heikki.linnakangas@i      666                 :              0 :                 set_debug_options(atoi(optctx.optarg), PGC_POSTMASTER, PGC_S_ARGV);
 7956 tgl@sss.pgh.pa.us         667                 :              0 :                 break;
                                668                 :                : 
 7539 peter_e@gmx.net           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                 :                : 
 9582 bruce@momjian.us          677                 :CBC         103 :             case 'F':
 8951 peter_e@gmx.net           678                 :            103 :                 SetConfigOption("fsync", "false", PGC_POSTMASTER, PGC_S_ARGV);
 9582 bruce@momjian.us          679                 :            103 :                 break;
                                680                 :                : 
 7539 peter_e@gmx.net           681                 :UBC           0 :             case 'f':
  150 heikki.linnakangas@i      682         [ #  # ]:              0 :                 if (!set_plan_disabling_options(optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV))
                                683                 :                :                 {
 7539 peter_e@gmx.net           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                 :                : 
 9418 bruce@momjian.us          690                 :              0 :             case 'h':
  150 heikki.linnakangas@i      691                 :              0 :                 SetConfigOption("listen_addresses", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
 9418 bruce@momjian.us          692                 :              0 :                 break;
                                693                 :                : 
10517                           694                 :              0 :             case 'i':
 8192 tgl@sss.pgh.pa.us         695                 :              0 :                 SetConfigOption("listen_addresses", "*", PGC_POSTMASTER, PGC_S_ARGV);
 9820 bruce@momjian.us          696                 :              0 :                 break;
                                697                 :                : 
 7539 peter_e@gmx.net           698                 :              0 :             case 'j':
                                699                 :                :                 /* only used by interactive backend */
                                700                 :              0 :                 break;
                                701                 :                : 
 9418 bruce@momjian.us          702                 :CBC         103 :             case 'k':
  150 heikki.linnakangas@i      703                 :            103 :                 SetConfigOption("unix_socket_directories", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
 9418 bruce@momjian.us          704                 :            103 :                 break;
                                705                 :                : 
 9820 bruce@momjian.us          706                 :UBC           0 :             case 'l':
 8951 peter_e@gmx.net           707                 :              0 :                 SetConfigOption("ssl", "true", PGC_POSTMASTER, PGC_S_ARGV);
10520 bruce@momjian.us          708                 :              0 :                 break;
                                709                 :                : 
10051 tgl@sss.pgh.pa.us         710                 :              0 :             case 'N':
  150 heikki.linnakangas@i      711                 :              0 :                 SetConfigOption("max_connections", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
10051 tgl@sss.pgh.pa.us         712                 :              0 :                 break;
                                713                 :                : 
 7539 peter_e@gmx.net           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                 :                : 
10580 bruce@momjian.us          722                 :CBC          69 :             case 'p':
  150 heikki.linnakangas@i      723                 :             69 :                 SetConfigOption("port", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
10580 bruce@momjian.us          724                 :             69 :                 break;
                                725                 :                : 
 7539 peter_e@gmx.net           726                 :UBC           0 :             case 'r':
                                727                 :                :                 /* only used by single-user backend */
                                728                 :              0 :                 break;
                                729                 :                : 
                                730                 :              0 :             case 'S':
  150 heikki.linnakangas@i      731                 :              0 :                 SetConfigOption("work_mem", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
10580 bruce@momjian.us          732                 :              0 :                 break;
                                733                 :                : 
                                734                 :              0 :             case 's':
 7175 tgl@sss.pgh.pa.us         735                 :              0 :                 SetConfigOption("log_statement_stats", "true", PGC_POSTMASTER, PGC_S_ARGV);
 7539 peter_e@gmx.net           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                 :                :                  */
 1375 tgl@sss.pgh.pa.us         744                 :              0 :                 SetConfigOption("send_abort_for_crash", "true", PGC_POSTMASTER, PGC_S_ARGV);
10580 bruce@momjian.us          745                 :              0 :                 break;
                                746                 :                : 
 7539 peter_e@gmx.net           747                 :              0 :             case 't':
                                748                 :                :                 {
  150 heikki.linnakangas@i      749                 :              0 :                     const char *tmp = get_stats_option_name(optctx.optarg);
                                750                 :                : 
 7267 bruce@momjian.us          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                 :                : 
 7539 peter_e@gmx.net           764                 :              0 :             case 'W':
  150 heikki.linnakangas@i      765                 :              0 :                 SetConfigOption("post_auth_delay", optctx.optarg, PGC_POSTMASTER, PGC_S_ARGV);
 7539 peter_e@gmx.net           766                 :              0 :                 break;
                                767                 :                : 
10580 bruce@momjian.us          768                 :              0 :             default:
 8072                           769                 :              0 :                 write_stderr("Try \"%s --help\" for more information.\n",
                                770                 :                :                              progname);
 9402 tgl@sss.pgh.pa.us         771                 :              0 :                 ExitPostmaster(1);
                                772                 :                :         }
                                773                 :                :     }
                                774                 :                : 
                                775                 :                :     /*
                                776                 :                :      * Postmaster accepts no non-option switch arguments.
                                777                 :                :      */
  150 heikki.linnakangas@i      778         [ -  + ]:CBC        1008 :     if (optctx.optind < argc)
                                779                 :                :     {
 8072 bruce@momjian.us          780                 :UBC           0 :         write_stderr("%s: invalid argument: \"%s\"\n",
  150 heikki.linnakangas@i      781                 :              0 :                      progname, argv[optctx.optind]);
 8072 bruce@momjian.us          782                 :              0 :         write_stderr("Try \"%s --help\" for more information.\n",
                                783                 :                :                      progname);
 8951 peter_e@gmx.net           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                 :                :      */
 7993 tgl@sss.pgh.pa.us         791         [ -  + ]:CBC        1008 :     if (!SelectConfigFiles(userDoption, progname))
 7993 tgl@sss.pgh.pa.us         792                 :UBC           0 :         ExitPostmaster(2);
                                793                 :                : 
 5439 bruce@momjian.us          794         [ +  + ]:CBC        1008 :     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                 :                :          */
 1806 michael@paquier.xyz       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                 :                :          */
 1541 tgl@sss.pgh.pa.us         830                 :              1 :         SetConfigOption("log_min_messages", "FATAL", PGC_SUSET,
                                831                 :                :                         PGC_S_OVERRIDE);
                                832                 :                :     }
                                833                 :                : 
                                834                 :                :     /* Verify that DataDir looks reasonable */
 7993                           835                 :           1007 :     checkDataDir();
                                836                 :                : 
                                837                 :                :     /* Check that pg_control exists */
 3064 sfrost@snowman.net        838                 :           1007 :     checkControlFile();
                                839                 :                : 
                                840                 :                :     /* And switch working directory into it */
 7724 tgl@sss.pgh.pa.us         841                 :           1007 :     ChangeToDataDir();
                                842                 :                : 
                                843                 :                :     /*
                                844                 :                :      * Check for invalid combinations of GUC settings.
                                845                 :                :      */
 1315 rhaas@postgresql.org      846         [ -  + ]:           1007 :     if (SuperuserReservedConnections + ReservedConnections >= MaxConnections)
                                847                 :                :     {
  832 peter@eisentraut.org      848                 :UBC           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);
 5130 magnus@hagander.net       852                 :              0 :         ExitPostmaster(1);
                                853                 :                :     }
 4122 heikki.linnakangas@i      854   [ +  +  -  + ]:CBC        1007 :     if (XLogArchiveMode > ARCHIVE_MODE_OFF && wal_level == WAL_LEVEL_MINIMAL)
 5965 heikki.linnakangas@i      855         [ #  # ]:UBC           0 :         ereport(ERROR,
                                856                 :                :                 (errmsg("WAL archival cannot be enabled when \"wal_level\" is \"minimal\"")));
 5965 heikki.linnakangas@i      857   [ +  +  -  + ]:CBC        1007 :     if (max_wal_senders > 0 && wal_level == WAL_LEVEL_MINIMAL)
 5965 heikki.linnakangas@i      858         [ #  # ]:UBC           0 :         ereport(ERROR,
                                859                 :                :                 (errmsg("WAL streaming (\"max_wal_senders\" > 0) requires \"wal_level\" to be \"replica\" or \"logical\"")));
  981 rhaas@postgresql.org      860   [ +  +  -  + ]:CBC        1007 :     if (summarize_wal && wal_level == WAL_LEVEL_MINIMAL)
  981 rhaas@postgresql.org      861         [ #  # ]:UBC           0 :         ereport(ERROR,
                                862                 :                :                 (errmsg("WAL cannot be summarized when \"wal_level\" is \"minimal\"")));
  247 msawada@postgresql.o      863   [ +  +  -  + ]:CBC        1007 :     if (sync_replication_slots && wal_level == WAL_LEVEL_MINIMAL)
  371 fujii@postgresql.org      864         [ #  # ]:UBC           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                 :                :      */
 8624 tgl@sss.pgh.pa.us         871         [ -  + ]:CBC        1007 :     if (!CheckDateTokenTables())
                                872                 :                :     {
 8072 bruce@momjian.us          873                 :UBC           0 :         write_stderr("%s: invalid datetoken tables, please fix\n", progname);
 8624 tgl@sss.pgh.pa.us         874                 :              0 :         ExitPostmaster(1);
                                875                 :                :     }
                                876                 :                : 
                                877                 :                :     /* For debugging: display postmaster environment */
  638 andres@anarazel.de        878         [ +  + ]:CBC        1007 :     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:");
 9419 tgl@sss.pgh.pa.us         889         [ +  + ]:            282 :         for (p = environ; *p; ++p)
  638 andres@anarazel.de        890                 :            275 :             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                 :                :      */
 7724 tgl@sss.pgh.pa.us         910                 :           1007 :     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                 :                :      */
 3266 andres@anarazel.de        921                 :           1006 :     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                 :                :      */
 3507 peter_e@gmx.net           927                 :           1006 :     ApplyLauncherRegister();
                                928                 :                : 
                                929                 :                :     /*
                                930                 :                :      * Register the shared memory needs of all core subsystems.
                                931                 :                :      */
  143 heikki.linnakangas@i      932                 :           1006 :     RegisterBuiltinShmemCallbacks();
                                933                 :                : 
                                934                 :                :     /*
                                935                 :                :      * process any libraries that should be preloaded at postmaster start
                                936                 :                :      */
 7317 tgl@sss.pgh.pa.us         937                 :           1006 :     process_shared_preload_libraries();
                                938                 :                : 
                                939                 :                :     /*
                                940                 :                :      * Initialize SSL library, if specified.
                                941                 :                :      */
                                942                 :                : #ifdef USE_SSL
 2346 andrew@dunslane.net       943         [ +  + ]:           1006 :     if (EnableSSL)
                                944                 :                :     {
                                945                 :             48 :         (void) secure_initialize(true);
                                946                 :             35 :         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                 :                :      */
 4985 alvherre@alvh.no-ip.      955                 :            993 :     InitializeMaxBackends();
  651 heikki.linnakangas@i      956                 :            993 :     InitPostmasterChildSlots();
                                957                 :                : 
                                958                 :                :     /*
                                959                 :                :      * Calculate the size of the PGPROC fast-path lock arrays.
                                960                 :                :      */
  705 tomas.vondra@postgre      961                 :            993 :     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                 :                :      */
 1567 rhaas@postgresql.org      971                 :            993 :     process_shmem_requests();
                                972                 :                : 
                                973                 :                :     /*
                                974                 :                :      * Ask all subsystems, including preloaded libraries, to register their
                                975                 :                :      * shared memory needs.
                                976                 :                :      */
  143 heikki.linnakangas@i      977                 :            993 :     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                 :                :      */
 1814 michael@paquier.xyz       984                 :            993 :     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                 :                :      */
 1604 jdavis@postgresql.or      990                 :            993 :     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                 :                :      */
 1806 michael@paquier.xyz      1003         [ +  + ]:            993 :     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                 :                :      */
 1503 tgl@sss.pgh.pa.us        1019                 :            992 :     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                 :                :      */
 2542                          1025                 :            991 :     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                 :            991 :     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                 :            991 :     RemovePromoteSignalFiles();
                               1077                 :                : 
                               1078                 :                :     /* Do the same for logrotate signal file */
                               1079                 :            991 :     RemoveLogrotateSignalFiles();
                               1080                 :                : 
                               1081                 :                :     /* Remove any outdated file holding the current log filenames. */
                               1082   [ +  -  -  + ]:            991 :     if (unlink(LOG_METAINFO_DATAFILE) < 0 && errno != ENOENT)
 2542 tgl@sss.pgh.pa.us        1083         [ #  # ]:UBC           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                 :                :      */
  651 heikki.linnakangas@i     1091         [ +  + ]:CBC         991 :     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                 :                :      */
 2542 tgl@sss.pgh.pa.us        1105         [ -  + ]:            991 :     if (!(Log_destination & LOG_DESTINATION_STDERR))
 2542 tgl@sss.pgh.pa.us        1106         [ #  # ]:UBC           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                 :                : 
 2542 tgl@sss.pgh.pa.us        1111                 :CBC         991 :     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                 :                :      */
 2766 peter@eisentraut.org     1118         [ +  - ]:            991 :     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                 :                :      */
   10 michael@paquier.xyz      1127                 :GNC         991 :     ListenSockets = palloc_array(pgsocket, MAXLISTEN);
 1057 heikki.linnakangas@i     1128                 :CBC         991 :     on_proc_exit(CloseServerPorts, 0);
                               1129                 :                : 
 8192 tgl@sss.pgh.pa.us        1130         [ +  - ]:            991 :     if (ListenAddresses)
                               1131                 :                :     {
                               1132                 :                :         char       *rawstring;
                               1133                 :                :         List       *elemlist;
                               1134                 :                :         ListCell   *l;
 7728 peter_e@gmx.net          1135                 :            991 :         int         success = 0;
                               1136                 :                : 
                               1137                 :                :         /* Need a modifiable copy of ListenAddresses */
 8054 tgl@sss.pgh.pa.us        1138                 :            991 :         rawstring = pstrdup(ListenAddresses);
                               1139                 :                : 
                               1140                 :                :         /* Parse string into list of hostnames */
 2479                          1141         [ -  + ]:            991 :         if (!SplitGUCList(rawstring, ',', &elemlist))
                               1142                 :                :         {
                               1143                 :                :             /* syntax error in list */
 8054 tgl@sss.pgh.pa.us        1144         [ #  # ]:UBC           0 :             ereport(FATAL,
                               1145                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1146                 :                :                      errmsg("invalid list syntax in parameter \"%s\"",
                               1147                 :                :                             "listen_addresses")));
                               1148                 :                :         }
                               1149                 :                : 
 8054 tgl@sss.pgh.pa.us        1150   [ +  +  +  +  :CBC        1027 :         foreach(l, elemlist)
                                              +  + ]
                               1151                 :                :         {
 8033 bruce@momjian.us         1152                 :             36 :             char       *curhost = (char *) lfirst(l);
                               1153                 :                : 
 8127                          1154         [ -  + ]:             36 :             if (strcmp(curhost, "*") == 0)
  898 heikki.linnakangas@i     1155                 :UBC           0 :                 status = ListenServerPort(AF_UNSPEC, NULL,
 8192 tgl@sss.pgh.pa.us        1156                 :              0 :                                           (unsigned short) PostPortNumber,
                               1157                 :                :                                           NULL,
                               1158                 :                :                                           ListenSockets,
                               1159                 :                :                                           &NumListenSockets,
                               1160                 :                :                                           MAXLISTEN);
                               1161                 :                :             else
  898 heikki.linnakangas@i     1162                 :CBC          36 :                 status = ListenServerPort(AF_UNSPEC, curhost,
 8436 tgl@sss.pgh.pa.us        1163                 :             36 :                                           (unsigned short) PostPortNumber,
                               1164                 :                :                                           NULL,
                               1165                 :                :                                           ListenSockets,
                               1166                 :                :                                           &NumListenSockets,
                               1167                 :                :                                           MAXLISTEN);
                               1168                 :                : 
 7728 peter_e@gmx.net          1169         [ +  - ]:             36 :             if (status == STATUS_OK)
                               1170                 :                :             {
                               1171                 :             36 :                 success++;
                               1172                 :                :                 /* record the first successful host addr in lockfile */
 5705 tgl@sss.pgh.pa.us        1173         [ +  - ]:             36 :                 if (!listen_addr_saved)
                               1174                 :                :                 {
                               1175                 :             36 :                     AddToDataDirLockFile(LOCK_FILE_LINE_LISTEN_ADDR, curhost);
                               1176                 :             36 :                     listen_addr_saved = true;
                               1177                 :                :                 }
                               1178                 :                :             }
                               1179                 :                :             else
 8192 tgl@sss.pgh.pa.us        1180         [ #  # ]:UBC           0 :                 ereport(WARNING,
                               1181                 :                :                         (errmsg("could not create listen socket for \"%s\"",
                               1182                 :                :                                 curhost)));
                               1183                 :                :         }
                               1184                 :                : 
 5130 tgl@sss.pgh.pa.us        1185   [ +  +  -  + ]:CBC         991 :         if (!success && elemlist != NIL)
 7728 peter_e@gmx.net          1186         [ #  # ]:UBC           0 :             ereport(FATAL,
                               1187                 :                :                     (errmsg("could not create any TCP/IP sockets")));
                               1188                 :                : 
 8054 tgl@sss.pgh.pa.us        1189                 :CBC         991 :         list_free(elemlist);
                               1190                 :            991 :         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                 :                : 
 5130                          1232         [ +  - ]:            991 :     if (Unix_socket_directories)
                               1233                 :                :     {
                               1234                 :                :         char       *rawstring;
                               1235                 :                :         List       *elemlist;
                               1236                 :                :         ListCell   *l;
                               1237                 :            991 :         int         success = 0;
                               1238                 :                : 
                               1239                 :                :         /* Need a modifiable copy of Unix_socket_directories */
                               1240                 :            991 :         rawstring = pstrdup(Unix_socket_directories);
                               1241                 :                : 
                               1242                 :                :         /* Parse string into list of directories */
                               1243         [ -  + ]:            991 :         if (!SplitDirectoriesString(rawstring, ',', &elemlist))
                               1244                 :                :         {
                               1245                 :                :             /* syntax error in list */
 5130 tgl@sss.pgh.pa.us        1246         [ #  # ]:UBC           0 :             ereport(FATAL,
                               1247                 :                :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                               1248                 :                :                      errmsg("invalid list syntax in parameter \"%s\"",
                               1249                 :                :                             "unix_socket_directories")));
                               1250                 :                :         }
                               1251                 :                : 
 5130 tgl@sss.pgh.pa.us        1252   [ +  -  +  +  :CBC        1982 :         foreach(l, elemlist)
                                              +  + ]
                               1253                 :                :         {
                               1254                 :            991 :             char       *socketdir = (char *) lfirst(l);
                               1255                 :                : 
  898 heikki.linnakangas@i     1256                 :            991 :             status = ListenServerPort(AF_UNIX, NULL,
 5130 tgl@sss.pgh.pa.us        1257                 :            991 :                                       (unsigned short) PostPortNumber,
                               1258                 :                :                                       socketdir,
                               1259                 :                :                                       ListenSockets,
                               1260                 :                :                                       &NumListenSockets,
                               1261                 :                :                                       MAXLISTEN);
                               1262                 :                : 
                               1263         [ +  - ]:            991 :             if (status == STATUS_OK)
                               1264                 :                :             {
                               1265                 :            991 :                 success++;
                               1266                 :                :                 /* record the first successful Unix socket in lockfile */
                               1267         [ +  - ]:            991 :                 if (success == 1)
                               1268                 :            991 :                     AddToDataDirLockFile(LOCK_FILE_LINE_SOCKET_DIR, socketdir);
                               1269                 :                :             }
                               1270                 :                :             else
 5130 tgl@sss.pgh.pa.us        1271         [ #  # ]:UBC           0 :                 ereport(WARNING,
                               1272                 :                :                         (errmsg("could not create Unix-domain socket in directory \"%s\"",
                               1273                 :                :                                 socketdir)));
                               1274                 :                :         }
                               1275                 :                : 
 5130 tgl@sss.pgh.pa.us        1276   [ -  +  -  - ]:CBC         991 :         if (!success && elemlist != NIL)
 5130 tgl@sss.pgh.pa.us        1277         [ #  # ]:UBC           0 :             ereport(FATAL,
                               1278                 :                :                     (errmsg("could not create any Unix-domain sockets")));
                               1279                 :                : 
 5130 tgl@sss.pgh.pa.us        1280                 :CBC         991 :         list_free_deep(elemlist);
                               1281                 :            991 :         pfree(rawstring);
                               1282                 :                :     }
                               1283                 :                : 
                               1284                 :                :     /*
                               1285                 :                :      * check that we have some socket to listen on
                               1286                 :                :      */
 1057 heikki.linnakangas@i     1287         [ -  + ]:            991 :     if (NumListenSockets == 0)
 8192 tgl@sss.pgh.pa.us        1288         [ #  # ]:UBC           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                 :                :      */
 5705 tgl@sss.pgh.pa.us        1296         [ +  + ]:CBC         991 :     if (!listen_addr_saved)
                               1297                 :            955 :         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                 :                :      */
 8141 bruce@momjian.us         1303         [ -  + ]:            991 :     if (!CreateOptsFile(argc, argv, my_exec_path))
 9402 tgl@sss.pgh.pa.us        1304                 :UBC           0 :         ExitPostmaster(1);
                               1305                 :                : 
                               1306                 :                :     /*
                               1307                 :                :      * Write the external PID file if requested
                               1308                 :                :      */
 7992 tgl@sss.pgh.pa.us        1309         [ -  + ]:CBC         991 :     if (external_pid_file)
                               1310                 :                :     {
 7992 tgl@sss.pgh.pa.us        1311                 :UBC           0 :         FILE       *fpidfile = fopen(external_pid_file, "w");
                               1312                 :                : 
 7993                          1313         [ #  # ]:              0 :         if (fpidfile)
                               1314                 :                :         {
                               1315                 :              0 :             fprintf(fpidfile, "%d\n", MyProcPid);
                               1316                 :              0 :             fclose(fpidfile);
                               1317                 :                : 
                               1318                 :                :             /* Make PID file world readable */
 5548 peter_e@gmx.net          1319         [ #  # ]:              0 :             if (chmod(external_pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) != 0)
  898 michael@paquier.xyz      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                 :                : 
 5120 peter_e@gmx.net          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                 :                :      */
 4244 andres@anarazel.de       1334                 :CBC         991 :     RemovePgTempFiles();
                               1335                 :                : 
                               1336                 :                :     /*
                               1337                 :                :      * Initialize the autovacuum subsystem (again, no process start yet)
                               1338                 :                :      */
 7338 tgl@sss.pgh.pa.us        1339                 :            991 :     autovac_init();
                               1340                 :                : 
                               1341                 :                :     /*
                               1342                 :                :      * Load configuration files for client authentication.
                               1343                 :                :      */
 6212                          1344         [ -  + ]:            991 :     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                 :                :          */
 6212 tgl@sss.pgh.pa.us        1350         [ #  # ]:UBC           0 :         ereport(FATAL,
                               1351                 :                :         /* translator: %s is a configuration file */
                               1352                 :                :                 (errmsg("could not load %s", HbaFileName)));
                               1353                 :                :     }
 5088 heikki.linnakangas@i     1354                 :CBC         991 :     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                 :                :      */
 7729 tgl@sss.pgh.pa.us        1387                 :            991 :     PgStartTime = GetCurrentTimestamp();
                               1388                 :                : 
                               1389                 :                :     /*
                               1390                 :                :      * Report postmaster status in the postmaster.pid file, to allow pg_ctl to
                               1391                 :                :      * see what's happening.
                               1392                 :                :      */
 3347                          1393                 :            991 :     AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STARTING);
                               1394                 :                : 
  527 andres@anarazel.de       1395                 :            991 :     UpdatePMState(PM_STARTUP);
                               1396                 :                : 
                               1397                 :                :     /* Make sure we can perform I/O while starting up. */
  141 tmunro@postgresql.or     1398                 :            991 :     maybe_start_io_workers();
                               1399                 :                : 
                               1400                 :                :     /* Start bgwriter and checkpointer so they can help with recovery */
  651 heikki.linnakangas@i     1401         [ +  - ]:            991 :     if (CheckpointerPMChild == NULL)
                               1402                 :            991 :         CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
                               1403         [ +  - ]:            991 :     if (BgWriterPMChild == NULL)
                               1404                 :            991 :         BgWriterPMChild = StartChildProcess(B_BG_WRITER);
                               1405                 :                : 
                               1406                 :                :     /*
                               1407                 :                :      * We're ready to rock and roll...
                               1408                 :                :      */
                               1409                 :            991 :     StartupPMChild = StartChildProcess(B_STARTUP);
                               1410         [ -  + ]:            991 :     Assert(StartupPMChild != NULL);
 4067 tgl@sss.pgh.pa.us        1411                 :            991 :     StartupStatus = STARTUP_RUNNING;
                               1412                 :                : 
                               1413                 :                :     /* Some workers may be scheduled to start now */
 3410                          1414                 :            991 :     maybe_start_bgworkers();
                               1415                 :                : 
10581 bruce@momjian.us         1416                 :            991 :     status = ServerLoop();
                               1417                 :                : 
                               1418                 :                :     /*
                               1419                 :                :      * ServerLoop probably shouldn't ever return, but if it does, close down.
                               1420                 :                :      */
10581 bruce@momjian.us         1421                 :UBC           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
 4043 tgl@sss.pgh.pa.us        1431                 :CBC         991 : 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                 :                :      */
 1057 heikki.linnakangas@i     1441         [ +  + ]:           2018 :     for (i = 0; i < NumListenSockets; i++)
                               1442                 :                :     {
  898                          1443         [ -  + ]:           1027 :         if (closesocket(ListenSockets[i]) != 0)
  898 heikki.linnakangas@i     1444         [ #  # ]:UBC           0 :             elog(LOG, "could not close listen socket: %m");
                               1445                 :                :     }
 1057 heikki.linnakangas@i     1446                 :CBC         991 :     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                 :                :      */
 4043 tgl@sss.pgh.pa.us        1453                 :            991 :     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                 :            991 : }
                               1460                 :                : 
                               1461                 :                : /*
                               1462                 :                :  * on_proc_exit callback to delete external_pid_file
                               1463                 :                :  */
                               1464                 :                : static void
 5120 peter_e@gmx.net          1465                 :UBC           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
 6326 tgl@sss.pgh.pa.us        1477                 :CBC        1012 : getInstallationPaths(const char *argv0)
                               1478                 :                : {
                               1479                 :                :     DIR        *pdir;
                               1480                 :                : 
                               1481                 :                :     /* Locate the postgres executable itself */
                               1482         [ -  + ]:           1012 :     if (find_my_exec(argv0, my_exec_path) < 0)
 2092 peter@eisentraut.org     1483         [ #  # ]:UBC           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                 :                :      */
 6326 tgl@sss.pgh.pa.us        1499                 :CBC        1012 :     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                 :           1012 :     pdir = AllocateDir(pkglib_path);
                               1509         [ -  + ]:           1012 :     if (pdir == NULL)
 6326 tgl@sss.pgh.pa.us        1510         [ #  # ]:UBC           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)));
 6326 tgl@sss.pgh.pa.us        1516                 :CBC        1012 :     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                 :           1012 : }
                               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
 3064 sfrost@snowman.net       1531                 :           1007 : checkControlFile(void)
                               1532                 :                : {
                               1533                 :                :     char        path[MAXPGPATH];
                               1534                 :                :     FILE       *fp;
                               1535                 :                : 
  507 fujii@postgresql.org     1536                 :           1007 :     snprintf(path, sizeof(path), "%s/%s", DataDir, XLOG_CONTROL_FILE);
                               1537                 :                : 
 8126 tgl@sss.pgh.pa.us        1538                 :           1007 :     fp = AllocateFile(path, PG_BINARY_R);
                               1539         [ -  + ]:           1007 :     if (fp == NULL)
                               1540                 :                :     {
 8072 bruce@momjian.us         1541                 :UBC           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);
 8126 tgl@sss.pgh.pa.us        1545                 :              0 :         ExitPostmaster(2);
                               1546                 :                :     }
 8126 tgl@sss.pgh.pa.us        1547                 :CBC        1007 :     FreeFile(fp);
                               1548                 :           1007 : }
                               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
 1323 tmunro@postgresql.or     1560                 :          45724 : 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                 :                :      */
  141                          1570         [ +  + ]:          45724 :     if (Shutdown >= ImmediateShutdown)
                               1571                 :                :     {
 4087 tgl@sss.pgh.pa.us        1572         [ +  - ]:           1495 :         if (AbortStartTime != 0)
                               1573                 :                :         {
  309                          1574                 :           1495 :             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         [ +  - ]:           1495 :             if (curtime < AbortStartTime ||
                               1582         [ -  + ]:           1495 :                 curtime - AbortStartTime >= SIGKILL_CHILDREN_AFTER_SECS)
  309 tgl@sss.pgh.pa.us        1583                 :UBC           0 :                 seconds = 0;
                               1584                 :                :             else
  309 tgl@sss.pgh.pa.us        1585                 :CBC        1495 :                 seconds = SIGKILL_CHILDREN_AFTER_SECS -
                               1586                 :                :                     (curtime - AbortStartTime);
                               1587                 :                : 
                               1588                 :           1495 :             return seconds * 1000;
                               1589                 :                :         }
                               1590                 :                :     }
                               1591                 :                : 
                               1592                 :                :     /* Time of next maybe_start_io_workers() call, or 0 for none. */
  141 tmunro@postgresql.or     1593                 :          44229 :     next_wakeup = maybe_start_io_workers_scheduled_at();
                               1594                 :                : 
                               1595                 :                :     /* Ignore bgworkers during shutdown. */
                               1596   [ -  +  -  - ]:          44229 :     if (StartWorkerNeeded && Shutdown == NoShutdown)
 1323 tmunro@postgresql.or     1597                 :UBC           0 :         return 0;
                               1598                 :                : 
  141 tmunro@postgresql.or     1599   [ +  +  -  + ]:CBC       44229 :     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                 :                :          */
  748 heikki.linnakangas@i     1609   [ #  #  #  # ]:UBC           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                 :                : 
 5012 alvherre@alvh.no-ip.     1616         [ #  # ]:              0 :             if (rw->rw_crashed_at == 0)
                               1617                 :              0 :                 continue;
                               1618                 :                : 
 4696 rhaas@postgresql.org     1619         [ #  # ]:              0 :             if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART
                               1620         [ #  # ]:              0 :                 || rw->rw_terminate)
                               1621                 :                :             {
  748 heikki.linnakangas@i     1622                 :              0 :                 ForgetBackgroundWorker(rw);
 5012 alvherre@alvh.no-ip.     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                 :                : 
 5012 alvherre@alvh.no-ip.     1633         [ +  + ]:CBC       44229 :     if (next_wakeup != 0)
                               1634                 :                :     {
                               1635                 :                :         int         ms;
                               1636                 :                : 
                               1637                 :                :         /* result of TimestampDifferenceMilliseconds is in [0, INT_MAX] */
 1309 tgl@sss.pgh.pa.us        1638                 :             34 :         ms = (int) TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
                               1639                 :                :                                                    next_wakeup);
                               1640                 :             34 :         return Min(60 * 1000, ms);
                               1641                 :                :     }
                               1642                 :                : 
 1323 tmunro@postgresql.or     1643                 :          44195 :     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                 :           1992 : ConfigurePostmasterWaitSet(bool accept_connections)
                               1657                 :                : {
                               1658         [ +  + ]:           1992 :     if (pm_wait_set)
                               1659                 :           1001 :         FreeWaitEventSet(pm_wait_set);
                               1660                 :           1992 :     pm_wait_set = NULL;
                               1661                 :                : 
 1008 heikki.linnakangas@i     1662                 :           3984 :     pm_wait_set = CreateWaitEventSet(NULL,
 1057                          1663                 :           1992 :                                      accept_connections ? (1 + NumListenSockets) : 1);
 1323 tmunro@postgresql.or     1664                 :           1992 :     AddWaitEventToSet(pm_wait_set, WL_LATCH_SET, PGINVALID_SOCKET, MyLatch,
                               1665                 :                :                       NULL);
                               1666                 :                : 
                               1667         [ +  + ]:           1992 :     if (accept_connections)
                               1668                 :                :     {
 1057 heikki.linnakangas@i     1669         [ +  + ]:           2028 :         for (int i = 0; i < NumListenSockets; i++)
                               1670                 :           1032 :             AddWaitEventToSet(pm_wait_set, WL_SOCKET_ACCEPT, ListenSockets[i],
                               1671                 :                :                               NULL, NULL);
                               1672                 :                :     }
 1323 tmunro@postgresql.or     1673                 :           1992 : }
                               1674                 :                : 
                               1675                 :                : /*
                               1676                 :                :  * Main idle loop of postmaster
                               1677                 :                :  */
                               1678                 :                : static int
10919 scrappy@hub.org          1679                 :            991 : ServerLoop(void)
                               1680                 :                : {
                               1681                 :                :     time_t      last_lockfile_recheck_time,
                               1682                 :                :                 last_touch_time;
                               1683                 :                :     WaitEvent   events[MAXLISTEN];
                               1684                 :                :     int         nevents;
                               1685                 :                : 
 1323 tmunro@postgresql.or     1686                 :            991 :     ConfigurePostmasterWaitSet(true);
 3978 tgl@sss.pgh.pa.us        1687                 :            991 :     last_lockfile_recheck_time = last_touch_time = time(NULL);
                               1688                 :                : 
                               1689                 :                :     for (;;)
10581 bruce@momjian.us         1690                 :          44733 :     {
                               1691                 :                :         time_t      now;
                               1692                 :                : 
 1323 tmunro@postgresql.or     1693                 :          45724 :         nevents = WaitEventSetWait(pm_wait_set,
                               1694                 :          45724 :                                    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         [ +  + ]:          90451 :         for (int i = 0; i < nevents; i++)
                               1704                 :                :         {
                               1705         [ +  + ]:          45718 :             if (events[i].events & WL_LATCH_SET)
                               1706                 :          30103 :                 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                 :                :              */
 1310                          1715         [ +  + ]:          45718 :             if (pending_pm_shutdown_request)
                               1716                 :            980 :                 process_pm_shutdown_request();
                               1717         [ +  + ]:          45718 :             if (pending_pm_reload_request)
                               1718                 :            172 :                 process_pm_reload_request();
                               1719         [ +  + ]:          45718 :             if (pending_pm_child_exit)
                               1720                 :          24328 :                 process_pm_child_exit();
                               1721         [ +  + ]:          44727 :             if (pending_pm_pmsignal)
                               1722                 :           4684 :                 process_pm_pmsignal();
                               1723                 :                : 
                               1724         [ +  + ]:          44727 :             if (events[i].events & WL_SOCKET_ACCEPT)
                               1725                 :                :             {
                               1726                 :                :                 ClientSocket s;
                               1727                 :                : 
  898 heikki.linnakangas@i     1728         [ +  - ]:          15615 :                 if (AcceptConnection(events[i].fd, &s) == STATUS_OK)
                               1729                 :          15615 :                     BackendStartup(&s);
                               1730                 :                : 
                               1731                 :                :                 /* We no longer need the open socket in this process */
                               1732         [ +  - ]:          15615 :                 if (s.sock != PGINVALID_SOCKET)
                               1733                 :                :                 {
                               1734         [ -  + ]:          15615 :                     if (closesocket(s.sock) != 0)
  898 heikki.linnakangas@i     1735         [ #  # ]:UBC           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                 :                :          */
  745 heikki.linnakangas@i     1744                 :CBC       44733 :         LaunchMissingBackgroundProcesses();
                               1745                 :                : 
                               1746                 :                :         /* If we need to signal the autovacuum launcher, do so now */
 6212 alvherre@alvh.no-ip.     1747         [ -  + ]:          44733 :         if (avlauncher_needs_signal)
                               1748                 :                :         {
 6212 alvherre@alvh.no-ip.     1749                 :UBC           0 :             avlauncher_needs_signal = false;
  651 heikki.linnakangas@i     1750         [ #  # ]:              0 :             if (AutoVacLauncherPMChild != NULL)
  594 andres@anarazel.de       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                 :                :          */
 3975 tgl@sss.pgh.pa.us        1771                 :CBC       44733 :         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                 :                :          */
 1375                          1782   [ +  +  +  + ]:          44733 :         if ((Shutdown >= ImmediateShutdown || FatalError) &&
 4087                          1783         [ +  + ]:           1566 :             AbortStartTime != 0 &&
                               1784         [ -  + ]:           1557 :             (now - AbortStartTime) >= SIGKILL_CHILDREN_AFTER_SECS)
                               1785                 :                :         {
                               1786                 :                :             /* We were gentle with them before. Not anymore */
 2176 tgl@sss.pgh.pa.us        1787   [ #  #  #  # ]:UBC           0 :             ereport(LOG,
                               1788                 :                :             /* translator: %s is SIGKILL or SIGABRT */
                               1789                 :                :                     (errmsg("issuing %s to recalcitrant children",
                               1790                 :                :                             send_abort_for_kill ? "SIGABRT" : "SIGKILL")));
 1375                          1791         [ #  # ]:              0 :             TerminateChildren(send_abort_for_kill ? SIGABRT : SIGKILL);
                               1792                 :                :             /* reset flag so we don't SIGKILL again */
 4709 alvherre@alvh.no-ip.     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                 :                :          */
 3978 tgl@sss.pgh.pa.us        1806         [ +  + ]:CBC       44733 :         if (now - last_lockfile_recheck_time >= 1 * SECS_PER_MINUTE)
                               1807                 :                :         {
                               1808         [ -  + ]:             42 :             if (!RecheckDataDirLockFile())
                               1809                 :                :             {
 3978 tgl@sss.pgh.pa.us        1810         [ #  # ]:UBC           0 :                 ereport(LOG,
                               1811                 :                :                         (errmsg("performing immediate shutdown because data directory lock file is invalid")));
                               1812                 :              0 :                 kill(MyProcPid, SIGQUIT);
                               1813                 :                :             }
 3978 tgl@sss.pgh.pa.us        1814                 :CBC          42 :             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         [ -  + ]:          44733 :         if (now - last_touch_time >= 58 * SECS_PER_MINUTE)
                               1823                 :                :         {
 3978 tgl@sss.pgh.pa.us        1824                 :UBC           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
  651 heikki.linnakangas@i     1838                 :CBC       15771 : canAcceptConnections(BackendType backend_type)
                               1839                 :                : {
 5765 tgl@sss.pgh.pa.us        1840                 :          15771 :     CAC_state   result = CAC_OK;
                               1841                 :                : 
  651 heikki.linnakangas@i     1842   [ +  +  -  + ]:          15771 :     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   [ +  +  +  + ]:          15771 :     if (pmState != PM_RUN && pmState != PM_HOT_STANDBY)
                               1850                 :                :     {
 2204 tgl@sss.pgh.pa.us        1851         [ +  + ]:            260 :         if (Shutdown > NoShutdown)
 6860 bruce@momjian.us         1852                 :             55 :             return CAC_SHUTDOWN;    /* shutdown is pending */
 1981 fujii@postgresql.org     1853   [ +  +  +  + ]:            205 :         else if (!FatalError && pmState == PM_STARTUP)
 5618 bruce@momjian.us         1854                 :            194 :             return CAC_STARTUP; /* normal startup */
 1981 fujii@postgresql.org     1855   [ +  +  +  - ]:             11 :         else if (!FatalError && pmState == PM_RECOVERY)
  512                          1856                 :              7 :             return CAC_NOTHOTSTANDBY;   /* not yet ready for hot standby */
                               1857                 :                :         else
 5765 tgl@sss.pgh.pa.us        1858                 :              4 :             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                 :                :      */
  651 heikki.linnakangas@i     1865   [ -  +  -  - ]:          15511 :     if (!connsAllowed && backend_type == B_BACKEND)
 1604 sfrost@snowman.net       1866                 :UBC           0 :         return CAC_SHUTDOWN;    /* shutdown is pending */
                               1867                 :                : 
 5765 tgl@sss.pgh.pa.us        1868                 :CBC       15511 :     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
 8057                          1882                 :          23502 : ClosePostmasterPorts(bool am_syslogger)
                               1883                 :                : {
                               1884                 :                :     /* Release resources held by the postmaster's WaitEventSet. */
 1323 tmunro@postgresql.or     1885         [ +  + ]:          23502 :     if (pm_wait_set)
                               1886                 :                :     {
                               1887                 :          20073 :         FreeWaitEventSetAfterFork(pm_wait_set);
                               1888                 :          20073 :         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                 :                :      */
 2609 peter@eisentraut.org     1898         [ -  + ]:          23502 :     if (close(postmaster_alive_fds[POSTMASTER_FD_OWN]) != 0)
 5529 heikki.linnakangas@i     1899         [ #  # ]:UBC           0 :         ereport(FATAL,
                               1900                 :                :                 (errcode_for_file_access(),
                               1901                 :                :                  errmsg_internal("could not close postmaster death monitoring pipe in child process: %m")));
 5529 heikki.linnakangas@i     1902                 :CBC       23502 :     postmaster_alive_fds[POSTMASTER_FD_OWN] = -1;
                               1903                 :                :     /* Notify fd.c that we released one pipe FD. */
 2376 tgl@sss.pgh.pa.us        1904                 :          23502 :     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
 1056 heikki.linnakangas@i     1915         [ +  + ]:          23502 :     if (ListenSockets)
                               1916                 :                :     {
                               1917         [ +  + ]:          47428 :         for (int i = 0; i < NumListenSockets; i++)
                               1918                 :                :         {
  898                          1919         [ -  + ]:          23927 :             if (closesocket(ListenSockets[i]) != 0)
  898 heikki.linnakangas@i     1920         [ #  # ]:UBC           0 :                 elog(LOG, "could not close listen socket: %m");
                               1921                 :                :         }
 1056 heikki.linnakangas@i     1922                 :CBC       23501 :         pfree(ListenSockets);
                               1923                 :                :     }
 1057                          1924                 :          23502 :     NumListenSockets = 0;
                               1925                 :          23502 :     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                 :                :      */
 8057 tgl@sss.pgh.pa.us        1932         [ +  + ]:          23502 :     if (!am_syslogger)
                               1933                 :                :     {
                               1934                 :                : #ifndef WIN32
                               1935         [ +  + ]:          23501 :         if (syslogPipe[0] >= 0)
                               1936                 :             16 :             close(syslogPipe[0]);
                               1937                 :          23501 :         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
 9331                          1950                 :          23502 : }
                               1951                 :                : 
                               1952                 :                : 
                               1953                 :                : /*
                               1954                 :                :  * InitProcessGlobals -- set MyStartTime[stamp], random seeds
                               1955                 :                :  *
                               1956                 :                :  * Called early in the postmaster and every backend.
                               1957                 :                :  */
                               1958                 :                : void
 2869 tmunro@postgresql.or     1959                 :          24781 : InitProcessGlobals(void)
                               1960                 :                : {
                               1961                 :          24781 :     MyStartTimestamp = GetCurrentTimestamp();
                               1962                 :          24781 :     MyStartTime = timestamptz_to_time_t(MyStartTimestamp);
                               1963                 :                : 
                               1964                 :                :     /* initialize timing infrastructure (required for INSTR_* calls) */
  142 andres@anarazel.de       1965                 :          24781 :     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                 :                :      */
 1733 tgl@sss.pgh.pa.us        1972   [ +  -  -  + ]:          24781 :     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                 :                :          */
 2798 tgl@sss.pgh.pa.us        1983                 :UBC           0 :         rseed = ((uint64) MyProcPid) ^
 2842 tmunro@postgresql.or     1984                 :              0 :             ((uint64) MyStartTimestamp << 12) ^
 2798 tgl@sss.pgh.pa.us        1985                 :              0 :             ((uint64) MyStartTimestamp >> 20);
                               1986                 :                : 
 1733                          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
 1733 tgl@sss.pgh.pa.us        1995                 :CBC       24781 :     srandom(pg_prng_uint32(&pg_global_prng_state));
                               1996                 :                : #endif
 2869 tmunro@postgresql.or     1997                 :          24781 : }
                               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
 1323                          2004                 :           4732 : handle_pm_pmsignal_signal(SIGNAL_ARGS)
                               2005                 :                : {
                               2006                 :           4732 :     pending_pm_pmsignal = true;
                               2007                 :           4732 :     SetLatch(MyLatch);
                               2008                 :           4732 : }
                               2009                 :                : 
                               2010                 :                : /*
                               2011                 :                :  * pg_ctl uses SIGHUP to request a reload of the configuration files.
                               2012                 :                :  */
                               2013                 :                : static void
                               2014                 :            172 : handle_pm_reload_request_signal(SIGNAL_ARGS)
                               2015                 :                : {
                               2016                 :            172 :     pending_pm_reload_request = true;
                               2017                 :            172 :     SetLatch(MyLatch);
                               2018                 :            172 : }
                               2019                 :                : 
                               2020                 :                : /*
                               2021                 :                :  * Re-read config files, and tell children to do same.
                               2022                 :                :  */
                               2023                 :                : static void
                               2024                 :            172 : process_pm_reload_request(void)
                               2025                 :                : {
                               2026                 :            172 :     pending_pm_reload_request = false;
                               2027                 :                : 
                               2028         [ +  + ]:            172 :     ereport(DEBUG2,
                               2029                 :                :             (errmsg_internal("postmaster received reload request signal")));
                               2030                 :                : 
 9205 tgl@sss.pgh.pa.us        2031         [ +  - ]:            172 :     if (Shutdown <= SmartShutdown)
                               2032                 :                :     {
 8437                          2033         [ +  - ]:            172 :         ereport(LOG,
                               2034                 :                :                 (errmsg("received SIGHUP, reloading configuration files")));
 9062                          2035                 :            172 :         ProcessConfigFile(PGC_SIGHUP);
  651 heikki.linnakangas@i     2036                 :            172 :         SignalChildren(SIGHUP, btmask_all_except(B_DEAD_END_BACKEND));
                               2037                 :                : 
                               2038                 :                :         /* Reload authentication config files too */
 6555 magnus@hagander.net      2039         [ -  + ]:            172 :         if (!load_hba())
 3524 tgl@sss.pgh.pa.us        2040         [ #  # ]:UBC           0 :             ereport(LOG,
                               2041                 :                :             /* translator: %s is a configuration file */
                               2042                 :                :                     (errmsg("%s was not reloaded", HbaFileName)));
                               2043                 :                : 
 5088 heikki.linnakangas@i     2044         [ -  + ]:CBC         172 :         if (!load_ident())
 3524 tgl@sss.pgh.pa.us        2045         [ #  # ]:UBC           0 :             ereport(LOG,
                               2046                 :                :                     (errmsg("%s was not reloaded", IdentFileName)));
                               2047                 :                : 
                               2048                 :                : #ifdef USE_SSL
                               2049                 :                :         /* Reload SSL configuration as well */
 3524 tgl@sss.pgh.pa.us        2050         [ +  + ]:CBC         172 :         if (EnableSSL)
                               2051                 :                :         {
                               2052         [ +  + ]:             13 :             if (secure_initialize(false) == 0)
                               2053                 :             11 :                 LoadedSSL = true;
                               2054                 :                :             else
                               2055         [ +  - ]:              2 :                 ereport(LOG,
                               2056                 :                :                         (errmsg("SSL configuration was not reloaded")));
                               2057                 :                :         }
                               2058                 :                :         else
                               2059                 :                :         {
                               2060                 :            159 :             secure_destroy();
                               2061                 :            159 :             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                 :                :     }
 1323 tmunro@postgresql.or     2070                 :            172 : }
                               2071                 :                : 
                               2072                 :                : /*
                               2073                 :                :  * pg_ctl uses SIGTERM, SIGINT and SIGQUIT to request different types of
                               2074                 :                :  * shutdown.
                               2075                 :                :  */
                               2076                 :                : static void
                               2077                 :            980 : handle_pm_shutdown_request_signal(SIGNAL_ARGS)
                               2078                 :                : {
                               2079   [ +  +  +  - ]:            980 :     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                 :            573 :         case SIGINT:
                               2086                 :            573 :             pending_pm_fast_shutdown_request = true;
                               2087                 :            573 :             pending_pm_shutdown_request = true;
                               2088                 :            573 :             break;
                               2089                 :            358 :         case SIGQUIT:
                               2090                 :            358 :             pending_pm_immediate_shutdown_request = true;
                               2091                 :            358 :             pending_pm_shutdown_request = true;
                               2092                 :            358 :             break;
                               2093                 :                :     }
                               2094                 :            980 :     SetLatch(MyLatch);
 9584 peter_e@gmx.net          2095                 :            980 : }
                               2096                 :                : 
                               2097                 :                : /*
                               2098                 :                :  * Process shutdown request.
                               2099                 :                :  */
                               2100                 :                : static void
 1323 tmunro@postgresql.or     2101                 :            980 : process_pm_shutdown_request(void)
                               2102                 :                : {
                               2103                 :                :     int         mode;
                               2104                 :                : 
 8416 tgl@sss.pgh.pa.us        2105         [ +  + ]:            980 :     ereport(DEBUG2,
                               2106                 :                :             (errmsg_internal("postmaster received shutdown request signal")));
                               2107                 :                : 
 1323 tmunro@postgresql.or     2108                 :            980 :     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         [ +  + ]:            980 :     if (pending_pm_immediate_shutdown_request)
                               2116                 :                :     {
                               2117                 :            358 :         pending_pm_immediate_shutdown_request = false;
                               2118                 :            358 :         pending_pm_fast_shutdown_request = false;
                               2119                 :            358 :         mode = ImmediateShutdown;
                               2120                 :                :     }
                               2121         [ +  + ]:            622 :     else if (pending_pm_fast_shutdown_request)
                               2122                 :                :     {
                               2123                 :            573 :         pending_pm_fast_shutdown_request = false;
                               2124                 :            573 :         mode = FastShutdown;
                               2125                 :                :     }
                               2126                 :                :     else
                               2127                 :             49 :         mode = SmartShutdown;
                               2128                 :                : 
                               2129   [ +  +  +  - ]:            980 :     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                 :                :              */
 9822 vadim4o@yahoo.com        2138         [ -  + ]:             49 :             if (Shutdown >= SmartShutdown)
 9062 tgl@sss.pgh.pa.us        2139                 :UBC           0 :                 break;
 9822 vadim4o@yahoo.com        2140                 :CBC          49 :             Shutdown = SmartShutdown;
 8437 tgl@sss.pgh.pa.us        2141         [ +  - ]:             49 :             ereport(LOG,
                               2142                 :                :                     (errmsg("received smart shutdown request")));
                               2143                 :                : 
                               2144                 :                :             /* Report status */
 3347                          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                 :                :              */
 1604 sfrost@snowman.net       2155   [ -  +  -  - ]:             49 :             if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
                               2156                 :             49 :                 connsAllowed = false;
 2204 tgl@sss.pgh.pa.us        2157   [ #  #  #  # ]:UBC           0 :             else if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
                               2158                 :                :             {
                               2159                 :                :                 /* There should be no clients, so proceed to stop children */
  594 andres@anarazel.de       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                 :                :              */
 6958 tgl@sss.pgh.pa.us        2168                 :CBC          49 :             PostmasterStateMachine();
 9062                          2169                 :             49 :             break;
                               2170                 :                : 
 1323 tmunro@postgresql.or     2171                 :            573 :         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                 :                :              */
 9822 vadim4o@yahoo.com        2179         [ -  + ]:            573 :             if (Shutdown >= FastShutdown)
 9062 tgl@sss.pgh.pa.us        2180                 :UBC           0 :                 break;
 8233 tgl@sss.pgh.pa.us        2181                 :CBC         573 :             Shutdown = FastShutdown;
 8437                          2182         [ +  - ]:            573 :             ereport(LOG,
                               2183                 :                :                     (errmsg("received fast shutdown request")));
                               2184                 :                : 
                               2185                 :                :             /* Report status */
 3347                          2186                 :            573 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_STOPPING);
                               2187                 :                : #ifdef USE_SYSTEMD
                               2188                 :                :             sd_notify(0, "STOPPING=1");
                               2189                 :                : #endif
                               2190                 :                : 
 2920 michael@paquier.xyz      2191   [ +  -  -  + ]:            573 :             if (pmState == PM_STARTUP || pmState == PM_RECOVERY)
                               2192                 :                :             {
                               2193                 :                :                 /* Just shut down background processes silently */
  594 andres@anarazel.de       2194                 :UBC           0 :                 UpdatePMState(PM_STOP_BACKENDS);
                               2195                 :                :             }
 5908 rhaas@postgresql.org     2196         [ +  + ]:CBC         573 :             else if (pmState == PM_RUN ||
                               2197         [ +  - ]:             70 :                      pmState == PM_HOT_STANDBY)
                               2198                 :                :             {
                               2199                 :                :                 /* Report that we're about to zap live client sessions */
 6958 tgl@sss.pgh.pa.us        2200         [ +  - ]:            573 :                 ereport(LOG,
                               2201                 :                :                         (errmsg("aborting any active transactions")));
  594 andres@anarazel.de       2202                 :            573 :                 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                 :                :              */
 6958 tgl@sss.pgh.pa.us        2209                 :            573 :             PostmasterStateMachine();
 9062                          2210                 :            573 :             break;
                               2211                 :                : 
 1323 tmunro@postgresql.or     2212                 :            358 :         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                 :                :              */
 4808 alvherre@alvh.no-ip.     2221         [ -  + ]:            358 :             if (Shutdown >= ImmediateShutdown)
 4808 alvherre@alvh.no-ip.     2222                 :UBC           0 :                 break;
 4808 alvherre@alvh.no-ip.     2223                 :CBC         358 :             Shutdown = ImmediateShutdown;
 8437 tgl@sss.pgh.pa.us        2224         [ +  - ]:            358 :             ereport(LOG,
                               2225                 :                :                     (errmsg("received immediate shutdown request")));
                               2226                 :                : 
                               2227                 :                :             /* Report status */
 3347                          2228                 :            358 :             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) */
 2072                          2235                 :            358 :             SetQuitSignalReason(PMQUIT_FOR_STOP);
 4808 alvherre@alvh.no-ip.     2236                 :            358 :             TerminateChildren(SIGQUIT);
  594 andres@anarazel.de       2237                 :            358 :             UpdatePMState(PM_WAIT_BACKENDS);
                               2238                 :                : 
                               2239                 :                :             /* set stopwatch for them to die */
 4808 alvherre@alvh.no-ip.     2240                 :            358 :             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                 :            358 :             PostmasterStateMachine();
 9822 vadim4o@yahoo.com        2247                 :            358 :             break;
                               2248                 :                :     }
 1323 tmunro@postgresql.or     2249                 :            980 : }
                               2250                 :                : 
                               2251                 :                : static void
                               2252                 :          24387 : handle_pm_child_exit_signal(SIGNAL_ARGS)
                               2253                 :                : {
                               2254                 :          24387 :     pending_pm_child_exit = true;
                               2255                 :          24387 :     SetLatch(MyLatch);
11006 scrappy@hub.org          2256                 :          24387 : }
                               2257                 :                : 
                               2258                 :                : /*
                               2259                 :                :  * Cleanup after a child process dies.
                               2260                 :                :  */
                               2261                 :                : static void
 1323 tmunro@postgresql.or     2262                 :          24328 : process_pm_child_exit(void)
                               2263                 :                : {
                               2264                 :                :     int         pid;            /* process id of dead child process */
                               2265                 :                :     int         exitstatus;     /* its exit status */
                               2266                 :                : 
                               2267                 :          24328 :     pending_pm_child_exit = false;
                               2268                 :                : 
 8416 tgl@sss.pgh.pa.us        2269         [ -  + ]:          24328 :     ereport(DEBUG4,
                               2270                 :                :             (errmsg_internal("reaping dead processes")));
                               2271                 :                : 
 5166                          2272         [ +  + ]:          50627 :     while ((pid = waitpid(-1, &exitstatus, WNOHANG)) > 0)
                               2273                 :                :     {
                               2274                 :                :         PMChild    *pmchild;
                               2275                 :                : 
                               2276                 :                :         /*
                               2277                 :                :          * Check if this child was a startup process.
                               2278                 :                :          */
  651 heikki.linnakangas@i     2279   [ +  +  +  + ]:          26299 :         if (StartupPMChild && pid == StartupPMChild->pid)
                               2280                 :                :         {
                               2281                 :            996 :             ReleasePostmasterChildSlot(StartupPMChild);
                               2282                 :            996 :             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                 :                :              */
 5027 tgl@sss.pgh.pa.us        2288         [ +  + ]:            996 :             if (Shutdown > NoShutdown &&
                               2289   [ +  +  +  -  :            122 :                 (EXIT_STATUS_0(exitstatus) || EXIT_STATUS_1(exitstatus)))
                                              +  + ]
                               2290                 :                :             {
 4067                          2291                 :             70 :                 StartupStatus = STARTUP_NOT_RUNNING;
  594 andres@anarazel.de       2292                 :             70 :                 UpdatePMState(PM_WAIT_BACKENDS);
                               2293                 :                :                 /* PostmasterStateMachine logic does the rest */
 4293 simon@2ndQuadrant.co     2294                 :             70 :                 continue;
                               2295                 :                :             }
                               2296                 :                : 
                               2297   [ +  -  -  + ]:            926 :             if (EXIT_STATUS_3(exitstatus))
                               2298                 :                :             {
 4293 simon@2ndQuadrant.co     2299         [ #  # ]:UBC           0 :                 ereport(LOG,
                               2300                 :                :                         (errmsg("shutdown at recovery target")));
 4067 tgl@sss.pgh.pa.us        2301                 :              0 :                 StartupStatus = STARTUP_NOT_RUNNING;
 2204                          2302                 :              0 :                 Shutdown = Max(Shutdown, SmartShutdown);
 4293 simon@2ndQuadrant.co     2303                 :              0 :                 TerminateChildren(SIGTERM);
  594 andres@anarazel.de       2304                 :              0 :                 UpdatePMState(PM_WAIT_BACKENDS);
                               2305                 :                :                 /* PostmasterStateMachine logic does the rest */
 5027 tgl@sss.pgh.pa.us        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                 :                :              */
 6399 heikki.linnakangas@i     2327         [ +  + ]:CBC         926 :             if (!EXIT_STATUS_0(exitstatus))
                               2328                 :                :             {
 4067 tgl@sss.pgh.pa.us        2329         [ +  + ]:             63 :                 if (StartupStatus == STARTUP_SIGNALED)
                               2330                 :                :                 {
                               2331                 :             52 :                     StartupStatus = STARTUP_NOT_RUNNING;
 2558                          2332         [ -  + ]:             52 :                     if (pmState == PM_STARTUP)
  594 andres@anarazel.de       2333                 :UBC           0 :                         UpdatePMState(PM_WAIT_BACKENDS);
                               2334                 :                :                 }
                               2335                 :                :                 else
 4067 tgl@sss.pgh.pa.us        2336                 :CBC          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                 :                :                  */
    7 michael@paquier.xyz      2345   [ +  +  -  + ]:             63 :                 if (StartupStatus == STARTUP_CRASHED &&
    7 michael@paquier.xyz      2346         [ #  # ]:UBC           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
    7 michael@paquier.xyz      2354                 :CBC          63 :                     HandleChildCrash(pid, exitstatus,
                               2355                 :             63 :                                      _("startup process"));
 6958 tgl@sss.pgh.pa.us        2356                 :             63 :                 continue;
                               2357                 :                :             }
                               2358                 :                : 
                               2359                 :                :             /*
                               2360                 :                :              * Startup succeeded, commence normal operations
                               2361                 :                :              */
 4067                          2362                 :            863 :             StartupStatus = STARTUP_NOT_RUNNING;
 6394 heikki.linnakangas@i     2363                 :            863 :             FatalError = false;
 2558 tgl@sss.pgh.pa.us        2364                 :            863 :             AbortStartTime = 0;
 5937 rhaas@postgresql.org     2365                 :            863 :             ReachedNormalRunning = true;
  594 andres@anarazel.de       2366                 :            863 :             UpdatePMState(PM_RUN);
 1604 sfrost@snowman.net       2367                 :            863 :             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                 :                :              */
  745 heikki.linnakangas@i     2374                 :            863 :             StartWorkerNeeded = true;
                               2375                 :                : 
                               2376                 :                :             /* at this point we are really open for business */
 6394                          2377         [ +  - ]:            863 :             ereport(LOG,
                               2378                 :                :                     (errmsg("database system is ready to accept connections")));
                               2379                 :                : 
                               2380                 :                :             /* Report status */
 3347 tgl@sss.pgh.pa.us        2381                 :            863 :             AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
                               2382                 :                : #ifdef USE_SYSTEMD
                               2383                 :                :             sd_notify(0, "READY=1");
                               2384                 :                : #endif
                               2385                 :                : 
 6392 heikki.linnakangas@i     2386                 :            863 :             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                 :                :          */
  651                          2394   [ +  +  +  + ]:          25303 :         if (BgWriterPMChild && pid == BgWriterPMChild->pid)
                               2395                 :                :         {
                               2396                 :            996 :             ReleasePostmasterChildSlot(BgWriterPMChild);
                               2397                 :            996 :             BgWriterPMChild = NULL;
 5413 simon@2ndQuadrant.co     2398         [ +  + ]:            996 :             if (!EXIT_STATUS_0(exitstatus))
                               2399                 :            374 :                 HandleChildCrash(pid, exitstatus,
                               2400                 :            374 :                                  _("background writer process"));
                               2401                 :            996 :             continue;
                               2402                 :                :         }
                               2403                 :                : 
                               2404                 :                :         /*
                               2405                 :                :          * Was it the checkpointer?
                               2406                 :                :          */
  651 heikki.linnakangas@i     2407   [ +  +  +  + ]:          24307 :         if (CheckpointerPMChild && pid == CheckpointerPMChild->pid)
                               2408                 :                :         {
                               2409                 :            996 :             ReleasePostmasterChildSlot(CheckpointerPMChild);
                               2410                 :            996 :             CheckpointerPMChild = NULL;
  579 andres@anarazel.de       2411   [ +  +  +  - ]:            996 :             if (EXIT_STATUS_0(exitstatus) && pmState == PM_WAIT_CHECKPOINTER)
 9822 vadim4o@yahoo.com        2412                 :            622 :             {
                               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                 :                :                  */
  579 andres@anarazel.de       2422                 :            622 :                 UpdatePMState(PM_WAIT_DEAD_END);
                               2423                 :            622 :                 ConfigurePostmasterWaitSet(false);
                               2424                 :            622 :                 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                 :                :                  */
 6958 tgl@sss.pgh.pa.us        2432                 :            374 :                 HandleChildCrash(pid, exitstatus,
 5413 simon@2ndQuadrant.co     2433                 :            374 :                                  _("checkpointer process"));
                               2434                 :                :             }
                               2435                 :                : 
 8125 tgl@sss.pgh.pa.us        2436                 :            996 :             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                 :                :          */
  651 heikki.linnakangas@i     2444   [ +  +  +  + ]:          23311 :         if (WalWriterPMChild && pid == WalWriterPMChild->pid)
                               2445                 :                :         {
                               2446                 :            863 :             ReleasePostmasterChildSlot(WalWriterPMChild);
                               2447                 :            863 :             WalWriterPMChild = NULL;
 6974 tgl@sss.pgh.pa.us        2448         [ +  + ]:            863 :             if (!EXIT_STATUS_0(exitstatus))
                               2449                 :            311 :                 HandleChildCrash(pid, exitstatus,
 6867 peter_e@gmx.net          2450                 :            311 :                                  _("WAL writer process"));
 6974 tgl@sss.pgh.pa.us        2451                 :            863 :             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                 :                :          */
  651 heikki.linnakangas@i     2460   [ +  +  +  + ]:          22448 :         if (WalReceiverPMChild && pid == WalReceiverPMChild->pid)
                               2461                 :                :         {
                               2462                 :            291 :             ReleasePostmasterChildSlot(WalReceiverPMChild);
                               2463                 :            291 :             WalReceiverPMChild = NULL;
 6068                          2464   [ +  -  +  -  :            291 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
                                              +  + ]
                               2465                 :             21 :                 HandleChildCrash(pid, exitstatus,
                               2466                 :             21 :                                  _("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                 :                :          */
  651                          2475   [ +  +  +  + ]:          22157 :         if (WalSummarizerPMChild && pid == WalSummarizerPMChild->pid)
                               2476                 :                :         {
                               2477                 :             24 :             ReleasePostmasterChildSlot(WalSummarizerPMChild);
                               2478                 :             24 :             WalSummarizerPMChild = NULL;
  981 rhaas@postgresql.org     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                 :                :          */
  651 heikki.linnakangas@i     2491   [ +  +  +  + ]:          22133 :         if (AutoVacLauncherPMChild && pid == AutoVacLauncherPMChild->pid)
                               2492                 :                :         {
                               2493                 :            714 :             ReleasePostmasterChildSlot(AutoVacLauncherPMChild);
                               2494                 :            714 :             AutoVacLauncherPMChild = NULL;
 7133 alvherre@alvh.no-ip.     2495         [ +  + ]:            714 :             if (!EXIT_STATUS_0(exitstatus))
 7714 tgl@sss.pgh.pa.us        2496                 :            260 :                 HandleChildCrash(pid, exitstatus,
 7133 alvherre@alvh.no-ip.     2497                 :            260 :                                  _("autovacuum launcher process"));
 7714 tgl@sss.pgh.pa.us        2498                 :            714 :             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                 :                :          */
  651 heikki.linnakangas@i     2507   [ +  +  +  + ]:          21419 :         if (PgArchPMChild && pid == PgArchPMChild->pid)
                               2508                 :                :         {
                               2509                 :             63 :             ReleasePostmasterChildSlot(PgArchPMChild);
                               2510                 :             63 :             PgArchPMChild = NULL;
 1991 fujii@postgresql.org     2511   [ +  +  +  -  :             63 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
                                              +  - ]
                               2512                 :             44 :                 HandleChildCrash(pid, exitstatus,
                               2513                 :             44 :                                  _("archiver process"));
 8074 tgl@sss.pgh.pa.us        2514                 :             63 :             continue;
                               2515                 :                :         }
                               2516                 :                : 
                               2517                 :                :         /* Was it the system logger?  If so, try to start a new one */
  651 heikki.linnakangas@i     2518   [ +  +  -  + ]:          21356 :         if (SysLoggerPMChild && pid == SysLoggerPMChild->pid)
                               2519                 :                :         {
  651 heikki.linnakangas@i     2520                 :UBC           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                 :                : 
 7219 tgl@sss.pgh.pa.us        2527         [ #  # ]:              0 :             if (!EXIT_STATUS_0(exitstatus))
 7856 bruce@momjian.us         2528                 :              0 :                 LogChildExit(LOG, _("system logger process"),
                               2529                 :                :                              pid, exitstatus);
 8057 tgl@sss.pgh.pa.us        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                 :                :          */
  651 heikki.linnakangas@i     2540   [ +  +  +  + ]:CBC       21356 :         if (SlotSyncWorkerPMChild && pid == SlotSyncWorkerPMChild->pid)
                               2541                 :                :         {
                               2542                 :              6 :             ReleasePostmasterChildSlot(SlotSyncWorkerPMChild);
                               2543                 :              6 :             SlotSyncWorkerPMChild = NULL;
  917 akapila@postgresql.o     2544   [ +  +  +  -  :              6 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
                                              -  + ]
  917 akapila@postgresql.o     2545                 :UBC           0 :                 HandleChildCrash(pid, exitstatus,
                               2546                 :              0 :                                  _("slot sync worker process"));
  917 akapila@postgresql.o     2547                 :CBC           6 :             continue;
                               2548                 :                :         }
                               2549                 :                : 
                               2550                 :                :         /* Was it an IO worker? */
  527 andres@anarazel.de       2551         [ +  + ]:          21350 :         if (maybe_reap_io_worker(pid))
                               2552                 :                :         {
                               2553   [ +  +  +  -  :           2039 :             if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
                                              +  + ]
                               2554                 :            751 :                 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                 :                :              */
  141 tmunro@postgresql.or     2565                 :           2039 :             maybe_start_io_workers();
                               2566                 :                : 
  527 andres@anarazel.de       2567                 :           2039 :             continue;
                               2568                 :                :         }
                               2569                 :                : 
                               2570                 :                :         /*
                               2571                 :                :          * Was it a backend or a background worker?
                               2572                 :                :          */
  651 heikki.linnakangas@i     2573                 :          19311 :         pmchild = FindPostmasterChildByPid(pid);
                               2574         [ +  - ]:          19311 :         if (pmchild)
                               2575                 :                :         {
                               2576                 :          19311 :             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                 :                :         {
  747 heikki.linnakangas@i     2585   [ #  #  #  #  :UBC           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                 :                :      */
 6958 tgl@sss.pgh.pa.us        2596                 :CBC       24328 :     PostmasterStateMachine();
11006 scrappy@hub.org          2597                 :          23337 : }
                               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
  651 heikki.linnakangas@i     2606                 :          19311 : CleanupBackend(PMChild *bp,
                               2607                 :                :                int exitstatus)  /* child's exit status. */
                               2608                 :                : {
                               2609                 :                :     char        namebuf[MAXPGPATH];
                               2610                 :                :     const char *procname;
  747                          2611                 :          19311 :     bool        crashed = false;
                               2612                 :          19311 :     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 */
  651                          2619         [ +  + ]:          19311 :     if (bp->bkend_type == B_BG_WORKER)
                               2620                 :                :     {
 3283 peter_e@gmx.net          2621                 :           3540 :         snprintf(namebuf, MAXPGPATH, _("background worker \"%s\""),
  747 heikki.linnakangas@i     2622                 :           3540 :                  bp->rw->rw_worker.bgw_type);
                               2623                 :           3540 :         procname = namebuf;
                               2624                 :                :     }
                               2625                 :                :     else
  651                          2626                 :          15771 :         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                 :                :      */
  747                          2634   [ +  +  +  +  :          19311 :     if (!EXIT_STATUS_0(exitstatus) && !EXIT_STATUS_1(exitstatus))
                                              +  + ]
                               2635                 :            714 :         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                 :                :      */
  651                          2660                 :          19311 :     bp_pid = bp->pid;
                               2661                 :          19311 :     bp_bgworker_notify = bp->bgworker_notify;
                               2662                 :          19311 :     bp_bkend_type = bp->bkend_type;
                               2663                 :          19311 :     rw = bp->rw;
                               2664         [ +  + ]:          19311 :     if (!ReleasePostmasterChildSlot(bp))
                               2665                 :                :     {
                               2666                 :                :         /*
                               2667                 :                :          * Uh-oh, the child failed to clean itself up.  Treat as a crash after
                               2668                 :                :          * all.
                               2669                 :                :          */
                               2670                 :            401 :         crashed = true;
                               2671                 :                :     }
                               2672                 :          19311 :     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                 :                :      */
  747                          2681         [ +  + ]:          19311 :     if (crashed)
                               2682                 :                :     {
  651                          2683                 :            714 :         HandleChildCrash(bp_pid, exitstatus, procname);
 8125 tgl@sss.pgh.pa.us        2684                 :            714 :         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                 :                :      */
  651 heikki.linnakangas@i     2694         [ +  + ]:          18597 :     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                 :                :      */
  224                          2702   [ +  +  +  + ]:          18597 :     if (bp_bkend_type == B_AUTOVAC_WORKER && AutoVacLauncherPMChild != NULL)
                               2703                 :            155 :         signal_child(AutoVacLauncherPMChild, SIGUSR2);
                               2704                 :                : 
                               2705                 :                :     /*
                               2706                 :                :      * If it was a background worker, also update its RegisteredBgWorker
                               2707                 :                :      * entry.
                               2708                 :                :      */
  651                          2709         [ +  + ]:          18597 :     if (bp_bkend_type == B_BG_WORKER)
                               2710                 :                :     {
  747                          2711         [ +  + ]:           3202 :         if (!EXIT_STATUS_0(exitstatus))
                               2712                 :                :         {
                               2713                 :                :             /* Record timestamp, so we know when to restart the worker. */
                               2714                 :            799 :             rw->rw_crashed_at = GetCurrentTimestamp();
                               2715                 :                :         }
                               2716                 :                :         else
                               2717                 :                :         {
                               2718                 :                :             /* Zero exit status means terminate */
                               2719                 :           2403 :             rw->rw_crashed_at = 0;
                               2720                 :           2403 :             rw->rw_terminate = true;
                               2721                 :                :         }
                               2722                 :                : 
                               2723                 :           3202 :         rw->rw_pid = 0;
                               2724                 :           3202 :         ReportBackgroundWorkerExit(rw); /* report child death */
                               2725                 :                : 
                               2726         [ +  - ]:           3202 :         if (!logged)
                               2727                 :                :         {
                               2728         [ +  + ]:           3202 :             LogChildExit(EXIT_STATUS_0(exitstatus) ? DEBUG1 : LOG,
                               2729                 :                :                          procname, bp_pid, exitstatus);
                               2730                 :           3202 :             logged = true;
                               2731                 :                :         }
                               2732                 :                : 
                               2733                 :                :         /* have it be restarted */
                               2734                 :           3202 :         HaveCrashedWorker = true;
                               2735                 :                :     }
                               2736                 :                : 
                               2737         [ +  + ]:          18597 :     if (!logged)
  651                          2738                 :          15395 :         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
  580 andres@anarazel.de       2749                 :             16 : HandleFatalError(QuitSignalReason reason, bool consider_sigabrt)
                               2750                 :                : {
                               2751                 :                :     int         sigtosend;
                               2752                 :                : 
                               2753         [ -  + ]:             16 :     Assert(Shutdown != ImmediateShutdown);
                               2754                 :                : 
                               2755                 :             16 :     SetQuitSignalReason(reason);
                               2756                 :                : 
                               2757   [ +  -  -  + ]:             16 :     if (consider_sigabrt && send_abort_for_crash)
  580 andres@anarazel.de       2758                 :UBC           0 :         sigtosend = SIGABRT;
                               2759                 :                :     else
  580 andres@anarazel.de       2760                 :CBC          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                 :                :     {
  580 andres@anarazel.de       2780                 :UBC           0 :         case PM_INIT:
                               2781                 :                :             /* shouldn't have any children */
                               2782                 :              0 :             Assert(false);
                               2783                 :                :             break;
                               2784                 :                : 
                               2785                 :                :             /* wait for children to die */
  128 michael@paquier.xyz      2786                 :CBC          16 :         case PM_STARTUP:
                               2787                 :                :         case PM_RECOVERY:
                               2788                 :                :         case PM_HOT_STANDBY:
                               2789                 :                :         case PM_RUN:
                               2790                 :                :         case PM_STOP_BACKENDS:
  580 andres@anarazel.de       2791                 :             16 :             UpdatePMState(PM_WAIT_BACKENDS);
                               2792                 :             16 :             break;
                               2793                 :                : 
  580 andres@anarazel.de       2794                 :UBC           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                 :                :      */
 4808 alvherre@alvh.no-ip.     2820         [ +  - ]:CBC          16 :     if (AbortStartTime == 0)
                               2821                 :             16 :         AbortStartTime = time(NULL);
11006 scrappy@hub.org          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
  580 andres@anarazel.de       2834                 :           2931 : 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   [ +  +  +  + ]:           2931 :     if (FatalError || Shutdown == ImmediateShutdown)
                               2844                 :           2915 :         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
 8942 tgl@sss.pgh.pa.us        2861                 :          18613 : 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];
 5424                          2868                 :          18613 :     const char *activity = NULL;
                               2869                 :                : 
                               2870         [ +  + ]:          18613 :     if (!EXIT_STATUS_0(exitstatus))
                               2871                 :           1219 :         activity = pgstat_get_crashed_backend_activity(pid,
                               2872                 :                :                                                        activity_buffer,
                               2873                 :                :                                                        sizeof(activity_buffer));
                               2874                 :                : 
 9060                          2875         [ +  + ]:          18613 :     if (WIFEXITED(exitstatus))
 8437                          2876   [ +  +  +  + ]:          18609 :         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));
 9060                          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
 3354                          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
 8437 tgl@sss.pgh.pa.us        2909   [ #  #  #  # ]:UBC           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));
 9060 tgl@sss.pgh.pa.us        2917                 :CBC       18613 : }
                               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
 6958                          2927                 :          27316 : PostmasterStateMachine(void)
                               2928                 :                : {
                               2929                 :                :     /* If we're doing a smart shutdown, try to advance that state. */
 2204                          2930   [ +  +  +  + ]:          27316 :     if (pmState == PM_RUN || pmState == PM_HOT_STANDBY)
                               2931                 :                :     {
 1604 sfrost@snowman.net       2932         [ +  + ]:          19436 :         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                 :                :              */
  651 heikki.linnakangas@i     2938         [ +  + ]:            107 :             if (CountChildren(btmask(B_BACKEND)) == 0)
  594 andres@anarazel.de       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                 :                :      */
  651 heikki.linnakangas@i     2953   [ +  +  +  + ]:          27316 :     if (pmState == PM_STOP_BACKENDS || pmState == PM_WAIT_BACKENDS)
                               2954                 :                :     {
                               2955                 :           5303 :         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                 :                :          */
  594 andres@anarazel.de       2962                 :           5303 :         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                 :           5303 :         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                 :           5303 :         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                 :                :          */
  651 heikki.linnakangas@i     2987   [ +  +  +  + ]:           5303 :         if (FatalError || Shutdown >= ImmediateShutdown)
  580 andres@anarazel.de       2988                 :           1940 :             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                 :                :         {
  651 heikki.linnakangas@i     3006                 :           5303 :             BackendTypeMask remainMask = BTYPE_MASK_NONE;
                               3007                 :                : 
  594 andres@anarazel.de       3008                 :           5303 :             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                 :                :              */
  580                          3016                 :           5303 :             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 */
  594                          3023                 :           5303 :             remainMask = btmask_add(remainMask,
                               3024                 :                :                                     B_INVALID,
                               3025                 :                :                                     B_STANDALONE_BACKEND);
                               3026                 :                : 
                               3027                 :                :             /* also add data checksums processes */
  146 dgustafsson@postgres     3028                 :           5303 :             remainMask = btmask_add(remainMask,
                               3029                 :                :                                     B_DATACHECKSUMSWORKER_LAUNCHER,
                               3030                 :                :                                     B_DATACHECKSUMSWORKER_WORKER);
                               3031                 :                : 
                               3032                 :                :             /* All types should be included in targetMask or remainMask */
  651 heikki.linnakangas@i     3033         [ -  + ]:           5303 :             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         [ +  + ]:           5303 :         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                 :            622 :             ForgetUnstartedBackgroundWorkers();
                               3046                 :                : 
                               3047                 :            622 :             SignalChildren(SIGTERM, targetMask);
                               3048                 :                : 
  594 andres@anarazel.de       3049                 :            622 :             UpdatePMState(PM_WAIT_BACKENDS);
                               3050                 :                :         }
                               3051                 :                : 
                               3052                 :                :         /* Are any of the target processes still running? */
  651 heikki.linnakangas@i     3053         [ +  + ]:           5303 :         if (CountChildren(targetMask) == 0)
                               3054                 :                :         {
 4808 alvherre@alvh.no-ip.     3055   [ +  +  +  + ]:            996 :             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                 :                :                  */
  594 andres@anarazel.de       3063                 :            374 :                 UpdatePMState(PM_WAIT_DEAD_END);
  651 heikki.linnakangas@i     3064                 :            374 :                 ConfigurePostmasterWaitSet(false);
                               3065                 :            374 :                 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                 :                :                  */
 6958 tgl@sss.pgh.pa.us        3080         [ -  + ]:            622 :                 Assert(Shutdown > NoShutdown);
                               3081                 :                :                 /* Start the checkpointer if not running */
  651 heikki.linnakangas@i     3082         [ -  + ]:            622 :                 if (CheckpointerPMChild == NULL)
  651 heikki.linnakangas@i     3083                 :UBC           0 :                     CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
                               3084                 :                :                 /* And tell it to write the shutdown checkpoint */
  651 heikki.linnakangas@i     3085         [ +  - ]:CBC         622 :                 if (CheckpointerPMChild != NULL)
                               3086                 :                :                 {
  579 andres@anarazel.de       3087                 :            622 :                     signal_child(CheckpointerPMChild, SIGINT);
  594                          3088                 :            622 :                     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                 :                :                      */
  580 andres@anarazel.de       3109                 :UBC           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                 :                : 
  594 andres@anarazel.de       3121         [ +  + ]:CBC       27316 :     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                 :                :          */
  527                          3129         [ +  + ]:            691 :         if (CountChildren(btmask_all_except(B_CHECKPOINTER, B_IO_WORKER,
                               3130                 :                :                                             B_LOGGER, B_DEAD_END_BACKEND)) == 0)
                               3131                 :                :         {
                               3132                 :            622 :             UpdatePMState(PM_WAIT_IO_WORKERS);
                               3133                 :            622 :             SignalChildren(SIGUSR2, btmask(B_IO_WORKER));
                               3134                 :                :         }
                               3135                 :                :     }
                               3136                 :                : 
                               3137         [ +  + ]:          27316 :     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         [ +  + ]:           1828 :         if (io_worker_count == 0)
                               3144                 :                :         {
  579                          3145                 :            622 :             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         [ +  - ]:            622 :             if (CheckpointerPMChild != NULL)
                               3154                 :            622 :                 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                 :                : 
 6958 tgl@sss.pgh.pa.us        3163         [ +  + ]:          27316 :     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                 :                :          */
  651 heikki.linnakangas@i     3178         [ +  + ]:           1024 :         if (CountChildren(btmask_all_except(B_LOGGER)) == 0)
                               3179                 :                :         {
                               3180                 :                :             /* These other guys should be dead already */
                               3181         [ -  + ]:            996 :             Assert(StartupPMChild == NULL);
                               3182         [ -  + ]:            996 :             Assert(WalReceiverPMChild == NULL);
                               3183         [ -  + ]:            996 :             Assert(WalSummarizerPMChild == NULL);
                               3184         [ -  + ]:            996 :             Assert(BgWriterPMChild == NULL);
                               3185         [ -  + ]:            996 :             Assert(CheckpointerPMChild == NULL);
                               3186         [ -  + ]:            996 :             Assert(WalWriterPMChild == NULL);
                               3187         [ -  + ]:            996 :             Assert(AutoVacLauncherPMChild == NULL);
                               3188         [ -  + ]:            996 :             Assert(SlotSyncWorkerPMChild == NULL);
                               3189                 :                :             /* syslogger is not considered here */
  594 andres@anarazel.de       3190                 :            996 :             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                 :                :      */
 6958 tgl@sss.pgh.pa.us        3206   [ +  +  +  + ]:          27316 :     if (Shutdown > NoShutdown && pmState == PM_NO_CHILDREN)
                               3207                 :                :     {
                               3208         [ -  + ]:            980 :         if (FatalError)
                               3209                 :                :         {
 6958 tgl@sss.pgh.pa.us        3210         [ #  # ]:UBC           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                 :                :              */
 6958 tgl@sss.pgh.pa.us        3220                 :CBC         980 :             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                 :                :      */
 1922                          3231         [ +  + ]:          26336 :     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                 :                :         {
 1922 tgl@sss.pgh.pa.us        3241         [ #  # ]:UBC           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                 :                :      */
 6958 tgl@sss.pgh.pa.us        3251   [ +  +  +  + ]:CBC       26325 :     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 */
 1988 tomas.vondra@postgre     3257         [ +  + ]:              5 :         if (remove_temp_files_after_crash)
                               3258                 :              4 :             RemovePgTempFiles();
                               3259                 :                : 
                               3260                 :                :         /* allow background workers to immediately restart */
 4495 rhaas@postgresql.org     3261                 :              5 :         ResetBackgroundWorkerCrashTimes();
                               3262                 :                : 
 6444 tgl@sss.pgh.pa.us        3263                 :              5 :         shmem_exit(1);
                               3264                 :                : 
                               3265                 :                :         /* re-read control file into local memory */
 3266 andres@anarazel.de       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                 :                :          */
  143 heikki.linnakangas@i     3274                 :              5 :         ResetShmemAllocator();
                               3275                 :              5 :         ShmemCallRequestCallbacks();
 1503 tgl@sss.pgh.pa.us        3276                 :              5 :         CreateSharedMemoryAndSemaphores();
                               3277                 :                : 
  527 andres@anarazel.de       3278                 :              5 :         UpdatePMState(PM_STARTUP);
                               3279                 :                : 
                               3280                 :                :         /* Make sure we can perform I/O while starting up. */
  141 tmunro@postgresql.or     3281                 :              5 :         maybe_start_io_workers();
                               3282                 :                : 
  651 heikki.linnakangas@i     3283                 :              5 :         StartupPMChild = StartChildProcess(B_STARTUP);
                               3284         [ -  + ]:              5 :         Assert(StartupPMChild != NULL);
 4067 tgl@sss.pgh.pa.us        3285                 :              5 :         StartupStatus = STARTUP_RUNNING;
                               3286                 :                :         /* crash recovery started, reset SIGKILL flag */
 4709 alvherre@alvh.no-ip.     3287                 :              5 :         AbortStartTime = 0;
                               3288                 :                : 
                               3289                 :                :         /* start accepting server socket connection events again */
 1323 tmunro@postgresql.or     3290                 :              5 :         ConfigurePostmasterWaitSet(true);
                               3291                 :                :     }
 6958 tgl@sss.pgh.pa.us        3292                 :          26325 : }
                               3293                 :                : 
                               3294                 :                : static const char *
  594 andres@anarazel.de       3295                 :           1308 : pmstate_name(PMState state)
                               3296                 :                : {
                               3297                 :                : #define PM_TOSTR_CASE(sym) case sym: return #sym
                               3298   [ +  +  +  +  :           1308 :     switch (state)
                                     +  +  +  +  +  
                                        +  +  +  +  
                                                 - ]
                               3299                 :                :     {
                               3300                 :             71 :             PM_TOSTR_CASE(PM_INIT);
                               3301                 :            142 :             PM_TOSTR_CASE(PM_STARTUP);
                               3302                 :             30 :             PM_TOSTR_CASE(PM_RECOVERY);
                               3303                 :             28 :             PM_TOSTR_CASE(PM_HOT_STANDBY);
                               3304                 :            127 :             PM_TOSTR_CASE(PM_RUN);
                               3305                 :            106 :             PM_TOSTR_CASE(PM_STOP_BACKENDS);
                               3306                 :            158 :             PM_TOSTR_CASE(PM_WAIT_BACKENDS);
                               3307                 :            106 :             PM_TOSTR_CASE(PM_WAIT_XLOG_SHUTDOWN);
                               3308                 :            106 :             PM_TOSTR_CASE(PM_WAIT_XLOG_ARCHIVAL);
  527                          3309                 :            106 :             PM_TOSTR_CASE(PM_WAIT_IO_WORKERS);
  594                          3310                 :            148 :             PM_TOSTR_CASE(PM_WAIT_DEAD_END);
  579                          3311                 :            106 :             PM_TOSTR_CASE(PM_WAIT_CHECKPOINTER);
  594                          3312                 :             74 :             PM_TOSTR_CASE(PM_NO_CHILDREN);
                               3313                 :                :     }
                               3314                 :                : #undef PM_TOSTR_CASE
                               3315                 :                : 
  594 andres@anarazel.de       3316                 :UBC           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
  594 andres@anarazel.de       3325                 :CBC        8489 : UpdatePMState(PMState newState)
                               3326                 :                : {
                               3327         [ +  + ]:           8489 :     elog(DEBUG1, "updating PMState from %s to %s",
                               3328                 :                :          pmstate_name(pmState), pmstate_name(newState));
                               3329                 :           8489 :     pmState = newState;
                               3330                 :           8489 : }
                               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
  745 heikki.linnakangas@i     3341                 :          44733 : LaunchMissingBackgroundProcesses(void)
                               3342                 :                : {
                               3343                 :                :     /* Syslogger is active in all states */
  651                          3344   [ +  +  -  + ]:          44733 :     if (SysLoggerPMChild == NULL && Logging_collector)
  651 heikki.linnakangas@i     3345                 :UBC           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                 :                :      */
  141 tmunro@postgresql.or     3355                 :CBC       44733 :     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                 :                :      */
  745 heikki.linnakangas@i     3366   [ +  +  +  + ]:          44733 :     if (pmState == PM_RUN || pmState == PM_RECOVERY ||
                               3367   [ +  +  +  + ]:           9858 :         pmState == PM_HOT_STANDBY || pmState == PM_STARTUP)
                               3368                 :                :     {
  651                          3369         [ +  + ]:          37817 :         if (CheckpointerPMChild == NULL)
                               3370                 :              5 :             CheckpointerPMChild = StartChildProcess(B_CHECKPOINTER);
                               3371         [ +  + ]:          37817 :         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   [ +  +  +  + ]:          44733 :     if (WalWriterPMChild == NULL && pmState == PM_RUN)
                               3380                 :            863 :         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   [ +  +  +  +  :          55761 :     if (!IsBinaryUpgrade && AutoVacLauncherPMChild == NULL &&
                                              +  + ]
  745                          3388         [ -  + ]:          15747 :         (AutoVacuumingActive() || start_autovac_launcher) &&
                               3389         [ +  + ]:           6309 :         pmState == PM_RUN)
                               3390                 :                :     {
  651                          3391                 :            714 :         AutoVacLauncherPMChild = StartChildProcess(B_AUTOVAC_LAUNCHER);
                               3392         [ +  - ]:            714 :         if (AutoVacLauncherPMChild != NULL)
  745                          3393                 :            714 :             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                 :                :      */
  651                          3400         [ +  + ]:          44733 :     if (PgArchPMChild == NULL &&
  745                          3401   [ +  +  -  +  :          43501 :         ((XLogArchivingActive() && pmState == PM_RUN) ||
                                        +  +  +  + ]
                               3402   [ +  +  -  +  :          43501 :          (XLogArchivingAlways() && (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) &&
                                     +  +  +  -  -  
                                           +  +  - ]
                               3403                 :             58 :         PgArchCanRestart())
  651                          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   [ +  +  +  + ]:          44733 :     if (SlotSyncWorkerPMChild == NULL && pmState == PM_HOT_STANDBY &&
  745                          3415   [ +  -  +  +  :           2668 :         Shutdown <= SmartShutdown && sync_replication_slots &&
                                              +  + ]
                               3416         [ +  + ]:             31 :         ValidateSlotSyncParams(LOG) && SlotSyncWorkerCanRestart())
  651                          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                 :                :      */
  745                          3431         [ +  + ]:          44733 :     if (WalReceiverRequested)
                               3432                 :                :     {
  651                          3433         [ +  + ]:            436 :         if (WalReceiverPMChild == NULL &&
  745                          3434   [ +  +  +  - ]:            315 :             (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
                               3435         [ +  + ]:            314 :              pmState == PM_HOT_STANDBY) &&
                               3436         [ +  - ]:            291 :             Shutdown <= SmartShutdown)
                               3437                 :                :         {
  651                          3438                 :            291 :             WalReceiverPMChild = StartChildProcess(B_WAL_RECEIVER);
  268 peter@eisentraut.org     3439         [ +  - ]:            291 :             if (WalReceiverPMChild != NULL)
  745 heikki.linnakangas@i     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 */
  651                          3446   [ +  +  +  + ]:          44733 :     if (summarize_wal && WalSummarizerPMChild == NULL &&
  745                          3447   [ +  +  +  + ]:            105 :         (pmState == PM_RUN || pmState == PM_HOT_STANDBY) &&
                               3448         [ +  - ]:             24 :         Shutdown <= SmartShutdown)
  651                          3449                 :             24 :         WalSummarizerPMChild = StartChildProcess(B_WAL_SUMMARIZER);
                               3450                 :                : 
                               3451                 :                :     /* Get other worker processes running, if needed */
  745                          3452   [ +  +  +  + ]:          44733 :     if (StartWorkerNeeded || HaveCrashedWorker)
                               3453                 :           8236 :         maybe_start_bgworkers();
                               3454                 :          44733 : }
                               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 *
  594 andres@anarazel.de       3464                 :             63 : pm_signame(int signal)
                               3465                 :                : {
                               3466                 :                : #define PM_TOSTR_CASE(sym) case sym: return #sym
                               3467   [ -  -  -  +  :             63 :     switch (signal)
                                     -  -  +  -  +  
                                                 - ]
                               3468                 :                :     {
  594 andres@anarazel.de       3469                 :UBC           0 :             PM_TOSTR_CASE(SIGABRT);
                               3470                 :              0 :             PM_TOSTR_CASE(SIGCHLD);
                               3471                 :              0 :             PM_TOSTR_CASE(SIGHUP);
  594 andres@anarazel.de       3472                 :CBC           7 :             PM_TOSTR_CASE(SIGINT);
  594 andres@anarazel.de       3473                 :UBC           0 :             PM_TOSTR_CASE(SIGKILL);
                               3474                 :              0 :             PM_TOSTR_CASE(SIGQUIT);
  594 andres@anarazel.de       3475                 :CBC          41 :             PM_TOSTR_CASE(SIGTERM);
  594 andres@anarazel.de       3476                 :UBC           0 :             PM_TOSTR_CASE(SIGUSR1);
  594 andres@anarazel.de       3477                 :CBC          15 :             PM_TOSTR_CASE(SIGUSR2);
  594 andres@anarazel.de       3478                 :UBC           0 :         default:
                               3479                 :                :             /* all signals sent by postmaster should be listed here */
                               3480                 :              0 :             Assert(false);
                               3481                 :                :             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
  651 heikki.linnakangas@i     3505                 :CBC       10209 : signal_child(PMChild *pmchild, int signal)
                               3506                 :                : {
                               3507                 :          10209 :     pid_t       pid = pmchild->pid;
                               3508                 :                : 
  594 andres@anarazel.de       3509         [ +  + ]:          10209 :     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                 :                : 
 7219 tgl@sss.pgh.pa.us        3515         [ -  + ]:          10209 :     if (kill(pid, signal) < 0)
 7219 tgl@sss.pgh.pa.us        3516         [ #  # ]:UBC           0 :         elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) pid, signal);
                               3517                 :                : #ifdef HAVE_SETSID
 7219 tgl@sss.pgh.pa.us        3518         [ +  + ]:CBC       10209 :     switch (signal)
                               3519                 :                :     {
                               3520                 :           6517 :         case SIGINT:
                               3521                 :                :         case SIGTERM:
                               3522                 :                :         case SIGQUIT:
                               3523                 :                :         case SIGKILL:
                               3524                 :                :         case SIGABRT:
                               3525         [ +  + ]:           6517 :             if (kill(-pid, signal) < 0)
                               3526         [ -  + ]:             10 :                 elog(DEBUG3, "kill(%ld,%d) failed: %m", (long) (-pid), signal);
                               3527                 :           6517 :             break;
                               3528                 :           3692 :         default:
                               3529                 :           3692 :             break;
                               3530                 :                :     }
                               3531                 :                : #endif
                               3532                 :          10209 : }
                               3533                 :                : 
                               3534                 :                : /*
                               3535                 :                :  * Send a signal to the targeted children.
                               3536                 :                :  */
                               3537                 :                : static bool
  651 heikki.linnakangas@i     3538                 :           3408 : SignalChildren(int signal, BackendTypeMask targetMask)
                               3539                 :                : {
                               3540                 :                :     dlist_iter  iter;
 6068                          3541                 :           3408 :     bool        signaled = false;
                               3542                 :                : 
  651                          3543   [ +  -  +  + ]:          16692 :     dlist_foreach(iter, &ActiveChildList)
                               3544                 :                :     {
                               3545                 :          13284 :         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         [ +  + ]:          13284 :         if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
                               3553         [ +  + ]:           6885 :             bp->bkend_type == B_BACKEND)
                               3554                 :                :         {
                               3555         [ +  + ]:            673 :             if (IsPostmasterChildWalSender(bp->child_slot))
                               3556                 :             51 :                 bp->bkend_type = B_WAL_SENDER;
                               3557                 :                :         }
                               3558                 :                : 
                               3559         [ +  + ]:          13284 :         if (!btmask_contains(targetMask, bp->bkend_type))
                               3560                 :           4549 :             continue;
                               3561                 :                : 
                               3562                 :           8735 :         signal_child(bp, signal);
 6068                          3563                 :           8735 :         signaled = true;
                               3564                 :                :     }
                               3565                 :           3408 :     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
 4808 alvherre@alvh.no-ip.     3573                 :            374 : TerminateChildren(int signal)
                               3574                 :                : {
  651 heikki.linnakangas@i     3575                 :            374 :     SignalChildren(signal, btmask_all_except(B_LOGGER));
                               3576         [ +  + ]:            374 :     if (StartupPMChild != NULL)
                               3577                 :                :     {
 1375 tgl@sss.pgh.pa.us        3578   [ -  +  -  -  :             52 :         if (signal == SIGQUIT || signal == SIGKILL || signal == SIGABRT)
                                              -  - ]
 4067                          3579                 :             52 :             StartupStatus = STARTUP_SIGNALED;
                               3580                 :                :     }
 4808 alvherre@alvh.no-ip.     3581                 :            374 : }
                               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
  898 heikki.linnakangas@i     3592                 :          15615 : BackendStartup(ClientSocket *client_sock)
                               3593                 :                : {
  651                          3594                 :          15615 :     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                 :                :      */
  533 melanieplageman@gmai     3603                 :          15615 :     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                 :                :      */
  651 heikki.linnakangas@i     3610                 :          15615 :     cac = canAcceptConnections(B_BACKEND);
                               3611         [ +  + ]:          15615 :     if (cac == CAC_OK)
                               3612                 :                :     {
                               3613                 :                :         /* Can change later to B_WAL_SENDER */
                               3614                 :          15355 :         bn = AssignPostmasterChildSlot(B_BACKEND);
                               3615         [ +  + ]:          15355 :         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                 :                :     }
 9076 tgl@sss.pgh.pa.us        3624         [ +  + ]:          15615 :     if (!bn)
                               3625                 :                :     {
  651 heikki.linnakangas@i     3626                 :            288 :         bn = AllocDeadEndChild();
                               3627         [ -  + ]:            288 :         if (!bn)
                               3628                 :                :         {
  651 heikki.linnakangas@i     3629         [ #  # ]:UBC           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 */
  651 heikki.linnakangas@i     3637                 :CBC       15615 :     startup_data.canAcceptConnections = cac;
  747                          3638                 :          15615 :     bn->rw = NULL;
                               3639                 :                : 
                               3640                 :                :     /* Hasn't asked to be notified about any bgworkers yet */
 4747 rhaas@postgresql.org     3641                 :          15615 :     bn->bgworker_notify = false;
                               3642                 :                : 
  651 heikki.linnakangas@i     3643                 :          15615 :     pid = postmaster_child_launch(bn->bkend_type, bn->child_slot,
                               3644                 :                :                                   &startup_data, sizeof(startup_data),
                               3645                 :                :                                   client_sock);
10581 bruce@momjian.us         3646         [ -  + ]:          15615 :     if (pid < 0)
                               3647                 :                :     {
                               3648                 :                :         /* in parent, fork failed */
 8999 tgl@sss.pgh.pa.us        3649                 :UBC           0 :         int         save_errno = errno;
                               3650                 :                : 
  651 heikki.linnakangas@i     3651                 :              0 :         (void) ReleasePostmasterChildSlot(bn);
 8437 tgl@sss.pgh.pa.us        3652                 :              0 :         errno = save_errno;
                               3653         [ #  # ]:              0 :         ereport(LOG,
                               3654                 :                :                 (errmsg("could not fork new process for connection: %m")));
  898 heikki.linnakangas@i     3655                 :              0 :         report_fork_failure_to_client(client_sock, save_errno);
10222 bruce@momjian.us         3656                 :              0 :         return STATUS_ERROR;
                               3657                 :                :     }
                               3658                 :                : 
                               3659                 :                :     /* in parent, successful fork */
 8416 tgl@sss.pgh.pa.us        3660         [ +  + ]:CBC       15615 :     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                 :                :      */
10581 bruce@momjian.us         3669                 :          15615 :     bn->pid = pid;
10222                          3670                 :          15615 :     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
  898 heikki.linnakangas@i     3682                 :UBC           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) */
 8999 tgl@sss.pgh.pa.us        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 */
  898 heikki.linnakangas@i     3693         [ #  # ]:              0 :     if (!pg_set_noblock(client_sock->sock))
 8999 tgl@sss.pgh.pa.us        3694                 :              0 :         return;
                               3695                 :                : 
                               3696                 :                :     /* We'll retry after EINTR, but ignore all other failures */
                               3697                 :                :     do
                               3698                 :                :     {
  898 heikki.linnakangas@i     3699                 :              0 :         rc = send(client_sock->sock, buffer, strlen(buffer) + 1, 0);
 7347 tgl@sss.pgh.pa.us        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
11006 scrappy@hub.org          3709                 :CBC         993 : 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                 :                : 
10288 bruce@momjian.us         3736                 :            993 :     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
 1323 tmunro@postgresql.or     3744                 :           4684 : process_pm_pmsignal(void)
                               3745                 :                : {
  579 andres@anarazel.de       3746                 :           4684 :     bool        request_state_update = false;
                               3747                 :                : 
 1323 tmunro@postgresql.or     3748                 :           4684 :     pending_pm_pmsignal = false;
                               3749                 :                : 
                               3750         [ +  + ]:           4684 :     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                 :                :      */
 6394 heikki.linnakangas@i     3759         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_STARTED) &&
 5027 tgl@sss.pgh.pa.us        3760   [ +  -  +  - ]:            282 :         pmState == PM_STARTUP && Shutdown == NoShutdown)
                               3761                 :                :     {
                               3762                 :                :         /* WAL redo has started. We're out of reinitialization. */
 6394 heikki.linnakangas@i     3763                 :            282 :         FatalError = false;
 2558 tgl@sss.pgh.pa.us        3764                 :            282 :         AbortStartTime = 0;
  512 fujii@postgresql.org     3765                 :            282 :         reachedConsistency = false;
                               3766                 :                : 
                               3767                 :                :         /*
                               3768                 :                :          * Start the archiver if we're responsible for (re-)archiving received
                               3769                 :                :          * files.
                               3770                 :                :          */
  651 heikki.linnakangas@i     3771         [ -  + ]:            282 :         Assert(PgArchPMChild == NULL);
 4094 fujii@postgresql.org     3772   [ +  +  -  +  :            282 :         if (XLogArchivingAlways())
                                              +  + ]
  651 heikki.linnakangas@i     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                 :                :          */
 3936 peter_e@gmx.net          3780         [ +  + ]:            282 :         if (!EnableHotStandby)
                               3781                 :                :         {
 3347 tgl@sss.pgh.pa.us        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                 :                : 
  594 andres@anarazel.de       3788                 :            282 :         UpdatePMState(PM_RECOVERY);
                               3789                 :                :     }
                               3790                 :                : 
  512 fujii@postgresql.org     3791         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT) &&
 5027 tgl@sss.pgh.pa.us        3792   [ +  -  +  - ]:            190 :         pmState == PM_RECOVERY && Shutdown == NoShutdown)
                               3793                 :                :     {
  512 fujii@postgresql.org     3794                 :            190 :         reachedConsistency = true;
                               3795                 :                :     }
                               3796                 :                : 
                               3797         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY) &&
                               3798   [ +  -  +  - ]:            180 :         (pmState == PM_RECOVERY && Shutdown == NoShutdown))
                               3799                 :                :     {
 6095 simon@2ndQuadrant.co     3800         [ +  - ]:            180 :         ereport(LOG,
                               3801                 :                :                 (errmsg("database system is ready to accept read-only connections")));
                               3802                 :                : 
                               3803                 :                :         /* Report status */
 3347 tgl@sss.pgh.pa.us        3804                 :            180 :         AddToDataDirLockFile(LOCK_FILE_LINE_PM_STATUS, PM_STATUS_READY);
                               3805                 :                : #ifdef USE_SYSTEMD
                               3806                 :                :         sd_notify(0, "READY=1");
                               3807                 :                : #endif
                               3808                 :                : 
  594 andres@anarazel.de       3809                 :            180 :         UpdatePMState(PM_HOT_STANDBY);
 1604 sfrost@snowman.net       3810                 :            180 :         connsAllowed = true;
                               3811                 :                : 
                               3812                 :                :         /* Some workers may be scheduled to start now */
 4345 rhaas@postgresql.org     3813                 :            180 :         StartWorkerNeeded = true;
                               3814                 :                :     }
                               3815                 :                : 
                               3816                 :                :     /* Process IO worker start requests. */
  141 tmunro@postgresql.or     3817                 :           4684 :     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. */
 2072 tgl@sss.pgh.pa.us        3827         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_BACKGROUND_WORKER_CHANGE))
                               3828                 :                :     {
                               3829                 :                :         /* Accept new worker requests only if not stopping. */
                               3830                 :           1849 :         BackgroundWorkerStateChange(pmState < PM_STOP_BACKENDS);
                               3831                 :           1849 :         StartWorkerNeeded = true;
                               3832                 :                :     }
                               3833                 :                : 
                               3834                 :                :     /* Tell syslogger to rotate logfile if requested */
  651 heikki.linnakangas@i     3835         [ +  + ]:           4684 :     if (SysLoggerPMChild != NULL)
                               3836                 :                :     {
 2917 akorotkov@postgresql     3837         [ +  + ]:              2 :         if (CheckLogrotateSignal())
                               3838                 :                :         {
  651 heikki.linnakangas@i     3839                 :              1 :             signal_child(SysLoggerPMChild, SIGUSR1);
 2917 akorotkov@postgresql     3840                 :              1 :             RemoveLogrotateSignalFiles();
                               3841                 :                :         }
                               3842         [ -  + ]:              1 :         else if (CheckPostmasterSignal(PMSIGNAL_ROTATE_LOGFILE))
                               3843                 :                :         {
  651 heikki.linnakangas@i     3844                 :UBC           0 :             signal_child(SysLoggerPMChild, SIGUSR1);
                               3845                 :                :         }
                               3846                 :                :     }
                               3847                 :                : 
 5027 tgl@sss.pgh.pa.us        3848         [ -  + ]:CBC        4684 :     if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_LAUNCHER) &&
 2204 tgl@sss.pgh.pa.us        3849   [ #  #  #  # ]:UBC           0 :         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                 :                :          */
 7133 alvherre@alvh.no-ip.     3860                 :              0 :         start_autovac_launcher = true;
                               3861                 :                :     }
                               3862                 :                : 
 5027 tgl@sss.pgh.pa.us        3863         [ +  + ]:CBC        4684 :     if (CheckPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER) &&
 2204                          3864   [ +  -  +  - ]:            156 :         Shutdown <= SmartShutdown && pmState < PM_STOP_BACKENDS)
                               3865                 :                :     {
                               3866                 :                :         /* The autovacuum launcher wants us to start a worker process. */
 7133 alvherre@alvh.no-ip.     3867                 :            156 :         StartAutovacuumWorker();
                               3868                 :                :     }
                               3869                 :                : 
 3349 tgl@sss.pgh.pa.us        3870         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_START_WALRECEIVER))
                               3871                 :                :     {
                               3872                 :                :         /* Startup Process wants us to start the walreceiver process. */
                               3873                 :            295 :         WalReceiverRequested = true;
                               3874                 :                :     }
                               3875                 :                : 
  579 andres@anarazel.de       3876         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_XLOG_IS_SHUTDOWN))
                               3877                 :                :     {
                               3878                 :                :         /* Checkpointer completed the shutdown checkpoint */
                               3879         [ +  - ]:            622 :         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         [ -  + ]:            622 :             Assert(Shutdown > NoShutdown);
                               3887                 :                : 
                               3888                 :                :             /* Waken archiver for the last time */
                               3889         [ +  + ]:            622 :             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                 :            622 :             SignalChildren(SIGUSR2, btmask(B_WAL_SENDER));
                               3897                 :                : 
                               3898                 :            622 :             UpdatePMState(PM_WAIT_XLOG_ARCHIVAL);
                               3899                 :                :         }
  579 andres@anarazel.de       3900   [ #  #  #  # ]:UBC           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                 :                :          */
  579 andres@anarazel.de       3925                 :CBC         622 :         request_state_update = true;
                               3926                 :                :     }
                               3927                 :                : 
                               3928                 :                :     /*
                               3929                 :                :      * Try to advance postmaster's state machine, if a child requests it.
                               3930                 :                :      */
                               3931         [ +  + ]:           4684 :     if (CheckPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE))
                               3932                 :                :     {
                               3933                 :           1386 :         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         [ +  + ]:           4684 :     if (request_state_update)
                               3945                 :                :     {
 5625 rhaas@postgresql.org     3946                 :           2008 :         PostmasterStateMachine();
                               3947                 :                :     }
                               3948                 :                : 
  651 heikki.linnakangas@i     3949         [ +  + ]:           4684 :     if (StartupPMChild != NULL &&
 5672 rhaas@postgresql.org     3950   [ +  +  +  + ]:            719 :         (pmState == PM_STARTUP || pmState == PM_RECOVERY ||
 2204 tgl@sss.pgh.pa.us        3951   [ +  +  +  + ]:           1227 :          pmState == PM_HOT_STANDBY) &&
 2682                          3952                 :            717 :         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                 :                :          */
  651 heikki.linnakangas@i     3960                 :             55 :         signal_child(StartupPMChild, SIGUSR2);
                               3961                 :                :     }
 9298 tgl@sss.pgh.pa.us        3962                 :           4684 : }
                               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
 9062 tgl@sss.pgh.pa.us        3974                 :UBC           0 : dummy_handler(SIGNAL_ARGS)
                               3975                 :                : {
                               3976                 :              0 : }
                               3977                 :                : 
                               3978                 :                : /*
                               3979                 :                :  * Count up number of child processes of specified types.
                               3980                 :                :  */
                               3981                 :                : static int
  651 heikki.linnakangas@i     3982                 :CBC        7125 : CountChildren(BackendTypeMask targetMask)
                               3983                 :                : {
                               3984                 :                :     dlist_iter  iter;
10071 tgl@sss.pgh.pa.us        3985                 :           7125 :     int         cnt = 0;
                               3986                 :                : 
  651 heikki.linnakangas@i     3987   [ +  -  +  + ]:          36691 :     dlist_foreach(iter, &ActiveChildList)
                               3988                 :                :     {
                               3989                 :          29566 :         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         [ +  + ]:          29566 :         if (btmask_contains(targetMask, B_WAL_SENDER) != btmask_contains(targetMask, B_BACKEND) &&
                               3997         [ +  + ]:          19955 :             bp->bkend_type == B_BACKEND)
                               3998                 :                :         {
                               3999         [ -  + ]:           1099 :             if (IsPostmasterChildWalSender(bp->child_slot))
  651 heikki.linnakangas@i     4000                 :UBC           0 :                 bp->bkend_type = B_WAL_SENDER;
                               4001                 :                :         }
                               4002                 :                : 
  651 heikki.linnakangas@i     4003         [ +  + ]:CBC       29566 :         if (!btmask_contains(targetMask, bp->bkend_type))
                               4004                 :          13473 :             continue;
                               4005                 :                : 
                               4006         [ -  + ]:          16093 :         ereport(DEBUG4,
                               4007                 :                :                 (errmsg_internal("%s process %d is still running",
                               4008                 :                :                                  GetBackendTypeDesc(bp->bkend_type), (int) bp->pid)));
                               4009                 :                : 
 6068                          4010                 :          16093 :         cnt++;
                               4011                 :                :     }
10071 tgl@sss.pgh.pa.us        4012                 :           7125 :     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 *
  906 heikki.linnakangas@i     4026                 :           7144 : StartChildProcess(BackendType type)
                               4027                 :                : {
                               4028                 :                :     PMChild    *pmchild;
                               4029                 :                :     pid_t       pid;
                               4030                 :                : 
  651                          4031                 :           7144 :     pmchild = AssignPostmasterChildSlot(type);
                               4032         [ -  + ]:           7144 :     if (!pmchild)
                               4033                 :                :     {
  651 heikki.linnakangas@i     4034         [ #  # ]:UBC           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                 :                : 
  651 heikki.linnakangas@i     4046                 :CBC        7144 :     pid = postmaster_child_launch(type, pmchild->child_slot, NULL, 0, NULL);
 9822 vadim4o@yahoo.com        4047         [ -  + ]:           7144 :     if (pid < 0)
                               4048                 :                :     {
                               4049                 :                :         /* in parent, fork failed */
  651 heikki.linnakangas@i     4050                 :UBC           0 :         ReleasePostmasterChildSlot(pmchild);
  892                          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                 :                :          */
  906                          4058         [ #  # ]:              0 :         if (type == B_STARTUP)
 8125 tgl@sss.pgh.pa.us        4059                 :              0 :             ExitPostmaster(1);
  651 heikki.linnakangas@i     4060                 :              0 :         return NULL;
                               4061                 :                :     }
                               4062                 :                : 
                               4063                 :                :     /* in parent, successful fork */
  651 heikki.linnakangas@i     4064                 :CBC        7144 :     pmchild->pid = pid;
                               4065                 :           7144 :     return pmchild;
                               4066                 :                : }
                               4067                 :                : 
                               4068                 :                : /*
                               4069                 :                :  * StartSysLogger -- start the syslogger process
                               4070                 :                :  */
                               4071                 :                : void
                               4072                 :              1 : StartSysLogger(void)
                               4073                 :                : {
                               4074         [ -  + ]:              1 :     Assert(SysLoggerPMChild == NULL);
                               4075                 :                : 
                               4076                 :              1 :     SysLoggerPMChild = AssignPostmasterChildSlot(B_LOGGER);
                               4077         [ -  + ]:              1 :     if (!SysLoggerPMChild)
  651 heikki.linnakangas@i     4078         [ #  # ]:UBC           0 :         elog(PANIC, "no postmaster child slot available for syslogger");
  651 heikki.linnakangas@i     4079                 :CBC           1 :     SysLoggerPMChild->pid = SysLogger_Start(SysLoggerPMChild->child_slot);
                               4080         [ -  + ]:              1 :     if (SysLoggerPMChild->pid == 0)
                               4081                 :                :     {
  651 heikki.linnakangas@i     4082                 :UBC           0 :         ReleasePostmasterChildSlot(SysLoggerPMChild);
                               4083                 :              0 :         SysLoggerPMChild = NULL;
                               4084                 :                :     }
 9822 vadim4o@yahoo.com        4085                 :CBC           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
 7133 alvherre@alvh.no-ip.     4097                 :            156 : 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                 :                :      */
  651 heikki.linnakangas@i     4108         [ +  - ]:            156 :     if (canAcceptConnections(B_AUTOVAC_WORKER) == CAC_OK)
                               4109                 :                :     {
                               4110                 :            156 :         bn = StartChildProcess(B_AUTOVAC_WORKER);
 6958 tgl@sss.pgh.pa.us        4111         [ +  - ]:            156 :         if (bn)
                               4112                 :                :         {
 3600 heikki.linnakangas@i     4113                 :            156 :             bn->bgworker_notify = false;
  747                          4114                 :            156 :             bn->rw = NULL;
  651                          4115                 :            156 :             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                 :                :      */
  651 heikki.linnakangas@i     4135         [ #  # ]:UBC           0 :     if (AutoVacLauncherPMChild != NULL)
                               4136                 :                :     {
 6958 tgl@sss.pgh.pa.us        4137                 :              0 :         AutoVacWorkerFailed();
 6212 alvherre@alvh.no-ip.     4138                 :              0 :         avlauncher_needs_signal = true;
                               4139                 :                :     }
                               4140                 :                : }
                               4141                 :                : 
                               4142                 :                : 
                               4143                 :                : /*
                               4144                 :                :  * Create the opts file
                               4145                 :                :  */
                               4146                 :                : static bool
 8141 bruce@momjian.us         4147                 :CBC         991 : CreateOptsFile(int argc, char *argv[], char *fullprogname)
                               4148                 :                : {
                               4149                 :                :     FILE       *fp;
                               4150                 :                :     int         i;
                               4151                 :                : 
                               4152                 :                : #define OPTS_FILE   "postmaster.opts"
                               4153                 :                : 
 7724 tgl@sss.pgh.pa.us        4154         [ -  + ]:            991 :     if ((fp = fopen(OPTS_FILE, "w")) == NULL)
                               4155                 :                :     {
 2092 peter@eisentraut.org     4156         [ #  # ]:UBC           0 :         ereport(LOG,
                               4157                 :                :                 (errcode_for_file_access(),
                               4158                 :                :                  errmsg("could not create file \"%s\": %m", OPTS_FILE)));
 9545 peter_e@gmx.net          4159                 :              0 :         return false;
                               4160                 :                :     }
                               4161                 :                : 
 9545 peter_e@gmx.net          4162                 :CBC         991 :     fprintf(fp, "%s", fullprogname);
                               4163         [ +  + ]:           5197 :     for (i = 1; i < argc; i++)
 6636 bruce@momjian.us         4164                 :           4206 :         fprintf(fp, " \"%s\"", argv[i]);
 9545 peter_e@gmx.net          4165                 :            991 :     fputs("\n", fp);
                               4166                 :                : 
 8249 tgl@sss.pgh.pa.us        4167         [ -  + ]:            991 :     if (fclose(fp))
                               4168                 :                :     {
 2092 peter@eisentraut.org     4169         [ #  # ]:UBC           0 :         ereport(LOG,
                               4170                 :                :                 (errcode_for_file_access(),
                               4171                 :                :                  errmsg("could not write file \"%s\": %m", OPTS_FILE)));
 9545 peter_e@gmx.net          4172                 :              0 :         return false;
                               4173                 :                :     }
                               4174                 :                : 
 9545 peter_e@gmx.net          4175                 :CBC         991 :     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
  651 heikki.linnakangas@i     4189                 :           3540 : StartBackgroundWorker(RegisteredBgWorker *rw)
                               4190                 :                : {
                               4191                 :                :     PMChild    *bn;
                               4192                 :                :     pid_t       worker_pid;
                               4193                 :                : 
 3412 tgl@sss.pgh.pa.us        4194         [ -  + ]:           3540 :     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                 :                :      */
  651 heikki.linnakangas@i     4206                 :           3540 :     bn = AssignPostmasterChildSlot(B_BG_WORKER);
  756                          4207         [ -  + ]:           3540 :     if (bn == NULL)
                               4208                 :                :     {
  651 heikki.linnakangas@i     4209         [ #  # ]:UBC           0 :         ereport(LOG,
                               4210                 :                :                 (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
                               4211                 :                :                  errmsg("no slot available for new background worker process")));
 3412 tgl@sss.pgh.pa.us        4212                 :              0 :         rw->rw_crashed_at = GetCurrentTimestamp();
                               4213                 :              0 :         return false;
                               4214                 :                :     }
  747 heikki.linnakangas@i     4215                 :CBC        3540 :     bn->rw = rw;
  651                          4216                 :           3540 :     bn->bkend_type = B_BG_WORKER;
                               4217                 :           3540 :     bn->bgworker_notify = false;
                               4218                 :                : 
 4080 rhaas@postgresql.org     4219         [ +  + ]:           3540 :     ereport(DEBUG1,
                               4220                 :                :             (errmsg_internal("starting background worker process \"%s\"",
                               4221                 :                :                              rw->rw_worker.bgw_name)));
                               4222                 :                : 
  651 heikki.linnakangas@i     4223                 :           3540 :     worker_pid = postmaster_child_launch(B_BG_WORKER, bn->child_slot,
  552 peter@eisentraut.org     4224                 :           3540 :                                          &rw->rw_worker, sizeof(BackgroundWorker), NULL);
  892 heikki.linnakangas@i     4225         [ -  + ]:           3540 :     if (worker_pid == -1)
                               4226                 :                :     {
                               4227                 :                :         /* in postmaster, fork failed ... */
  892 heikki.linnakangas@i     4228         [ #  # ]:UBC           0 :         ereport(LOG,
                               4229                 :                :                 (errmsg("could not fork background worker process: %m")));
                               4230                 :                :         /* undo what AssignPostmasterChildSlot did */
  651                          4231                 :              0 :         ReleasePostmasterChildSlot(bn);
                               4232                 :                : 
                               4233                 :                :         /* mark entry as crashed, so we'll try again later */
  892                          4234                 :              0 :         rw->rw_crashed_at = GetCurrentTimestamp();
                               4235                 :              0 :         return false;
                               4236                 :                :     }
                               4237                 :                : 
                               4238                 :                :     /* in postmaster, fork successful ... */
  892 heikki.linnakangas@i     4239                 :CBC        3540 :     rw->rw_pid = worker_pid;
  747                          4240                 :           3540 :     bn->pid = rw->rw_pid;
  892                          4241                 :           3540 :     ReportBackgroundWorkerPID(rw);
                               4242                 :           3540 :     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
 5012 alvherre@alvh.no-ip.     4250                 :           4653 : bgworker_should_start_now(BgWorkerStartTime start_time)
                               4251                 :                : {
                               4252   [ -  +  +  +  :           4653 :     switch (pmState)
                                                 - ]
                               4253                 :                :     {
 5012 alvherre@alvh.no-ip.     4254                 :UBC           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                 :                : 
 5012 alvherre@alvh.no-ip.     4264                 :CBC        3540 :         case PM_RUN:
                               4265         [ +  + ]:           3540 :             if (start_time == BgWorkerStart_RecoveryFinished)
                               4266                 :           1519 :                 return true;
                               4267                 :                :             pg_fallthrough;
                               4268                 :                : 
                               4269                 :                :         case PM_HOT_STANDBY:
                               4270         [ +  + ]:           2197 :             if (start_time == BgWorkerStart_ConsistentState)
                               4271                 :           2021 :                 return true;
                               4272                 :                :             pg_fallthrough;
                               4273                 :                : 
                               4274                 :                :         case PM_RECOVERY:
                               4275                 :                :         case PM_STARTUP:
                               4276                 :                :         case PM_INIT:
                               4277         [ -  + ]:           1113 :             if (start_time == BgWorkerStart_PostmasterStart)
 5012 alvherre@alvh.no-ip.     4278                 :UBC           0 :                 return true;
                               4279                 :                :     }
                               4280                 :                : 
 5012 alvherre@alvh.no-ip.     4281                 :CBC        1113 :     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
 3410 tgl@sss.pgh.pa.us        4296                 :           9227 : maybe_start_bgworkers(void)
                               4297                 :                : {
                               4298                 :                : #define MAX_BGWORKERS_TO_LAUNCH 100
                               4299                 :           9227 :     int         num_launched = 0;
 5012 alvherre@alvh.no-ip.     4300                 :           9227 :     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         [ -  + ]:           9227 :     if (FatalError)
                               4308                 :                :     {
 5012 alvherre@alvh.no-ip.     4309                 :UBC           0 :         StartWorkerNeeded = false;
                               4310                 :              0 :         HaveCrashedWorker = false;
 3412 tgl@sss.pgh.pa.us        4311                 :              0 :         return;
                               4312                 :                :     }
                               4313                 :                : 
                               4314                 :                :     /* Don't need to be called again unless we find a reason for it below */
 3412 tgl@sss.pgh.pa.us        4315                 :CBC        9227 :     StartWorkerNeeded = false;
 5012 alvherre@alvh.no-ip.     4316                 :           9227 :     HaveCrashedWorker = false;
                               4317                 :                : 
  748 heikki.linnakangas@i     4318   [ +  -  +  + ]:          25154 :     dlist_foreach_modify(iter, &BackgroundWorkerList)
                               4319                 :                :     {
                               4320                 :                :         RegisteredBgWorker *rw;
                               4321                 :                : 
                               4322                 :          15927 :         rw = dlist_container(RegisteredBgWorker, rw_lnode, iter.cur);
                               4323                 :                : 
                               4324                 :                :         /* ignore if already running */
 5012 alvherre@alvh.no-ip.     4325         [ +  + ]:          15927 :         if (rw->rw_pid != 0)
                               4326                 :           8406 :             continue;
                               4327                 :                : 
                               4328                 :                :         /* if marked for death, clean up and remove from list */
 4696 rhaas@postgresql.org     4329         [ -  + ]:           7521 :         if (rw->rw_terminate)
                               4330                 :                :         {
  748 heikki.linnakangas@i     4331                 :UBC           0 :             ForgetBackgroundWorker(rw);
 4696 rhaas@postgresql.org     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                 :                :          */
 5012 alvherre@alvh.no-ip.     4342         [ +  + ]:CBC        7521 :         if (rw->rw_crashed_at != 0)
                               4343                 :                :         {
                               4344         [ -  + ]:           2868 :             if (rw->rw_worker.bgw_restart_time == BGW_NEVER_RESTART)
 4790 rhaas@postgresql.org     4345                 :UBC           0 :             {
                               4346                 :                :                 int         notify_pid;
                               4347                 :                : 
 3186                          4348                 :              0 :                 notify_pid = rw->rw_worker.bgw_notify_pid;
                               4349                 :                : 
  748 heikki.linnakangas@i     4350                 :              0 :                 ForgetBackgroundWorker(rw);
                               4351                 :                : 
                               4352                 :                :                 /* Report worker is gone now. */
 3186 rhaas@postgresql.org     4353         [ #  # ]:              0 :                 if (notify_pid != 0)
                               4354                 :              0 :                     kill(notify_pid, SIGUSR1);
                               4355                 :                : 
 5012 alvherre@alvh.no-ip.     4356                 :              0 :                 continue;
                               4357                 :                :             }
                               4358                 :                : 
                               4359                 :                :             /* read system time only when needed */
 5012 alvherre@alvh.no-ip.     4360         [ +  - ]:CBC        2868 :             if (now == 0)
                               4361                 :           2868 :                 now = GetCurrentTimestamp();
                               4362                 :                : 
                               4363         [ +  - ]:           2868 :             if (!TimestampDifferenceExceeds(rw->rw_crashed_at, now,
 3354 tgl@sss.pgh.pa.us        4364                 :           2868 :                                             rw->rw_worker.bgw_restart_time * 1000))
                               4365                 :                :             {
                               4366                 :                :                 /* Set flag to remember that we have workers to start later */
 5012 alvherre@alvh.no-ip.     4367                 :           2868 :                 HaveCrashedWorker = true;
                               4368                 :           2868 :                 continue;
                               4369                 :                :             }
                               4370                 :                :         }
                               4371                 :                : 
                               4372         [ +  + ]:           4653 :         if (bgworker_should_start_now(rw->rw_worker.bgw_start_time))
                               4373                 :                :         {
                               4374                 :                :             /* reset crash time before trying to start worker */
                               4375                 :           3540 :             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                 :                :              */
  651 heikki.linnakangas@i     4388         [ -  + ]:           3540 :             if (!StartBackgroundWorker(rw))
                               4389                 :                :             {
 3412 tgl@sss.pgh.pa.us        4390                 :UBC           0 :                 StartWorkerNeeded = true;
 4013 rhaas@postgresql.org     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                 :                :              */
 3410 tgl@sss.pgh.pa.us        4400         [ -  + ]:CBC        3540 :             if (++num_launched >= MAX_BGWORKERS_TO_LAUNCH)
                               4401                 :                :             {
 3410 tgl@sss.pgh.pa.us        4402                 :UBC           0 :                 StartWorkerNeeded = true;
                               4403                 :              0 :                 return;
                               4404                 :                :             }
                               4405                 :                :         }
                               4406                 :                :     }
                               4407                 :                : }
                               4408                 :                : 
                               4409                 :                : static bool
  527 andres@anarazel.de       4410                 :CBC       21350 : maybe_reap_io_worker(int pid)
                               4411                 :                : {
  411 tmunro@postgresql.or     4412         [ +  + ]:         640835 :     for (int i = 0; i < MAX_IO_WORKERS; ++i)
                               4413                 :                :     {
                               4414         [ +  + ]:         621524 :         if (io_worker_children[i] &&
                               4415         [ +  + ]:          41783 :             io_worker_children[i]->pid == pid)
                               4416                 :                :         {
                               4417                 :           2039 :             ReleasePostmasterChildSlot(io_worker_children[i]);
                               4418                 :                : 
  527 andres@anarazel.de       4419                 :           2039 :             --io_worker_count;
  411 tmunro@postgresql.or     4420                 :           2039 :             io_worker_children[i] = NULL;
  527 andres@anarazel.de       4421                 :           2039 :             return true;
                               4422                 :                :         }
                               4423                 :                :     }
                               4424                 :          19311 :     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
  141 tmunro@postgresql.or     4436                 :          94036 : maybe_start_io_workers_scheduled_at(void)
                               4437                 :                : {
  527 andres@anarazel.de       4438         [ +  + ]:          94036 :     if (!pgaio_workers_enabled())
  141 tmunro@postgresql.or     4439                 :            232 :         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                 :                :      */
  527 andres@anarazel.de       4445         [ +  + ]:          93804 :     if (pmState >= PM_WAIT_IO_WORKERS)
  141 tmunro@postgresql.or     4446                 :           5148 :         return 0;
                               4447                 :                : 
                               4448                 :                :     /* Don't start new workers during an immediate shutdown either. */
  527 andres@anarazel.de       4449         [ +  + ]:          88656 :     if (Shutdown >= ImmediateShutdown)
  141 tmunro@postgresql.or     4450                 :           2213 :         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                 :                :      */
  527 andres@anarazel.de       4456   [ +  +  +  + ]:          86443 :     if (FatalError && pmState >= PM_STOP_BACKENDS)
  141 tmunro@postgresql.or     4457                 :            156 :         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         [ +  + ]:          86287 :     if (io_worker_count >= io_max_workers)
                               4465                 :             37 :         return 0;
                               4466                 :                : 
                               4467                 :                :     /* If we're under the minimum, start a worker as soon as possible. */
                               4468         [ +  + ]:          86250 :     if (io_worker_count < io_min_workers)
                               4469                 :           2022 :         return TIMESTAMP_MINUS_INFINITY;    /* start worker ASAP */
                               4470                 :                : 
                               4471                 :                :     /* Only proceed if a "grow" signal has been received from a worker. */
                               4472         [ +  + ]:          84228 :     if (!pgaio_worker_pm_test_grow_signal_sent())
                               4473                 :          84106 :         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                 :            122 :     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                 :          47768 : maybe_start_io_workers(void)
                               4490                 :                : {
                               4491                 :                :     TimestampTz scheduled_at;
                               4492                 :                : 
                               4493         [ +  + ]:          49807 :     while ((scheduled_at = maybe_start_io_workers_scheduled_at()) != 0)
                               4494                 :                :     {
                               4495                 :           2110 :         TimestampTz now = GetCurrentTimestamp();
                               4496                 :                :         PMChild    *child;
                               4497                 :                :         int         i;
                               4498                 :                : 
                               4499         [ -  + ]:           2110 :         Assert(pmState < PM_WAIT_IO_WORKERS);
                               4500                 :                : 
                               4501                 :                :         /* Still waiting for the scheduled time? */
                               4502         [ +  + ]:           2110 :         if (scheduled_at > now)
                               4503                 :             34 :             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                 :           2076 :         io_worker_launch_next_time =
                               4511                 :           2076 :             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         [ +  + ]:           2076 :         if (io_worker_launch_next_time <= now)
                               4520                 :           1062 :             io_worker_launch_next_time =
                               4521                 :           1062 :                 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   [ +  +  +  + ]:           2076 :         if (io_worker_count >= io_min_workers && !pgaio_worker_pm_test_grow())
                               4530                 :                :         {
                               4531                 :             37 :             pgaio_worker_pm_clear_grow_signal_sent();
                               4532                 :             37 :             break;
                               4533                 :                :         }
                               4534                 :                : 
                               4535                 :                :         /* find unused entry in io_worker_children array */
  411                          4536         [ +  - ]:           3572 :         for (i = 0; i < MAX_IO_WORKERS; ++i)
                               4537                 :                :         {
                               4538         [ +  + ]:           3572 :             if (io_worker_children[i] == NULL)
  527 andres@anarazel.de       4539                 :           2039 :                 break;
                               4540                 :                :         }
  411 tmunro@postgresql.or     4541         [ -  + ]:           2039 :         if (i == MAX_IO_WORKERS)
  411 tmunro@postgresql.or     4542         [ #  # ]:UBC           0 :             elog(ERROR, "could not find a free IO worker slot");
                               4543                 :                : 
                               4544                 :                :         /* Try to launch one. */
  527 andres@anarazel.de       4545                 :CBC        2039 :         child = StartChildProcess(B_IO_WORKER);
                               4546         [ +  - ]:           2039 :         if (child != NULL)
                               4547                 :                :         {
  411 tmunro@postgresql.or     4548                 :           2039 :             io_worker_children[i] = child;
  527 andres@anarazel.de       4549                 :           2039 :             ++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                 :                :              */
  141 tmunro@postgresql.or     4559                 :UBC           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                 :                :      */
  527 andres@anarazel.de       4567                 :CBC       47768 : }
                               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
 4747 rhaas@postgresql.org     4576                 :           2728 : PostmasterMarkPIDForWorkerNotify(int pid)
                               4577                 :                : {
                               4578                 :                :     dlist_iter  iter;
                               4579                 :                :     PMChild    *bp;
                               4580                 :                : 
  651 heikki.linnakangas@i     4581   [ +  -  +  - ]:           7191 :     dlist_foreach(iter, &ActiveChildList)
                               4582                 :                :     {
                               4583                 :           7191 :         bp = dlist_container(PMChild, elem, iter.cur);
 4747 rhaas@postgresql.org     4584         [ +  + ]:           7191 :         if (bp->pid == pid)
                               4585                 :                :         {
                               4586                 :           2728 :             bp->bgworker_notify = true;
                               4587                 :           2728 :             return true;
                               4588                 :                :         }
                               4589                 :                :     }
 4747 rhaas@postgresql.org     4590                 :UBC           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
 5529 heikki.linnakangas@i     4711                 :CBC         991 : 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         [ -  + ]:            991 :     Assert(MyProcPid == PostmasterPid);
 3415 tgl@sss.pgh.pa.us        4725         [ -  + ]:            991 :     if (pipe(postmaster_alive_fds) < 0)
 5529 heikki.linnakangas@i     4726         [ #  # ]:UBC           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. */
 2376 tgl@sss.pgh.pa.us        4731                 :CBC         991 :     ReserveExternalFD();
                               4732                 :            991 :     ReserveExternalFD();
                               4733                 :                : 
                               4734                 :                :     /*
                               4735                 :                :      * Set O_NONBLOCK to allow testing for the fd's presence with a read()
                               4736                 :                :      * call.
                               4737                 :                :      */
 3415                          4738         [ -  + ]:            991 :     if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFL, O_NONBLOCK) == -1)
 5529 heikki.linnakangas@i     4739         [ #  # ]:UBC           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 */
 5529 heikki.linnakangas@i     4758                 :CBC         991 : }
        

Generated by: LCOV version 2.0-1