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