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