]> granicus.if.org Git - apache/blob - server/mpm/mpmt_pthread/mpmt_pthread.c
Remove the ap_thread_mutex code from all MPM's. This code isn't actually
[apache] / server / mpm / mpmt_pthread / mpmt_pthread.c
1 /* ====================================================================
2  * Copyright (c) 1995-1999 The Apache Group.  All rights reserved.
3  * 
4  * Redistribution and use in source and binary forms, with or without 
5  * modification, are permitted provided that the following conditions 
6  * are met: 
7  * 
8  * 1. Redistributions of source code must retain the above copyright 
9  *    notice, this list of conditions and the following disclaimer.  
10  * 
11  * 2. Redistributions in binary form must reproduce the above copyright 
12  *    notice, this list of conditions and the following disclaimer in 
13  *    the documentation and/or other materials provided with the 
14  *    distribution. 
15  * 
16  * 3. All advertising materials mentioning features or use of this 
17  *    software must display the following acknowledgment: 
18  *    "This product includes software developed by the Apache Group 
19  *    for use in the Apache HTTP server project (http://www.apache.org/)." 
20  * 
21  * 4. The names "Apache Server" and "Apache Group" must not be used to 
22  *    endorse or promote products derived from this software without 
23  *    prior written permission. For written permission, please contact 
24  *    apache@apache.org. 
25  * 
26  * 5. Products derived from this software may not be called "Apache" 
27  *    nor may "Apache" appear in their names without prior written 
28  *    permission of the Apache Group. 
29  * 
30  * 6. Redistributions of any form whatsoever must retain the following 
31  *    acknowledgment: 
32  *    "This product includes software developed by the Apache Group 
33  *    for use in the Apache HTTP server project (http://www.apache.org/)." 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE APACHE GROUP ``AS IS'' AND ANY 
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
38  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE APACHE GROUP OR 
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
46  * OF THE POSSIBILITY OF SUCH DAMAGE. 
47  * ==================================================================== 
48  * 
49  * This software consists of voluntary contributions made by many 
50  * individuals on behalf of the Apache Group and was originally based 
51  * on public domain software written at the National Center for 
52  * Supercomputing Applications, University of Illinois, Urbana-Champaign. 
53  * For more information on the Apache Group and the Apache HTTP server 
54  * project, please see <http://www.apache.org/>. 
55  * 
56  */ 
57  
58 #define CORE_PRIVATE 
59  
60 #include "apr_portable.h"
61 #include "httpd.h" 
62 #include "http_main.h" 
63 #include "http_log.h" 
64 #include "http_config.h"        /* for read_config */ 
65 #include "http_core.h"          /* for get_remote_host */ 
66 #include "http_connection.h"
67 #include "ap_mpm.h"
68 #include "unixd.h"
69 #include "iol_socket.h"
70 #include "ap_listen.h"
71 #include "scoreboard.h" 
72
73 #include <netinet/tcp.h> 
74 #include <pthread.h>
75
76 /*
77  * Actual definitions of config globals
78  */
79
80 int ap_threads_per_child=0;         /* Worker threads per child */
81 int ap_max_requests_per_child=0;
82 static char *ap_pid_fname=NULL;
83 static char *ap_scoreboard_fname=NULL;
84 static int ap_daemons_to_start=0;
85 static int min_spare_threads=0;
86 static int max_spare_threads=0;
87 static int ap_daemons_limit=0;
88 static time_t ap_restart_time=0;
89 API_VAR_EXPORT int ap_extended_status = 0;
90 static int workers_may_exit = 0;
91 static int requests_this_child;
92 static int num_listensocks = 0;
93 static ap_socket_t **listensocks;
94
95 /* The structure used to pass unique initialization info to each thread */
96 typedef struct {
97     int pid;
98     int tid;
99     int sd;
100     ap_context_t *tpool; /* "pthread" would be confusing */
101 } proc_info;
102
103 /*
104  * The max child slot ever assigned, preserved across restarts.  Necessary
105  * to deal with MaxClients changes across SIGWINCH restarts.  We use this
106  * value to optimize routines that have to scan the entire scoreboard.
107  */
108 static int max_daemons_limit = -1;
109
110 static char ap_coredump_dir[MAX_STRING_LEN];
111
112 static int pipe_of_death[2];
113 static pthread_mutex_t pipe_of_death_mutex;
114
115 /* *Non*-shared http_main globals... */
116
117 static server_rec *server_conf;
118
119 /* one_process --- debugging mode variable; can be set from the command line
120  * with the -X flag.  If set, this gets you the child_main loop running
121  * in the process which originally started up (no detach, no make_child),
122  * which is a pretty nice debugging environment.  (You'll get a SIGHUP
123  * early in standalone_main; just continue through.  This is the server
124  * trying to kill off any child processes which it might have lying
125  * around --- Apache doesn't keep track of their pids, it just sends
126  * SIGHUP to the process group, ignoring it in the root process.
127  * Continue through and you'll be fine.).
128  */
129
130 static int one_process = 0;
131
132 #ifdef DEBUG_SIGSTOP
133 int raise_sigstop_flags;
134 #endif
135
136 #ifdef HAS_OTHER_CHILD
137 /* used to maintain list of children which aren't part of the scoreboard */
138 typedef struct other_child_rec other_child_rec;
139 struct other_child_rec {
140     other_child_rec *next;
141     int pid;
142     void (*maintenance) (int, void *, ap_wait_t);
143     void *data;
144     int write_fd;
145 };
146 static other_child_rec *other_children;
147 #endif
148
149 static ap_context_t *pconf;             /* Pool for config stuff */
150 static ap_context_t *pchild;            /* Pool for httpd child stuff */
151
152 static int my_pid; /* Linux getpid() doesn't work except in main thread. Use
153                       this instead */
154 /* Keep track of the number of worker threads currently active */
155 static int worker_thread_count;
156 static pthread_mutex_t worker_thread_count_mutex;
157
158 /* Locks for accept serialization */
159 static pthread_mutex_t thread_accept_mutex = PTHREAD_MUTEX_INITIALIZER;
160 static ap_lock_t *process_accept_mutex;
161 static char *lock_fname;
162
163 #ifdef NO_SERIALIZED_ACCEPT
164 #define SAFE_ACCEPT(stmt) APR_SUCCESS
165 #else
166 #define SAFE_ACCEPT(stmt) (stmt)
167 #endif
168
169
170 /* Global, alas, so http_core can talk to us */
171 enum server_token_type ap_server_tokens = SrvTk_FULL;
172
173 API_EXPORT(const server_rec *) ap_get_server_conf(void)
174 {
175     return (server_conf);
176 }
177
178 API_EXPORT(int) ap_get_max_daemons(void)
179 {
180     return max_daemons_limit;
181 }
182
183 /* a clean exit from a child with proper cleanup 
184    static void clean_child_exit(int code) __attribute__ ((noreturn)); */
185 void clean_child_exit(int code)
186 {
187     if (pchild) {
188         ap_destroy_pool(pchild);
189     }
190     exit(code);
191 }
192
193 /*****************************************************************
194  * dealing with other children
195  */
196
197 #ifdef HAS_OTHER_CHILD
198 API_EXPORT(void) ap_register_other_child(int pid,
199                        void (*maintenance) (int reason, void *, ap_wait_t status),
200                           void *data, int write_fd)
201 {
202     other_child_rec *ocr;
203
204     ocr = ap_palloc(pconf, sizeof(*ocr));
205     ocr->pid = pid;
206     ocr->maintenance = maintenance;
207     ocr->data = data;
208     ocr->write_fd = write_fd;
209     ocr->next = other_children;
210     other_children = ocr;
211 }
212
213 /* note that since this can be called by a maintenance function while we're
214  * scanning the other_children list, all scanners should protect themself
215  * by loading ocr->next before calling any maintenance function.
216  */
217 API_EXPORT(void) ap_unregister_other_child(void *data)
218 {
219     other_child_rec **pocr, *nocr;
220
221     for (pocr = &other_children; *pocr; pocr = &(*pocr)->next) {
222         if ((*pocr)->data == data) {
223             nocr = (*pocr)->next;
224             (*(*pocr)->maintenance) (OC_REASON_UNREGISTER, (*pocr)->data, -1);
225             *pocr = nocr;
226             /* XXX: um, well we've just wasted some space in pconf ? */
227             return;
228         }
229     }
230 }
231
232 /* test to ensure that the write_fds are all still writable, otherwise
233  * invoke the maintenance functions as appropriate */
234 static void probe_writable_fds(void)
235 {
236     return;
237 #if 0
238     fd_set writable_fds;
239     int fd_max;
240     other_child_rec *ocr, *nocr;
241     struct timeval tv;
242     int rc;
243
244     if (other_children == NULL)
245         return;
246
247     fd_max = 0;
248     FD_ZERO(&writable_fds);
249     do {
250         for (ocr = other_children; ocr; ocr = ocr->next) {
251             if (ocr->write_fd == -1)
252                 continue;
253             FD_SET(ocr->write_fd, &writable_fds);
254             if (ocr->write_fd > fd_max) {
255                 fd_max = ocr->write_fd;
256             }
257         }
258         if (fd_max == 0)
259             return;
260
261         tv.tv_sec = 0;
262         tv.tv_usec = 0;
263         rc = ap_select(fd_max + 1, NULL, &writable_fds, NULL, &tv);
264     } while (rc == -1 && errno == EINTR);
265
266     if (rc == -1) {
267         /* XXX: uhh this could be really bad, we could have a bad file
268          * descriptor due to a bug in one of the maintenance routines */
269         ap_log_unixerr("probe_writable_fds", "select",
270                     "could not probe writable fds", server_conf);
271         return;
272     }
273     if (rc == 0)
274         return;
275
276     for (ocr = other_children; ocr; ocr = nocr) {
277         nocr = ocr->next;
278         if (ocr->write_fd == -1)
279             continue;
280         if (FD_ISSET(ocr->write_fd, &writable_fds))
281             continue;
282         (*ocr->maintenance) (OC_REASON_UNWRITABLE, ocr->data, -1);
283     }
284 #endif
285 }
286
287 /* possibly reap an other_child, return 0 if yes, -1 if not */
288 static int reap_other_child(int pid, ap_wait_t status)
289 {
290     other_child_rec *ocr, *nocr;
291
292     for (ocr = other_children; ocr; ocr = nocr) {
293         nocr = ocr->next;
294         if (ocr->pid != pid)
295             continue;
296         ocr->pid = -1;
297         (*ocr->maintenance) (OC_REASON_DEATH, ocr->data, status);
298         return 0;
299     }
300     return -1;
301 }
302 #endif
303
304 static void reclaim_child_processes(int terminate)
305 {
306     int i, status;
307     long int waittime = 1024 * 16;      /* in usecs */
308     struct timeval tv;
309     int waitret, tries;
310     int not_dead_yet;
311 #ifdef HAS_OTHER_CHILD
312     other_child_rec *ocr, *nocr;
313 #endif
314
315     ap_sync_scoreboard_image();
316
317     for (tries = terminate ? 4 : 1; tries <= 9; ++tries) {
318         /* don't want to hold up progress any more than 
319          * necessary, but we need to allow children a few moments to exit.
320          * Set delay with an exponential backoff.
321          */
322         tv.tv_sec = waittime / 1000000;
323         tv.tv_usec = waittime % 1000000;
324         waittime = waittime * 4;
325         ap_select(0, NULL, NULL, NULL, &tv);
326
327         /* now see who is done */
328         not_dead_yet = 0;
329         for (i = 0; i < max_daemons_limit; ++i) {
330             int pid = ap_scoreboard_image->parent[i].pid;
331
332             if (pid == my_pid || pid == 0)
333                 continue;
334
335             waitret = waitpid(pid, &status, WNOHANG);
336             if (waitret == pid || waitret == -1) {
337                 ap_scoreboard_image->parent[i].pid = 0;
338                 continue;
339             }
340             ++not_dead_yet;
341             switch (tries) {
342             case 1:     /*  16ms */
343             case 2:     /*  82ms */
344                 break;
345             case 3:     /* 344ms */
346             case 4:     /*  16ms */
347             case 5:     /*  82ms */
348             case 6:     /* 344ms */
349             case 7:     /* 1.4sec */
350                 /* ok, now it's being annoying */
351                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING,
352                             0, server_conf,
353                    "child process %d still did not exit, sending a SIGTERM",
354                             pid);
355                 kill(pid, SIGTERM);
356                 break;
357             case 8:     /*  6 sec */
358                 /* die child scum */
359                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, server_conf,
360                    "child process %d still did not exit, sending a SIGKILL",
361                             pid);
362                 kill(pid, SIGKILL);
363                 break;
364             case 9:     /* 14 sec */
365                 /* gave it our best shot, but alas...  If this really 
366                  * is a child we are trying to kill and it really hasn't
367                  * exited, we will likely fail to bind to the port
368                  * after the restart.
369                  */
370                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, server_conf,
371                             "could not make child process %d exit, "
372                             "attempting to continue anyway", pid);
373                 break;
374             }
375         }
376 #ifdef HAS_OTHER_CHILD
377         for (ocr = other_children; ocr; ocr = nocr) {
378             nocr = ocr->next;
379             if (ocr->pid == -1)
380                 continue;
381
382             waitret = waitpid(ocr->pid, &status, WNOHANG);
383             if (waitret == ocr->pid) {
384                 ocr->pid = -1;
385                 (*ocr->maintenance) (OC_REASON_DEATH, ocr->data, status);
386             }
387             else if (waitret == 0) {
388                 (*ocr->maintenance) (OC_REASON_RESTART, ocr->data, -1);
389                 ++not_dead_yet;
390             }
391             else if (waitret == -1) {
392                 /* uh what the heck? they didn't call unregister? */
393                 ocr->pid = -1;
394                 (*ocr->maintenance) (OC_REASON_LOST, ocr->data, -1);
395             }
396         }
397 #endif
398         if (!not_dead_yet) {
399             /* nothing left to wait for */
400             break;
401         }
402     }
403 }
404
405 /* Finally, this routine is used by the caretaker process to wait for
406  * a while...
407  */
408
409 /* number of calls to wait_or_timeout between writable probes */
410 #ifndef INTERVAL_OF_WRITABLE_PROBES
411 #define INTERVAL_OF_WRITABLE_PROBES 10
412 #endif
413 static int wait_or_timeout_counter;
414
415 static int wait_or_timeout(ap_wait_t *status)
416 {
417     struct timeval tv;
418     int ret;
419
420     ++wait_or_timeout_counter;
421     if (wait_or_timeout_counter == INTERVAL_OF_WRITABLE_PROBES) {
422         wait_or_timeout_counter = 0;
423 #ifdef HAS_OTHER_CHILD
424         probe_writable_fds();
425 #endif
426     }
427     ret = waitpid(-1, status, WNOHANG);
428     if (ret == -1 && errno == EINTR) {
429         return -1;
430     }
431     if (ret > 0) {
432         return ret;
433     }
434     tv.tv_sec = SCOREBOARD_MAINTENANCE_INTERVAL / 1000000;
435     tv.tv_usec = SCOREBOARD_MAINTENANCE_INTERVAL % 1000000;
436     ap_select(0, NULL, NULL, NULL, &tv);
437     return -1;
438 }
439
440 /* handle all varieties of core dumping signals */
441 static void sig_coredump(int sig)
442 {
443     chdir(ap_coredump_dir);
444     signal(sig, SIG_DFL);
445     kill(my_pid, sig);
446     /* At this point we've got sig blocked, because we're still inside
447      * the signal handler.  When we leave the signal handler it will
448      * be unblocked, and we'll take the signal... and coredump or whatever
449      * is appropriate for this particular Unix.  In addition the parent
450      * will see the real signal we received -- whereas if we called
451      * abort() here, the parent would only see SIGABRT.
452      */
453 }
454
455 static void just_die(int sig)
456 {
457     clean_child_exit(0);
458 }
459
460 /*****************************************************************
461  * Connection structures and accounting...
462  */
463
464 /* volatile just in case */
465 static int volatile shutdown_pending;
466 static int volatile restart_pending;
467 static int volatile is_graceful;
468 ap_generation_t volatile ap_my_generation;
469
470 /*
471  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
472  * functions to initiate shutdown or restart without relying on signals. 
473  * Previously this was initiated in sig_term() and restart() signal handlers, 
474  * but we want to be able to start a shutdown/restart from other sources --
475  * e.g. on Win32, from the service manager. Now the service manager can
476  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
477  * these functions can also be called by the child processes, since global
478  * variables are no longer used to pass on the required action to the parent.
479  *
480  * These should only be called from the parent process itself, since the
481  * parent process will use the shutdown_pending and restart_pending variables
482  * to determine whether to shutdown or restart. The child process should
483  * call signal_parent() directly to tell the parent to die -- this will
484  * cause neither of those variable to be set, which the parent will
485  * assume means something serious is wrong (which it will be, for the
486  * child to force an exit) and so do an exit anyway.
487  */
488
489 void ap_start_shutdown(void)
490 {
491     if (shutdown_pending == 1) {
492         /* Um, is this _probably_ not an error, if the user has
493          * tried to do a shutdown twice quickly, so we won't
494          * worry about reporting it.
495          */
496         return;
497     }
498     shutdown_pending = 1;
499 }
500
501 /* do a graceful restart if graceful == 1 */
502 void ap_start_restart(int graceful)
503 {
504
505     if (restart_pending == 1) {
506         /* Probably not an error - don't bother reporting it */
507         return;
508     }
509     restart_pending = 1;
510     is_graceful = graceful;
511 }
512
513 static void sig_term(int sig)
514 {
515     ap_start_shutdown();
516 }
517
518 static void restart(int sig)
519 {
520 #ifndef WIN32
521     ap_start_restart(sig == SIGWINCH);
522 #else
523     ap_start_restart(1);
524 #endif
525 }
526
527 static void set_signals(void)
528 {
529 #ifndef NO_USE_SIGACTION
530     struct sigaction sa;
531
532     sigemptyset(&sa.sa_mask);
533     sa.sa_flags = 0;
534
535     if (!one_process) {
536         sa.sa_handler = sig_coredump;
537 #if defined(SA_ONESHOT)
538         sa.sa_flags = SA_ONESHOT;
539 #elif defined(SA_RESETHAND)
540         sa.sa_flags = SA_RESETHAND;
541 #endif
542         if (sigaction(SIGSEGV, &sa, NULL) < 0)
543             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGSEGV)");
544 #ifdef SIGBUS
545         if (sigaction(SIGBUS, &sa, NULL) < 0)
546             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGBUS)");
547 #endif
548 #ifdef SIGABORT
549         if (sigaction(SIGABORT, &sa, NULL) < 0)
550             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGABORT)");
551 #endif
552 #ifdef SIGABRT
553         if (sigaction(SIGABRT, &sa, NULL) < 0)
554             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGABRT)");
555 #endif
556 #ifdef SIGILL
557         if (sigaction(SIGILL, &sa, NULL) < 0)
558             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGILL)");
559 #endif
560         sa.sa_flags = 0;
561     }
562     sa.sa_handler = sig_term;
563     if (sigaction(SIGTERM, &sa, NULL) < 0)
564         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGTERM)");
565 #ifdef SIGINT
566     if (sigaction(SIGINT, &sa, NULL) < 0)
567         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGINT)");
568 #endif
569 #ifdef SIGXCPU
570     sa.sa_handler = SIG_DFL;
571     if (sigaction(SIGXCPU, &sa, NULL) < 0)
572         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGXCPU)");
573 #endif
574 #ifdef SIGXFSZ
575     sa.sa_handler = SIG_DFL;
576     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
577         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGXFSZ)");
578 #endif
579 #ifdef SIGPIPE
580     sa.sa_handler = SIG_IGN;
581     if (sigaction(SIGPIPE, &sa, NULL) < 0)
582         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGPIPE)");
583 #endif
584
585     /* we want to ignore HUPs and WINCH while we're busy processing one */
586     sigaddset(&sa.sa_mask, SIGHUP);
587     sigaddset(&sa.sa_mask, SIGWINCH);
588     sa.sa_handler = restart;
589     if (sigaction(SIGHUP, &sa, NULL) < 0)
590         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGHUP)");
591     if (sigaction(SIGWINCH, &sa, NULL) < 0)
592         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGWINCH)");
593 #else
594     if (!one_process) {
595         signal(SIGSEGV, sig_coredump);
596 #ifdef SIGBUS
597         signal(SIGBUS, sig_coredump);
598 #endif /* SIGBUS */
599 #ifdef SIGABORT
600         signal(SIGABORT, sig_coredump);
601 #endif /* SIGABORT */
602 #ifdef SIGABRT
603         signal(SIGABRT, sig_coredump);
604 #endif /* SIGABRT */
605 #ifdef SIGILL
606         signal(SIGILL, sig_coredump);
607 #endif /* SIGILL */
608 #ifdef SIGXCPU
609         signal(SIGXCPU, SIG_DFL);
610 #endif /* SIGXCPU */
611 #ifdef SIGXFSZ
612         signal(SIGXFSZ, SIG_DFL);
613 #endif /* SIGXFSZ */
614     }
615
616     signal(SIGTERM, sig_term);
617 #ifdef SIGHUP
618     signal(SIGHUP, restart);
619 #endif /* SIGHUP */
620 #ifdef SIGWINCH
621     signal(SIGWINCH, restart);
622 #endif /* SIGWINCH */
623 #ifdef SIGPIPE
624     signal(SIGPIPE, SIG_IGN);
625 #endif /* SIGPIPE */
626
627 #endif
628 }
629
630 static void process_child_status(int pid, ap_wait_t status)
631 {
632     /* Child died... if it died due to a fatal error,
633         * we should simply bail out.
634         */
635     if ((WIFEXITED(status)) &&
636         WEXITSTATUS(status) == APEXIT_CHILDFATAL) {
637         ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO, 0, server_conf,
638                         "Child %d returned a Fatal error... \n"
639                         "Apache is exiting!",
640                         pid);
641         exit(APEXIT_CHILDFATAL);
642     }
643     if (WIFSIGNALED(status)) {
644         switch (WTERMSIG(status)) {
645         case SIGTERM:
646         case SIGHUP:
647         case SIGUSR1:
648         case SIGKILL:
649             break;
650         default:
651 #ifdef SYS_SIGLIST
652 #ifdef WCOREDUMP
653             if (WCOREDUMP(status)) {
654                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
655                              0, server_conf,
656                              "child pid %d exit signal %s (%d), "
657                              "possible coredump in %s",
658                              pid, (WTERMSIG(status) >= NumSIG) ? "" : 
659                              SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status),
660                              ap_coredump_dir);
661             }
662             else {
663 #endif
664                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
665                              0, server_conf,
666                              "child pid %d exit signal %s (%d)", pid,
667                              SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status));
668 #ifdef WCOREDUMP
669             }
670 #endif
671 #else
672             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
673                          server_conf,
674                          "child pid %d exit signal %d",
675                          pid, WTERMSIG(status));
676 #endif
677         }
678     }
679 }
680
681 static int setup_listeners(server_rec *s)
682 {
683     ap_listen_rec *lr;
684     int num_listeners = 0;
685     if (ap_listen_open(s->process, s->port)) {
686        return 0;
687     }
688     for (lr = ap_listeners; lr; lr = lr->next) {
689         num_listeners++;
690     }
691     return num_listeners;
692 }
693
694 /*****************************************************************
695  * Here follows a long bunch of generic server bookkeeping stuff...
696  */
697
698 #if defined(TCP_NODELAY) && !defined(MPE) && !defined(TPF)
699 static void sock_disable_nagle(int s) 
700 {
701     /* The Nagle algorithm says that we should delay sending partial
702      * packets in hopes of getting more data.  We don't want to do
703      * this; we are not telnet.  There are bad interactions between
704      * persistent connections and Nagle's algorithm that have very severe
705      * performance penalties.  (Failing to disable Nagle is not much of a
706      * problem with simple HTTP.)
707      *
708      * In spite of these problems, failure here is not a shooting offense.
709      */
710     int just_say_no = 1;
711
712     if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
713                    sizeof(int)) < 0) {
714         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf,
715                     "setsockopt: (TCP_NODELAY)");
716     }
717 }
718
719 #else
720 #define sock_disable_nagle(s)   /* NOOP */
721 #endif
722
723 int ap_graceful_stop_signalled(void)
724 {
725     /* XXX - Does this really work? - Manoj */
726     return is_graceful;
727 }
728
729 /*****************************************************************
730  * Child process main loop.
731  */
732
733 static void process_socket(ap_context_t *p, ap_socket_t *sock, int my_child_num, int my_thread_num)
734 {
735     BUFF *conn_io;
736     conn_rec *current_conn;
737     ap_iol *iol;
738     long conn_id = my_child_num * HARD_THREAD_LIMIT + my_thread_num;
739     int csd;
740
741     (void) ap_get_os_sock(&csd, sock);
742
743     sock_disable_nagle(csd);
744
745     iol = unix_attach_socket(sock);
746     if (iol == NULL) {
747         if (errno == EBADF) {
748             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
749                 "filedescriptor (%u) larger than FD_SETSIZE (%u) "
750                 "found, you probably need to rebuild Apache with a "
751                 "larger FD_SETSIZE", csd, FD_SETSIZE);
752         }
753         else {
754             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, NULL,
755                 "error attaching to socket");
756         }
757         ap_close_socket(sock);
758         return;
759     }
760
761     (void) ap_update_child_status(my_child_num, my_thread_num,  
762                                   SERVER_BUSY_READ, (request_rec *) NULL);
763     conn_io = ap_bcreate(p, B_RDWR);
764     ap_bpush_iol(conn_io, iol);
765
766     current_conn = ap_new_apr_connection(p, server_conf, conn_io, sock,
767                                          conn_id);
768
769     ap_process_connection(current_conn);
770 }
771 /* Sets workers_may_exit if we received a character on the pipe_of_death */
772 static void check_pipe_of_death(void)
773 {
774     pthread_mutex_lock(&pipe_of_death_mutex);
775     if (!workers_may_exit) {
776         ap_status_t ret;
777         char pipe_read_char;
778         int n=1;
779
780         ret = ap_recv(listensocks[0], &pipe_read_char, &n);
781         if (ret == APR_EAGAIN) {
782             /* It lost the lottery. It must continue to suffer
783              * through a life of servitude. */
784         }
785         else {
786             /* It won the lottery (or something else is very
787              * wrong). Embrace death with open arms. */
788             workers_may_exit = 1;
789         }
790     }
791     pthread_mutex_unlock(&pipe_of_death_mutex);
792 }
793
794 static void * worker_thread(void * dummy)
795 {
796     proc_info * ti = dummy;
797     int process_slot = ti->pid;
798     int thread_slot = ti->tid;
799     ap_context_t *tpool = ti->tpool;
800     ap_socket_t *csd = NULL;
801     ap_context_t *ptrans;               /* Pool for per-transaction stuff */
802     ap_socket_t *sd = NULL;
803     int n;
804     int curr_pollfd, last_pollfd = 0;
805     ap_pollfd_t *pollset;
806     ap_status_t rv;
807
808     free(ti);
809
810     ap_create_context(&ptrans, tpool);
811
812     pthread_mutex_lock(&worker_thread_count_mutex);
813     worker_thread_count++;
814     pthread_mutex_unlock(&worker_thread_count_mutex);
815
816     ap_setup_poll(&pollset, num_listensocks+1, tpool);
817     for(n=0 ; n <= num_listensocks ; ++n)
818         ap_add_poll_socket(pollset, listensocks[n], APR_POLLIN);
819
820     /* TODO: Switch to a system where threads reuse the results from earlier
821        poll calls - manoj */
822     while (!workers_may_exit) {
823         workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
824         if (workers_may_exit) break;
825
826         (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY, 
827                                       (request_rec *) NULL);
828         pthread_mutex_lock(&thread_accept_mutex);
829         if (workers_may_exit) {
830             pthread_mutex_unlock(&thread_accept_mutex);
831             break;
832         }
833         if ((rv = SAFE_ACCEPT(ap_lock(process_accept_mutex)))
834             != APR_SUCCESS) {
835             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
836                          "ap_lock failed. Attempting to shutdown "
837                          "process gracefully.");
838             workers_may_exit = 1;
839         }
840
841         while (!workers_may_exit) {
842             ap_status_t ret;
843             ap_int16_t event;
844
845             ret = ap_poll(pollset, &n, -1);
846             if (ret != APR_SUCCESS) {
847                 if (ret == APR_EINTR) {
848                     continue;
849                 }
850
851                 /* poll() will only return errors in catastrophic
852                  * circumstances. Let's try exiting gracefully, for now. */
853                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (const server_rec *)
854                              ap_get_server_conf(), "poll: (listen)");
855                 workers_may_exit = 1;
856             }
857
858             if (workers_may_exit) break;
859
860             ap_get_revents(&event, listensocks[0], pollset);
861             if (event & APR_POLLIN) {
862                 /* A process got a signal on the shutdown pipe. Check if we're
863                  * the lucky process to die. */
864                 check_pipe_of_death();
865                 continue;
866             }
867
868             if (num_listensocks == 1) {
869                 sd = ap_listeners->sd;
870                 goto got_fd;
871             }
872             else {
873                 /* find a listener */
874                 curr_pollfd = last_pollfd;
875                 do {
876                     curr_pollfd++;
877                     if (curr_pollfd > num_listensocks) {
878                         curr_pollfd = 1;
879                     }
880                     /* XXX: Should we check for POLLERR? */
881                     ap_get_revents(&event, listensocks[curr_pollfd], pollset);
882                     if (event & APR_POLLIN) {
883                         last_pollfd = curr_pollfd;
884                         sd=listensocks[curr_pollfd];
885                         goto got_fd;
886                     }
887                 } while (curr_pollfd != last_pollfd);
888             }
889         }
890     got_fd:
891         if (!workers_may_exit) {
892             ap_accept(&csd, sd, ptrans);
893             if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
894                 != APR_SUCCESS) {
895                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
896                              "ap_unlock failed. Attempting to shutdown "
897                              "process gracefully.");
898                 workers_may_exit = 1;
899             }
900             pthread_mutex_unlock(&thread_accept_mutex);
901             process_socket(ptrans, csd, process_slot, thread_slot);
902             requests_this_child--;
903         }
904         else {
905             if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
906                 != APR_SUCCESS) {
907                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
908                              "ap_unlock failed. Attempting to shutdown "
909                              "process gracefully.");
910                 workers_may_exit = 1;
911             }
912             pthread_mutex_unlock(&thread_accept_mutex);
913             break;
914         }
915         ap_clear_pool(ptrans);
916     }
917
918     ap_destroy_pool(tpool);
919     ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
920         (request_rec *) NULL);
921     pthread_mutex_lock(&worker_thread_count_mutex);
922     worker_thread_count--;
923     if (worker_thread_count == 0) {
924         /* All the threads have exited, now finish the shutdown process
925          * by signalling the sigwait thread */
926         kill(my_pid, SIGTERM);
927     }
928     pthread_mutex_unlock(&worker_thread_count_mutex);
929
930     return NULL;
931 }
932
933
934 static void child_main(int child_num_arg)
935 {
936     sigset_t sig_mask;
937     int signal_received;
938     pthread_t thread;
939     pthread_attr_t thread_attr;
940     int i;
941     int my_child_num = child_num_arg;
942     proc_info *my_info = NULL;
943     ap_listen_rec *lr;
944     ap_status_t rv;
945
946
947     my_pid = getpid();
948     ap_create_context(&pchild, pconf);
949
950     /*stuff to do before we switch id's, so we have permissions.*/
951     reopen_scoreboard(pchild);
952
953     rv = SAFE_ACCEPT(ap_child_init_lock(&process_accept_mutex, lock_fname,
954                      pchild));
955     if (rv != APR_SUCCESS) {
956         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
957                      "Couldn't initialize cross-process lock in child");
958         clean_child_exit(APEXIT_CHILDFATAL);
959     }
960
961     if (unixd_setup_child()) {
962         clean_child_exit(APEXIT_CHILDFATAL);
963     }
964
965     ap_child_init_hook(pchild, server_conf);
966
967     /*done with init critical section */
968
969     /* All threads should mask signals out, accoring to sigwait(2) man page */
970     sigfillset(&sig_mask);
971
972     if (pthread_sigmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
973         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf, "pthread_sigmask");
974     }
975
976     requests_this_child = ap_max_requests_per_child;
977     
978     /* Set up the pollfd array */
979     listensocks = ap_palloc(pchild,
980                             sizeof(*listensocks) * (num_listensocks + 1));
981     ap_create_tcp_socket(&listensocks[0], pchild);
982     ap_put_os_sock(&listensocks[0], &pipe_of_death[0], pchild);
983     for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
984         listensocks[i]=lr->sd;
985
986     /* Setup worker threads */
987
988     worker_thread_count = 0;
989     pthread_mutex_init(&worker_thread_count_mutex, NULL);
990     pthread_mutex_init(&pipe_of_death_mutex, NULL);
991     pthread_attr_init(&thread_attr);
992     pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
993     for (i=0; i < ap_threads_per_child; i++) {
994
995         my_info = (proc_info *)malloc(sizeof(proc_info));
996         if (my_info == NULL) {
997             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf,
998                          "malloc: out of memory");
999             clean_child_exit(APEXIT_CHILDFATAL);
1000         }
1001         my_info->pid = my_child_num;
1002         my_info->tid = i;
1003         my_info->sd = 0;
1004         ap_create_context(&my_info->tpool, pchild);
1005         
1006         /* We are creating threads right now */
1007         (void) ap_update_child_status(my_child_num, i, SERVER_STARTING, 
1008                                       (request_rec *) NULL);
1009 #ifndef NO_THREADS
1010         if (pthread_create(&thread, &thread_attr, worker_thread, my_info)) {
1011             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf,
1012                          "pthread_create: unable to create worker thread");
1013             /* In case system resources are maxxed out, we don't want
1014                Apache running away with the CPU trying to fork over and
1015                over and over again if we exit. */
1016             sleep(10);
1017             clean_child_exit(APEXIT_CHILDFATAL);
1018         }
1019 #else
1020         worker_thread(my_info);
1021         /* The SIGTERM shouldn't let us reach this point, but just in case... */
1022         clean_child_exit(APEXIT_OK);
1023 #endif
1024
1025         /* We let each thread update it's own scoreboard entry.  This is done
1026          * because it let's us deal with tid better.
1027          */
1028     }
1029
1030     pthread_attr_destroy(&thread_attr);
1031
1032     /* This thread will be the one responsible for handling signals */
1033     sigemptyset(&sig_mask);
1034     sigaddset(&sig_mask, SIGTERM);
1035     sigaddset(&sig_mask, SIGINT);
1036     sigwait(&sig_mask, &signal_received);
1037     switch (signal_received) {
1038         case SIGTERM:
1039         case SIGINT:
1040             just_die(signal_received);
1041             break;
1042         default:
1043             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf,
1044             "received impossible signal: %d", signal_received);
1045             just_die(SIGTERM);
1046     }
1047 }
1048
1049 static int make_child(server_rec *s, int slot, time_t now) 
1050 {
1051     int pid;
1052
1053     if (slot + 1 > max_daemons_limit) {
1054         max_daemons_limit = slot + 1;
1055     }
1056
1057     if (one_process) {
1058         set_signals();
1059         ap_scoreboard_image->parent[slot].pid = getpid();
1060         child_main(slot);
1061     }
1062
1063     /* Tag this slot as occupied so that perform_idle_server_maintenance
1064      * doesn't try to steal it */
1065     (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
1066
1067     if ((pid = fork()) == -1) {
1068         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
1069
1070         /* fork didn't succeed. Fix the scoreboard or else
1071          * it will say SERVER_STARTING forever and ever
1072          */
1073         (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
1074
1075         /* In case system resources are maxxed out, we don't want
1076            Apache running away with the CPU trying to fork over and
1077            over and over again. */
1078         sleep(10);
1079
1080         return -1;
1081     }
1082
1083     if (!pid) {
1084 #ifdef AIX_BIND_PROCESSOR
1085       /* By default, AIX binds to a single processor.  This bit unbinds
1086          children which will then bind to another CPU.
1087       */
1088 #include <sys/processor.h>
1089         int status = bindprocessor(BINDPROCESS, (int)getpid(),
1090                                PROCESSOR_CLASS_ANY);
1091         if (status != OK)
1092             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, server_conf,
1093                          "processor unbind failed %d", status);
1094 #endif
1095
1096         RAISE_SIGSTOP(MAKE_CHILD);
1097
1098         signal(SIGTERM, just_die);
1099         child_main(slot);
1100
1101         return 0;
1102     }
1103     /* else */
1104     ap_scoreboard_image->parent[slot].pid = pid;
1105     return 0;
1106 }
1107
1108 /* start up a bunch of children */
1109 static void startup_children(int number_to_start)
1110 {
1111     int i;
1112
1113     for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
1114         if (ap_scoreboard_image->parent[i].pid != 0) {
1115             continue;
1116         }
1117         if (make_child(server_conf, i, 0) < 0) {
1118             break;
1119         }
1120         --number_to_start;
1121     }
1122 }
1123
1124
1125 /*
1126  * idle_spawn_rate is the number of children that will be spawned on the
1127  * next maintenance cycle if there aren't enough idle servers.  It is
1128  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
1129  * without the need to spawn.
1130  */
1131 static int idle_spawn_rate = 1;
1132 #ifndef MAX_SPAWN_RATE
1133 #define MAX_SPAWN_RATE  (32)
1134 #endif
1135 static int hold_off_on_exponential_spawning;
1136
1137 static void perform_idle_server_maintenance(void)
1138 {
1139     int i, j;
1140     int idle_thread_count;
1141     thread_score *ss;
1142     time_t now = 0;
1143     int free_length;
1144     int free_slots[MAX_SPAWN_RATE];
1145     int last_non_dead;
1146     int total_non_dead;
1147
1148     /* initialize the free_list */
1149     free_length = 0;
1150
1151     idle_thread_count = 0;
1152     last_non_dead = -1;
1153     total_non_dead = 0;
1154
1155     ap_check_signals();
1156
1157     ap_sync_scoreboard_image();
1158     for (i = 0; i < ap_daemons_limit; ++i) {
1159         /* Initialization to satisfy the compiler. It doesn't know
1160          * that ap_threads_per_child is always > 0 */
1161         int status = SERVER_DEAD;
1162         int any_dying_threads = 0;
1163         int all_dead_threads = 1;
1164         int idle_thread_addition = 0;
1165
1166         if (i >= max_daemons_limit && free_length == idle_spawn_rate)
1167             break;
1168         for (j = 0; j < ap_threads_per_child; j++) {
1169             ss = &ap_scoreboard_image->servers[i][j];
1170             status = ss->status;
1171
1172             any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
1173                                     || (status == SERVER_GRACEFUL);
1174             all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
1175
1176             /* We consider a starting server as idle because we started it
1177              * at least a cycle ago, and if it still hasn't finished starting
1178              * then we're just going to swamp things worse by forking more.
1179              * So we hopefully won't need to fork more if we count it.
1180              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
1181              */
1182             if (status <= SERVER_READY) {
1183                 ++idle_thread_addition;
1184             }
1185         }
1186         if (all_dead_threads && free_length < idle_spawn_rate) {
1187             free_slots[free_length] = i;
1188             ++free_length;
1189         }
1190         if (!all_dead_threads) {
1191             last_non_dead = i;
1192         }
1193         if (!any_dying_threads) {
1194             ++total_non_dead;
1195             idle_thread_count += idle_thread_addition;
1196         }
1197     }
1198     max_daemons_limit = last_non_dead + 1;
1199
1200     if (idle_thread_count > max_spare_threads) {
1201         /* Kill off one child */
1202         char char_of_death = '!';
1203         if (write(pipe_of_death[1], &char_of_death, 1) == -1) {
1204             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "write pipe_of_death");
1205         }
1206         idle_spawn_rate = 1;
1207     }
1208     else if (idle_thread_count < min_spare_threads) {
1209         /* terminate the free list */
1210         if (free_length == 0) {
1211             /* only report this condition once */
1212             static int reported = 0;
1213             
1214             if (!reported) {
1215                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, server_conf,
1216                              "server reached MaxClients setting, consider"
1217                              " raising the MaxClients setting");
1218                 reported = 1;
1219             }
1220             idle_spawn_rate = 1;
1221         }
1222         else {
1223             
1224             if (idle_spawn_rate >= 8) {
1225                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, server_conf,
1226                              "server seems busy, (you may need "
1227                              "to increase StartServers, ThreadsPerChild "
1228                              "or Min/MaxSparetThreads), "
1229                              "spawning %d children, there are around %d idle "
1230                              "threads, and %d total children", idle_spawn_rate,
1231                              idle_thread_count, total_non_dead);
1232             }
1233             for (i = 0; i < free_length; ++i) {
1234                 make_child(server_conf, free_slots[i], now);
1235             }
1236             /* the next time around we want to spawn twice as many if this
1237              * wasn't good enough, but not if we've just done a graceful
1238              */
1239             if (hold_off_on_exponential_spawning) {
1240                 --hold_off_on_exponential_spawning;
1241             }
1242             else if (idle_spawn_rate < MAX_SPAWN_RATE) {
1243                 idle_spawn_rate *= 2;
1244             }
1245         }
1246     }
1247     else {
1248       idle_spawn_rate = 1;
1249     }
1250 }
1251
1252 static void server_main_loop(int remaining_children_to_start)
1253 {
1254     int child_slot;
1255     ap_wait_t status;
1256     int pid;
1257     int i;
1258
1259     while (!restart_pending && !shutdown_pending) {
1260         pid = wait_or_timeout(&status);
1261         
1262         if (pid >= 0) {
1263             process_child_status(pid, status);
1264             /* non-fatal death... note that it's gone in the scoreboard. */
1265             child_slot = find_child_by_pid(pid);
1266             if (child_slot >= 0) {
1267                 for (i = 0; i < ap_threads_per_child; i++)
1268                     ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
1269                 
1270                 if (remaining_children_to_start
1271                     && child_slot < ap_daemons_limit) {
1272                     /* we're still doing a 1-for-1 replacement of dead
1273                      * children with new children
1274                      */
1275                     make_child(server_conf, child_slot, time(NULL));
1276                     --remaining_children_to_start;
1277                 }
1278 #ifdef HAS_OTHER_CHILD
1279             }
1280             else if (reap_other_child(pid, status) == 0) {
1281                 /* handled */
1282 #endif
1283             }
1284             else if (is_graceful) {
1285                 /* Great, we've probably just lost a slot in the
1286                     * scoreboard.  Somehow we don't know about this
1287                     * child.
1288                     */
1289                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, server_conf,
1290                             "long lost child came home! (pid %d)", pid);
1291             }
1292             /* Don't perform idle maintenance when a child dies,
1293              * only do it when there's a timeout.  Remember only a
1294              * finite number of children can die, and it's pretty
1295              * pathological for a lot to die suddenly.
1296              */
1297             continue;
1298         }
1299         else if (remaining_children_to_start) {
1300             /* we hit a 1 second timeout in which none of the previous
1301              * generation of children needed to be reaped... so assume
1302              * they're all done, and pick up the slack if any is left.
1303              */
1304             startup_children(remaining_children_to_start);
1305             remaining_children_to_start = 0;
1306             /* In any event we really shouldn't do the code below because
1307              * few of the servers we just started are in the IDLE state
1308              * yet, so we'd mistakenly create an extra server.
1309              */
1310             continue;
1311         }
1312
1313         perform_idle_server_maintenance();
1314     }
1315 }
1316
1317 int ap_mpm_run(ap_context_t *_pconf, ap_context_t *plog, server_rec *s)
1318 {
1319     int remaining_children_to_start;
1320     ap_status_t rv;
1321
1322     pconf = _pconf;
1323     server_conf = s;
1324     if (pipe(pipe_of_death) == -1) {
1325         ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1326                      (const server_rec*) server_conf,
1327                      "pipe: (pipe_of_death)");
1328         exit(1);
1329     }
1330 /*  XXXXXX  Removed because these functions don't exist anymore.  When
1331     These pipes are changed to apr_types, these functions won't be needed
1332     anyway.
1333     ap_note_cleanups_for_fd(pconf, pipe_of_death[0]);
1334     ap_note_cleanups_for_fd(pconf, pipe_of_death[1]);
1335 */
1336
1337     if (fcntl(pipe_of_death[0], F_SETFD, O_NONBLOCK) == -1) {
1338         ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1339                      (const server_rec*) server_conf,
1340                      "fcntl: O_NONBLOCKing (pipe_of_death)");
1341         exit(1);
1342     }
1343     server_conf = s;
1344     if ((num_listensocks = setup_listeners(server_conf)) < 1) {
1345         /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1346         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1347             "no listening sockets available, shutting down");
1348         return 1;
1349     }
1350     ap_log_pid(pconf, ap_pid_fname);
1351
1352     /* Initialize cross-process accept lock */
1353     lock_fname = ap_psprintf(_pconf, "%s.%lu",
1354                              ap_server_root_relative(_pconf, lock_fname),
1355                              my_pid);
1356     rv = ap_create_lock(&process_accept_mutex, APR_MUTEX, APR_CROSS_PROCESS,
1357                    lock_fname, _pconf);
1358     if (rv != APR_SUCCESS) {
1359         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1360                      "Couldn't create cross-process lock");
1361         return 1;
1362     }
1363
1364
1365     if (!is_graceful) {
1366         reinit_scoreboard(pconf);
1367     }
1368
1369     set_signals();
1370     /* Don't thrash... */
1371     if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1372         max_spare_threads = min_spare_threads + ap_threads_per_child;
1373
1374     /* If we're doing a graceful_restart then we're going to see a lot
1375      * of children exiting immediately when we get into the main loop
1376      * below (because we just sent them SIGWINCH).  This happens pretty
1377      * rapidly... and for each one that exits we'll start a new one until
1378      * we reach at least daemons_min_free.  But we may be permitted to
1379      * start more than that, so we'll just keep track of how many we're
1380      * supposed to start up without the 1 second penalty between each fork.
1381      */
1382     remaining_children_to_start = ap_daemons_to_start;
1383     if (remaining_children_to_start > ap_daemons_limit) {
1384         remaining_children_to_start = ap_daemons_limit;
1385     }
1386     if (!is_graceful) {
1387         startup_children(remaining_children_to_start);
1388         remaining_children_to_start = 0;
1389     }
1390     else {
1391         /* give the system some time to recover before kicking into
1392             * exponential mode */
1393         hold_off_on_exponential_spawning = 10;
1394     }
1395
1396     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1397                 "%s configured -- resuming normal operations",
1398                 ap_get_server_version());
1399     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, server_conf,
1400                 "Server built: %s", ap_get_server_built());
1401     restart_pending = shutdown_pending = 0;
1402
1403     server_main_loop(remaining_children_to_start);
1404
1405     if (shutdown_pending) {
1406         /* Time to gracefully shut down:
1407          * Kill child processes, tell them to call child_exit, etc...
1408          */
1409         if (ap_killpg(getpgrp(), SIGTERM) < 0) {
1410             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "killpg SIGTERM");
1411         }
1412         reclaim_child_processes(1);             /* Start with SIGTERM */
1413     
1414         /* cleanup pid file on normal shutdown */
1415         {
1416             const char *pidfile = NULL;
1417             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1418             if ( pidfile != NULL && unlink(pidfile) == 0)
1419                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1420                          server_conf,
1421                          "removed PID file %s (pid=%ld)",
1422                          pidfile, (long)getpid());
1423         }
1424     
1425         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1426             "caught SIGTERM, shutting down");
1427     
1428         return 1;
1429     }
1430
1431     /* we've been told to restart */
1432     signal(SIGHUP, SIG_IGN);
1433
1434     if (one_process) {
1435         /* not worth thinking about */
1436         return 1;
1437     }
1438
1439     /* advance to the next generation */
1440     /* XXX: we really need to make sure this new generation number isn't in
1441      * use by any of the children.
1442      */
1443     ++ap_my_generation;
1444     ap_scoreboard_image->global.running_generation = ap_my_generation;
1445     update_scoreboard_global();
1446
1447     if (is_graceful) {
1448         int i, j;
1449         char char_of_death = '!';
1450
1451         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1452                     "SIGWINCH received.  Doing graceful restart");
1453
1454         /* give the children the signal to die */
1455         for (i = 0; i < ap_daemons_limit;) {
1456             if (write(pipe_of_death[1], &char_of_death, 1) == -1) {
1457                 if (errno == EINTR) continue;
1458                 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "write pipe_of_death");
1459             }
1460             i++;
1461         }
1462
1463         /* This is mostly for debugging... so that we know what is still
1464          * gracefully dealing with existing request.
1465          */
1466         
1467         for (i = 0; i < ap_daemons_limit; ++i) {
1468             for (j = 0; j < ap_threads_per_child; j++) { 
1469                 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1470                     ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1471                 }
1472             } 
1473         }
1474     }
1475     else {
1476       /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
1477        * and a SIGHUP, we may as well use the same signal, because some user
1478        * pthreads are stealing signals from us left and right.
1479        */
1480         if (ap_killpg(getpgrp(), SIGTERM) < 0) {
1481             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "killpg SIGTERM");
1482         }
1483         reclaim_child_processes(1);             /* Start with SIGTERM */
1484         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1485                     "SIGHUP received.  Attempting to restart");
1486     }
1487     if (!is_graceful) {
1488         ap_restart_time = time(NULL); 
1489     }
1490     return 0;
1491 }
1492
1493 static void mpmt_pthread_pre_config(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp)
1494 {
1495     static int restart_num = 0;
1496
1497     one_process = !!getenv("ONE_PROCESS");
1498
1499     /* sigh, want this only the second time around */
1500     if (restart_num++ == 1) {
1501         is_graceful = 0;
1502
1503         if (!one_process) {
1504             unixd_detach();
1505         }
1506
1507         my_pid = getpid();
1508     }
1509
1510     unixd_pre_config();
1511     ap_listen_pre_config();
1512     ap_daemons_to_start = DEFAULT_START_DAEMON;
1513     min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1514     max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1515     ap_daemons_limit = HARD_SERVER_LIMIT;
1516     ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1517     ap_pid_fname = DEFAULT_PIDLOG;
1518     ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1519     lock_fname = DEFAULT_LOCKFILE;
1520     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1521     ap_extended_status = 0;
1522
1523     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1524 }
1525
1526 static void mpmt_pthread_hooks(void)
1527 {
1528     ap_hook_pre_config(mpmt_pthread_pre_config,NULL,NULL,HOOK_MIDDLE);
1529     INIT_SIGLIST()
1530     one_process = 0;
1531 }
1532
1533
1534 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
1535 {
1536     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1537     if (err != NULL) {
1538         return err;
1539     }
1540
1541     if (cmd->server->is_virtual) {
1542         return "PidFile directive not allowed in <VirtualHost>";
1543     }
1544     ap_pid_fname = arg;
1545     return NULL;
1546 }
1547
1548 static const char *set_scoreboard(cmd_parms *cmd, void *dummy, char *arg) 
1549 {
1550     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1551     if (err != NULL) {
1552         return err;
1553     }
1554
1555     ap_scoreboard_fname = arg;
1556     return NULL;
1557 }
1558
1559 static const char *set_lockfile(cmd_parms *cmd, void *dummy, char *arg) 
1560 {
1561     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1562     if (err != NULL) {
1563         return err;
1564     }
1565
1566     lock_fname = arg;
1567     return NULL;
1568 }
1569
1570 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, char *arg) 
1571 {
1572     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1573     if (err != NULL) {
1574         return err;
1575     }
1576
1577     ap_daemons_to_start = atoi(arg);
1578     return NULL;
1579 }
1580
1581 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, char *arg)
1582 {
1583     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1584     if (err != NULL) {
1585         return err;
1586     }
1587
1588     min_spare_threads = atoi(arg);
1589     if (min_spare_threads <= 0) {
1590        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1591                     "WARNING: detected MinSpareThreads set to non-positive.");
1592        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1593                     "Resetting to 1 to avoid almost certain Apache failure.");
1594        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1595                     "Please read the documentation.");
1596        min_spare_threads = 1;
1597     }
1598        
1599     return NULL;
1600 }
1601
1602 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, char *arg)
1603 {
1604     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1605     if (err != NULL) {
1606         return err;
1607     }
1608
1609     max_spare_threads = atoi(arg);
1610     return NULL;
1611 }
1612
1613 static const char *set_server_limit (cmd_parms *cmd, void *dummy, char *arg) 
1614 {
1615     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1616     if (err != NULL) {
1617         return err;
1618     }
1619
1620     ap_daemons_limit = atoi(arg);
1621     if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1622        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1623                     "WARNING: MaxClients of %d exceeds compile time limit "
1624                     "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1625        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1626                     " lowering MaxClients to %d.  To increase, please "
1627                     "see the", HARD_SERVER_LIMIT);
1628        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1629                     " HARD_SERVER_LIMIT define in src/include/httpd.h.");
1630        ap_daemons_limit = HARD_SERVER_LIMIT;
1631     } 
1632     else if (ap_daemons_limit < 1) {
1633         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1\n");
1634         ap_daemons_limit = 1;
1635     }
1636     return NULL;
1637 }
1638
1639 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
1640 {
1641     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1642     if (err != NULL) {
1643         return err;
1644     }
1645
1646     ap_threads_per_child = atoi(arg);
1647     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1648         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1649                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1650                      "limit of %d threads,", ap_threads_per_child,
1651                      HARD_THREAD_LIMIT);
1652         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1653                      " lowering ThreadsPerChild to %d. To increase, please"
1654                      "see the", HARD_THREAD_LIMIT);
1655         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1656                      " HARD_THREAD_LIMIT define in src/include/httpd.h.");
1657     }
1658     else if (ap_threads_per_child < 1) {
1659         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1660                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1661         ap_threads_per_child = 1;
1662     }
1663     return NULL;
1664 }
1665
1666 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
1667 {
1668     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1669     if (err != NULL) {
1670         return err;
1671     }
1672
1673     ap_max_requests_per_child = atoi(arg);
1674
1675     return NULL;
1676 }
1677
1678 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
1679 {
1680     struct stat finfo;
1681     const char *fname;
1682     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1683     if (err != NULL) {
1684         return err;
1685     }
1686
1687     fname = ap_server_root_relative(cmd->pool, arg);
1688     if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1689         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1690                           " does not exist or is not a directory", NULL);
1691     }
1692     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1693     return NULL;
1694 }
1695
1696 static const command_rec mpmt_pthread_cmds[] = {
1697 UNIX_DAEMON_COMMANDS
1698 LISTEN_COMMANDS
1699 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1700     "A file for logging the server process ID"},
1701 { "ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF, TAKE1,
1702     "A file for Apache to maintain runtime process management information"},
1703 { "LockFile", set_lockfile, NULL, RSRC_CONF, TAKE1,
1704     "The lockfile used when Apache needs to lock the accept() call"},
1705 { "StartServers", set_daemons_to_start, NULL, RSRC_CONF, TAKE1,
1706   "Number of child processes launched at server startup" },
1707 { "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF, TAKE1,
1708   "Minimum number of idle children, to handle request spikes" },
1709 { "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF, TAKE1,
1710   "Maximum number of idle children" },
1711 { "MaxClients", set_server_limit, NULL, RSRC_CONF, TAKE1,
1712   "Maximum number of children alive at the same time" },
1713 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1714   "Number of threads each child creates" },
1715 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1716   "Maximum number of requests a particular child serves before dying." },
1717 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1718   "The location of the directory Apache changes to before dumping core" },
1719 { NULL }
1720 };
1721
1722 module MODULE_VAR_EXPORT mpm_mpmt_pthread_module = {
1723     STANDARD20_MODULE_STUFF,
1724     NULL,                       /* create per-directory config structure */
1725     NULL,                       /* merge per-directory config structures */
1726     NULL,                       /* create per-server config structure */
1727     NULL,                       /* merge per-server config structures */
1728     mpmt_pthread_cmds,          /* command ap_table_t */
1729     NULL,                       /* handlers */
1730     mpmt_pthread_hooks          /* register_hooks */
1731 };
1732