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