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