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