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