]> granicus.if.org Git - apache/blob - server/mpm/mpmt_pthread/mpmt_pthread.c
Change ap_context_t to ap_pool_t. This compiles, runs, and serves pages
[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 int wait_or_timeout(ap_wait_t *status)
275 {
276     struct timeval tv;
277     int ret;
278
279     ++wait_or_timeout_counter;
280     if (wait_or_timeout_counter == INTERVAL_OF_WRITABLE_PROBES) {
281         wait_or_timeout_counter = 0;
282 #ifdef HAS_OTHER_CHILD
283         probe_writable_fds();
284 #endif
285     }
286     ret = waitpid(-1, status, WNOHANG);
287     if (ret == -1 && errno == EINTR) {
288         return -1;
289     }
290     if (ret > 0) {
291         return ret;
292     }
293     tv.tv_sec = SCOREBOARD_MAINTENANCE_INTERVAL / 1000000;
294     tv.tv_usec = SCOREBOARD_MAINTENANCE_INTERVAL % 1000000;
295     ap_select(0, NULL, NULL, NULL, &tv);
296     return -1;
297 }
298
299 /* handle all varieties of core dumping signals */
300 static void sig_coredump(int sig)
301 {
302     chdir(ap_coredump_dir);
303     ap_signal(sig, SIG_DFL);
304     kill(my_pid, sig);
305     /* At this point we've got sig blocked, because we're still inside
306      * the signal handler.  When we leave the signal handler it will
307      * be unblocked, and we'll take the signal... and coredump or whatever
308      * is appropriate for this particular Unix.  In addition the parent
309      * will see the real signal we received -- whereas if we called
310      * abort() here, the parent would only see SIGABRT.
311      */
312 }
313
314 static void just_die(int sig)
315 {
316     clean_child_exit(0);
317 }
318
319 /*****************************************************************
320  * Connection structures and accounting...
321  */
322
323 /* volatile just in case */
324 static int volatile shutdown_pending;
325 static int volatile restart_pending;
326 static int volatile is_graceful;
327 ap_generation_t volatile ap_my_generation;
328
329 /*
330  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
331  * functions to initiate shutdown or restart without relying on signals. 
332  * Previously this was initiated in sig_term() and restart() signal handlers, 
333  * but we want to be able to start a shutdown/restart from other sources --
334  * e.g. on Win32, from the service manager. Now the service manager can
335  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
336  * these functions can also be called by the child processes, since global
337  * variables are no longer used to pass on the required action to the parent.
338  *
339  * These should only be called from the parent process itself, since the
340  * parent process will use the shutdown_pending and restart_pending variables
341  * to determine whether to shutdown or restart. The child process should
342  * call signal_parent() directly to tell the parent to die -- this will
343  * cause neither of those variable to be set, which the parent will
344  * assume means something serious is wrong (which it will be, for the
345  * child to force an exit) and so do an exit anyway.
346  */
347
348 void ap_start_shutdown(void)
349 {
350     if (shutdown_pending == 1) {
351         /* Um, is this _probably_ not an error, if the user has
352          * tried to do a shutdown twice quickly, so we won't
353          * worry about reporting it.
354          */
355         return;
356     }
357     shutdown_pending = 1;
358 }
359
360 /* do a graceful restart if graceful == 1 */
361 void ap_start_restart(int graceful)
362 {
363
364     if (restart_pending == 1) {
365         /* Probably not an error - don't bother reporting it */
366         return;
367     }
368     restart_pending = 1;
369     is_graceful = graceful;
370 }
371
372 static void sig_term(int sig)
373 {
374     ap_start_shutdown();
375 }
376
377 static void restart(int sig)
378 {
379 #ifndef WIN32
380     ap_start_restart(sig == SIGWINCH);
381 #else
382     ap_start_restart(1);
383 #endif
384 }
385
386 static void set_signals(void)
387 {
388 #ifndef NO_USE_SIGACTION
389     struct sigaction sa;
390
391     sigemptyset(&sa.sa_mask);
392     sa.sa_flags = 0;
393
394     if (!one_process) {
395         sa.sa_handler = sig_coredump;
396 #if defined(SA_ONESHOT)
397         sa.sa_flags = SA_ONESHOT;
398 #elif defined(SA_RESETHAND)
399         sa.sa_flags = SA_RESETHAND;
400 #endif
401         if (sigaction(SIGSEGV, &sa, NULL) < 0)
402             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGSEGV)");
403 #ifdef SIGBUS
404         if (sigaction(SIGBUS, &sa, NULL) < 0)
405             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGBUS)");
406 #endif
407 #ifdef SIGABORT
408         if (sigaction(SIGABORT, &sa, NULL) < 0)
409             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGABORT)");
410 #endif
411 #ifdef SIGABRT
412         if (sigaction(SIGABRT, &sa, NULL) < 0)
413             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGABRT)");
414 #endif
415 #ifdef SIGILL
416         if (sigaction(SIGILL, &sa, NULL) < 0)
417             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGILL)");
418 #endif
419         sa.sa_flags = 0;
420     }
421     sa.sa_handler = sig_term;
422     if (sigaction(SIGTERM, &sa, NULL) < 0)
423         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGTERM)");
424 #ifdef SIGINT
425     if (sigaction(SIGINT, &sa, NULL) < 0)
426         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGINT)");
427 #endif
428 #ifdef SIGXCPU
429     sa.sa_handler = SIG_DFL;
430     if (sigaction(SIGXCPU, &sa, NULL) < 0)
431         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGXCPU)");
432 #endif
433 #ifdef SIGXFSZ
434     sa.sa_handler = SIG_DFL;
435     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
436         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGXFSZ)");
437 #endif
438 #ifdef SIGPIPE
439     sa.sa_handler = SIG_IGN;
440     if (sigaction(SIGPIPE, &sa, NULL) < 0)
441         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGPIPE)");
442 #endif
443
444     /* we want to ignore HUPs and WINCH while we're busy processing one */
445     sigaddset(&sa.sa_mask, SIGHUP);
446     sigaddset(&sa.sa_mask, SIGWINCH);
447     sa.sa_handler = restart;
448     if (sigaction(SIGHUP, &sa, NULL) < 0)
449         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGHUP)");
450     if (sigaction(SIGWINCH, &sa, NULL) < 0)
451         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "sigaction(SIGWINCH)");
452 #else
453     if (!one_process) {
454         ap_signal(SIGSEGV, sig_coredump);
455 #ifdef SIGBUS
456         ap_signal(SIGBUS, sig_coredump);
457 #endif /* SIGBUS */
458 #ifdef SIGABORT
459         ap_signal(SIGABORT, sig_coredump);
460 #endif /* SIGABORT */
461 #ifdef SIGABRT
462         ap_signal(SIGABRT, sig_coredump);
463 #endif /* SIGABRT */
464 #ifdef SIGILL
465         ap_signal(SIGILL, sig_coredump);
466 #endif /* SIGILL */
467 #ifdef SIGXCPU
468         ap_signal(SIGXCPU, SIG_DFL);
469 #endif /* SIGXCPU */
470 #ifdef SIGXFSZ
471         ap_signal(SIGXFSZ, SIG_DFL);
472 #endif /* SIGXFSZ */
473     }
474
475     ap_signal(SIGTERM, sig_term);
476 #ifdef SIGHUP
477     ap_signal(SIGHUP, restart);
478 #endif /* SIGHUP */
479 #ifdef SIGWINCH
480     ap_signal(SIGWINCH, restart);
481 #endif /* SIGWINCH */
482 #ifdef SIGPIPE
483     ap_signal(SIGPIPE, SIG_IGN);
484 #endif /* SIGPIPE */
485
486 #endif
487 }
488
489 static void process_child_status(int pid, ap_wait_t status)
490 {
491     /* Child died... if it died due to a fatal error,
492         * we should simply bail out.
493         */
494     if ((WIFEXITED(status)) &&
495         WEXITSTATUS(status) == APEXIT_CHILDFATAL) {
496         ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO, 0, server_conf,
497                         "Child %d returned a Fatal error... \n"
498                         "Apache is exiting!",
499                         pid);
500         exit(APEXIT_CHILDFATAL);
501     }
502     if (WIFSIGNALED(status)) {
503         switch (WTERMSIG(status)) {
504         case SIGTERM:
505         case SIGHUP:
506         case SIGUSR1:
507         case SIGKILL:
508             break;
509         default:
510 #ifdef SYS_SIGLIST
511 #ifdef WCOREDUMP
512             if (WCOREDUMP(status)) {
513                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
514                              0, server_conf,
515                              "child pid %d exit signal %s (%d), "
516                              "possible coredump in %s",
517                              pid, (WTERMSIG(status) >= NumSIG) ? "" : 
518                              SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status),
519                              ap_coredump_dir);
520             }
521             else {
522 #endif
523                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
524                              0, server_conf,
525                              "child pid %d exit signal %s (%d)", pid,
526                              SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status));
527 #ifdef WCOREDUMP
528             }
529 #endif
530 #else
531             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
532                          server_conf,
533                          "child pid %d exit signal %d",
534                          pid, WTERMSIG(status));
535 #endif
536         }
537     }
538 }
539
540 static int setup_listeners(server_rec *s)
541 {
542     ap_listen_rec *lr;
543     int num_listeners = 0;
544     if (ap_listen_open(s->process, s->port)) {
545        return 0;
546     }
547     for (lr = ap_listeners; lr; lr = lr->next) {
548         num_listeners++;
549     }
550     return num_listeners;
551 }
552
553 /*****************************************************************
554  * Here follows a long bunch of generic server bookkeeping stuff...
555  */
556
557 #if defined(TCP_NODELAY) && !defined(MPE) && !defined(TPF)
558 static void sock_disable_nagle(int s) 
559 {
560     /* The Nagle algorithm says that we should delay sending partial
561      * packets in hopes of getting more data.  We don't want to do
562      * this; we are not telnet.  There are bad interactions between
563      * persistent connections and Nagle's algorithm that have very severe
564      * performance penalties.  (Failing to disable Nagle is not much of a
565      * problem with simple HTTP.)
566      *
567      * In spite of these problems, failure here is not a shooting offense.
568      */
569     int just_say_no = 1;
570
571     if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
572                    sizeof(int)) < 0) {
573         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf,
574                     "setsockopt: (TCP_NODELAY)");
575     }
576 }
577
578 #else
579 #define sock_disable_nagle(s)   /* NOOP */
580 #endif
581
582 int ap_graceful_stop_signalled(void)
583 {
584     /* XXX - Does this really work? - Manoj */
585     return is_graceful;
586 }
587
588 /*****************************************************************
589  * Child process main loop.
590  */
591
592 static void process_socket(ap_pool_t *p, ap_socket_t *sock, int my_child_num, int my_thread_num)
593 {
594     BUFF *conn_io;
595     conn_rec *current_conn;
596     ap_iol *iol;
597     long conn_id = my_child_num * HARD_THREAD_LIMIT + my_thread_num;
598     int csd;
599
600     (void) ap_get_os_sock(&csd, sock);
601
602     sock_disable_nagle(csd);
603
604     iol = unix_attach_socket(sock);
605     if (iol == NULL) {
606         if (errno == EBADF) {
607             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
608                 "filedescriptor (%u) larger than FD_SETSIZE (%u) "
609                 "found, you probably need to rebuild Apache with a "
610                 "larger FD_SETSIZE", csd, FD_SETSIZE);
611         }
612         else {
613             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, NULL,
614                 "error attaching to socket");
615         }
616         ap_close_socket(sock);
617         return;
618     }
619
620     (void) ap_update_child_status(my_child_num, my_thread_num,  
621                                   SERVER_BUSY_READ, (request_rec *) NULL);
622     conn_io = ap_bcreate(p, B_RDWR);
623     ap_bpush_iol(conn_io, iol);
624
625     current_conn = ap_new_apr_connection(p, server_conf, conn_io, sock,
626                                          conn_id);
627
628     ap_process_connection(current_conn);
629 }
630 /* Sets workers_may_exit if we received a character on the pipe_of_death */
631 static void check_pipe_of_death(void)
632 {
633     pthread_mutex_lock(&pipe_of_death_mutex);
634     if (!workers_may_exit) {
635         ap_status_t ret;
636         char pipe_read_char;
637         int n=1;
638
639         ret = ap_recv(listensocks[0], &pipe_read_char, &n);
640         if (ret == APR_EAGAIN) {
641             /* It lost the lottery. It must continue to suffer
642              * through a life of servitude. */
643         }
644         else {
645             /* It won the lottery (or something else is very
646              * wrong). Embrace death with open arms. */
647             workers_may_exit = 1;
648         }
649     }
650     pthread_mutex_unlock(&pipe_of_death_mutex);
651 }
652
653 static void * worker_thread(void * dummy)
654 {
655     proc_info * ti = dummy;
656     int process_slot = ti->pid;
657     int thread_slot = ti->tid;
658     ap_pool_t *tpool = ti->tpool;
659     ap_socket_t *csd = NULL;
660     ap_pool_t *ptrans;          /* Pool for per-transaction stuff */
661     ap_socket_t *sd = NULL;
662     int n;
663     int curr_pollfd, last_pollfd = 0;
664     ap_pollfd_t *pollset;
665     ap_status_t rv;
666
667     free(ti);
668
669     ap_create_pool(&ptrans, tpool);
670
671     pthread_mutex_lock(&worker_thread_count_mutex);
672     worker_thread_count++;
673     pthread_mutex_unlock(&worker_thread_count_mutex);
674
675     ap_setup_poll(&pollset, num_listensocks+1, tpool);
676     for(n=0 ; n <= num_listensocks ; ++n)
677         ap_add_poll_socket(pollset, listensocks[n], APR_POLLIN);
678
679     /* TODO: Switch to a system where threads reuse the results from earlier
680        poll calls - manoj */
681     while (!workers_may_exit) {
682         workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
683         if (workers_may_exit) break;
684
685         (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY, 
686                                       (request_rec *) NULL);
687         pthread_mutex_lock(&thread_accept_mutex);
688         if (workers_may_exit) {
689             pthread_mutex_unlock(&thread_accept_mutex);
690             break;
691         }
692         if ((rv = SAFE_ACCEPT(ap_lock(process_accept_mutex)))
693             != APR_SUCCESS) {
694             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
695                          "ap_lock failed. Attempting to shutdown "
696                          "process gracefully.");
697             workers_may_exit = 1;
698         }
699
700         while (!workers_may_exit) {
701             ap_status_t ret;
702             ap_int16_t event;
703
704             ret = ap_poll(pollset, &n, -1);
705             if (ret != APR_SUCCESS) {
706                 if (ret == APR_EINTR) {
707                     continue;
708                 }
709
710                 /* poll() will only return errors in catastrophic
711                  * circumstances. Let's try exiting gracefully, for now. */
712                 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (const server_rec *)
713                              ap_get_server_conf(), "poll: (listen)");
714                 workers_may_exit = 1;
715             }
716
717             if (workers_may_exit) break;
718
719             ap_get_revents(&event, listensocks[0], pollset);
720             if (event & APR_POLLIN) {
721                 /* A process got a signal on the shutdown pipe. Check if we're
722                  * the lucky process to die. */
723                 check_pipe_of_death();
724                 continue;
725             }
726
727             if (num_listensocks == 1) {
728                 sd = ap_listeners->sd;
729                 goto got_fd;
730             }
731             else {
732                 /* find a listener */
733                 curr_pollfd = last_pollfd;
734                 do {
735                     curr_pollfd++;
736                     if (curr_pollfd > num_listensocks) {
737                         curr_pollfd = 1;
738                     }
739                     /* XXX: Should we check for POLLERR? */
740                     ap_get_revents(&event, listensocks[curr_pollfd], pollset);
741                     if (event & APR_POLLIN) {
742                         last_pollfd = curr_pollfd;
743                         sd=listensocks[curr_pollfd];
744                         goto got_fd;
745                     }
746                 } while (curr_pollfd != last_pollfd);
747             }
748         }
749     got_fd:
750         if (!workers_may_exit) {
751             ap_accept(&csd, sd, ptrans);
752             if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
753                 != APR_SUCCESS) {
754                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
755                              "ap_unlock failed. Attempting to shutdown "
756                              "process gracefully.");
757                 workers_may_exit = 1;
758             }
759             pthread_mutex_unlock(&thread_accept_mutex);
760             process_socket(ptrans, csd, process_slot, thread_slot);
761             requests_this_child--;
762         }
763         else {
764             if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
765                 != APR_SUCCESS) {
766                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
767                              "ap_unlock failed. Attempting to shutdown "
768                              "process gracefully.");
769                 workers_may_exit = 1;
770             }
771             pthread_mutex_unlock(&thread_accept_mutex);
772             break;
773         }
774         ap_clear_pool(ptrans);
775     }
776
777     ap_destroy_pool(tpool);
778     ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
779         (request_rec *) NULL);
780     pthread_mutex_lock(&worker_thread_count_mutex);
781     worker_thread_count--;
782     if (worker_thread_count == 0) {
783         /* All the threads have exited, now finish the shutdown process
784          * by signalling the sigwait thread */
785         kill(my_pid, SIGTERM);
786     }
787     pthread_mutex_unlock(&worker_thread_count_mutex);
788
789     return NULL;
790 }
791
792
793 static void child_main(int child_num_arg)
794 {
795     sigset_t sig_mask;
796     int signal_received;
797     pthread_t thread;
798     pthread_attr_t thread_attr;
799     int i;
800     int my_child_num = child_num_arg;
801     proc_info *my_info = NULL;
802     ap_listen_rec *lr;
803     ap_status_t rv;
804
805
806     my_pid = getpid();
807     ap_create_pool(&pchild, pconf);
808
809     /*stuff to do before we switch id's, so we have permissions.*/
810     reopen_scoreboard(pchild);
811
812     rv = SAFE_ACCEPT(ap_child_init_lock(&process_accept_mutex, lock_fname,
813                      pchild));
814     if (rv != APR_SUCCESS) {
815         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, server_conf,
816                      "Couldn't initialize cross-process lock in child");
817         clean_child_exit(APEXIT_CHILDFATAL);
818     }
819
820     if (unixd_setup_child()) {
821         clean_child_exit(APEXIT_CHILDFATAL);
822     }
823
824     ap_child_init_hook(pchild, server_conf);
825
826     /*done with init critical section */
827
828     /* All threads should mask signals out, accoring to sigwait(2) man page */
829     sigfillset(&sig_mask);
830
831     if (pthread_sigmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
832         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf, "pthread_sigmask");
833     }
834
835     requests_this_child = ap_max_requests_per_child;
836     
837     /* Set up the pollfd array */
838     listensocks = ap_palloc(pchild,
839                             sizeof(*listensocks) * (num_listensocks + 1));
840     ap_create_tcp_socket(&listensocks[0], pchild);
841     ap_put_os_sock(&listensocks[0], &pipe_of_death[0], pchild);
842     for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
843         listensocks[i]=lr->sd;
844
845     /* Setup worker threads */
846
847     worker_thread_count = 0;
848     pthread_mutex_init(&worker_thread_count_mutex, NULL);
849     pthread_mutex_init(&pipe_of_death_mutex, NULL);
850     pthread_attr_init(&thread_attr);
851     pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
852     for (i=0; i < ap_threads_per_child; i++) {
853
854         my_info = (proc_info *)malloc(sizeof(proc_info));
855         if (my_info == NULL) {
856             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf,
857                          "malloc: out of memory");
858             clean_child_exit(APEXIT_CHILDFATAL);
859         }
860         my_info->pid = my_child_num;
861         my_info->tid = i;
862         my_info->sd = 0;
863         ap_create_pool(&my_info->tpool, pchild);
864         
865         /* We are creating threads right now */
866         (void) ap_update_child_status(my_child_num, i, SERVER_STARTING, 
867                                       (request_rec *) NULL);
868 #ifndef NO_THREADS
869         if (pthread_create(&thread, &thread_attr, worker_thread, my_info)) {
870             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf,
871                          "pthread_create: unable to create worker thread");
872             /* In case system resources are maxxed out, we don't want
873                Apache running away with the CPU trying to fork over and
874                over and over again if we exit. */
875             sleep(10);
876             clean_child_exit(APEXIT_CHILDFATAL);
877         }
878 #else
879         worker_thread(my_info);
880         /* The SIGTERM shouldn't let us reach this point, but just in case... */
881         clean_child_exit(APEXIT_OK);
882 #endif
883
884         /* We let each thread update it's own scoreboard entry.  This is done
885          * because it let's us deal with tid better.
886          */
887     }
888
889     pthread_attr_destroy(&thread_attr);
890
891     /* This thread will be the one responsible for handling signals */
892     sigemptyset(&sig_mask);
893     sigaddset(&sig_mask, SIGTERM);
894     sigaddset(&sig_mask, SIGINT);
895     sigwait(&sig_mask, &signal_received);
896     switch (signal_received) {
897         case SIGTERM:
898         case SIGINT:
899             just_die(signal_received);
900             break;
901         default:
902             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, server_conf,
903             "received impossible signal: %d", signal_received);
904             just_die(SIGTERM);
905     }
906 }
907
908 static int make_child(server_rec *s, int slot, time_t now) 
909 {
910     int pid;
911
912     if (slot + 1 > max_daemons_limit) {
913         max_daemons_limit = slot + 1;
914     }
915
916     if (one_process) {
917         set_signals();
918         ap_scoreboard_image->parent[slot].pid = getpid();
919         child_main(slot);
920     }
921
922     /* Tag this slot as occupied so that perform_idle_server_maintenance
923      * doesn't try to steal it */
924     (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
925
926     if ((pid = fork()) == -1) {
927         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
928
929         /* fork didn't succeed. Fix the scoreboard or else
930          * it will say SERVER_STARTING forever and ever
931          */
932         (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
933
934         /* In case system resources are maxxed out, we don't want
935            Apache running away with the CPU trying to fork over and
936            over and over again. */
937         sleep(10);
938
939         return -1;
940     }
941
942     if (!pid) {
943 #ifdef AIX_BIND_PROCESSOR
944       /* By default, AIX binds to a single processor.  This bit unbinds
945          children which will then bind to another CPU.
946       */
947 #include <sys/processor.h>
948         int status = bindprocessor(BINDPROCESS, (int)getpid(),
949                                PROCESSOR_CLASS_ANY);
950         if (status != OK)
951             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, server_conf,
952                          "processor unbind failed %d", status);
953 #endif
954
955         RAISE_SIGSTOP(MAKE_CHILD);
956
957         ap_signal(SIGTERM, just_die);
958         child_main(slot);
959
960         return 0;
961     }
962     /* else */
963     ap_scoreboard_image->parent[slot].pid = pid;
964     return 0;
965 }
966
967 /* start up a bunch of children */
968 static void startup_children(int number_to_start)
969 {
970     int i;
971
972     for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
973         if (ap_scoreboard_image->parent[i].pid != 0) {
974             continue;
975         }
976         if (make_child(server_conf, i, 0) < 0) {
977             break;
978         }
979         --number_to_start;
980     }
981 }
982
983
984 /*
985  * idle_spawn_rate is the number of children that will be spawned on the
986  * next maintenance cycle if there aren't enough idle servers.  It is
987  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
988  * without the need to spawn.
989  */
990 static int idle_spawn_rate = 1;
991 #ifndef MAX_SPAWN_RATE
992 #define MAX_SPAWN_RATE  (32)
993 #endif
994 static int hold_off_on_exponential_spawning;
995
996 static void perform_idle_server_maintenance(void)
997 {
998     int i, j;
999     int idle_thread_count;
1000     thread_score *ss;
1001     time_t now = 0;
1002     int free_length;
1003     int free_slots[MAX_SPAWN_RATE];
1004     int last_non_dead;
1005     int total_non_dead;
1006
1007     /* initialize the free_list */
1008     free_length = 0;
1009
1010     idle_thread_count = 0;
1011     last_non_dead = -1;
1012     total_non_dead = 0;
1013
1014     ap_sync_scoreboard_image();
1015     for (i = 0; i < ap_daemons_limit; ++i) {
1016         /* Initialization to satisfy the compiler. It doesn't know
1017          * that ap_threads_per_child is always > 0 */
1018         int status = SERVER_DEAD;
1019         int any_dying_threads = 0;
1020         int all_dead_threads = 1;
1021         int idle_thread_addition = 0;
1022
1023         if (i >= max_daemons_limit && free_length == idle_spawn_rate)
1024             break;
1025         for (j = 0; j < ap_threads_per_child; j++) {
1026             ss = &ap_scoreboard_image->servers[i][j];
1027             status = ss->status;
1028
1029             any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
1030                                     || (status == SERVER_GRACEFUL);
1031             all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
1032
1033             /* We consider a starting server as idle because we started it
1034              * at least a cycle ago, and if it still hasn't finished starting
1035              * then we're just going to swamp things worse by forking more.
1036              * So we hopefully won't need to fork more if we count it.
1037              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
1038              */
1039             if (status <= SERVER_READY) {
1040                 ++idle_thread_addition;
1041             }
1042         }
1043         if (all_dead_threads && free_length < idle_spawn_rate) {
1044             free_slots[free_length] = i;
1045             ++free_length;
1046         }
1047         if (!all_dead_threads) {
1048             last_non_dead = i;
1049         }
1050         if (!any_dying_threads) {
1051             ++total_non_dead;
1052             idle_thread_count += idle_thread_addition;
1053         }
1054     }
1055     max_daemons_limit = last_non_dead + 1;
1056
1057     if (idle_thread_count > max_spare_threads) {
1058         /* Kill off one child */
1059         char char_of_death = '!';
1060         if (write(pipe_of_death[1], &char_of_death, 1) == -1) {
1061             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "write pipe_of_death");
1062         }
1063         idle_spawn_rate = 1;
1064     }
1065     else if (idle_thread_count < min_spare_threads) {
1066         /* terminate the free list */
1067         if (free_length == 0) {
1068             /* only report this condition once */
1069             static int reported = 0;
1070             
1071             if (!reported) {
1072                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, server_conf,
1073                              "server reached MaxClients setting, consider"
1074                              " raising the MaxClients setting");
1075                 reported = 1;
1076             }
1077             idle_spawn_rate = 1;
1078         }
1079         else {
1080             
1081             if (idle_spawn_rate >= 8) {
1082                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, server_conf,
1083                              "server seems busy, (you may need "
1084                              "to increase StartServers, ThreadsPerChild "
1085                              "or Min/MaxSparetThreads), "
1086                              "spawning %d children, there are around %d idle "
1087                              "threads, and %d total children", idle_spawn_rate,
1088                              idle_thread_count, total_non_dead);
1089             }
1090             for (i = 0; i < free_length; ++i) {
1091                 make_child(server_conf, free_slots[i], now);
1092             }
1093             /* the next time around we want to spawn twice as many if this
1094              * wasn't good enough, but not if we've just done a graceful
1095              */
1096             if (hold_off_on_exponential_spawning) {
1097                 --hold_off_on_exponential_spawning;
1098             }
1099             else if (idle_spawn_rate < MAX_SPAWN_RATE) {
1100                 idle_spawn_rate *= 2;
1101             }
1102         }
1103     }
1104     else {
1105       idle_spawn_rate = 1;
1106     }
1107 }
1108
1109 static void server_main_loop(int remaining_children_to_start)
1110 {
1111     int child_slot;
1112     ap_wait_t status;
1113     int pid;
1114     int i;
1115
1116     while (!restart_pending && !shutdown_pending) {
1117         pid = wait_or_timeout(&status);
1118         
1119         if (pid >= 0) {
1120             process_child_status(pid, status);
1121             /* non-fatal death... note that it's gone in the scoreboard. */
1122             child_slot = find_child_by_pid(pid);
1123             if (child_slot >= 0) {
1124                 ap_mpmt_pthread_force_reset_connection_status(child_slot);
1125                 for (i = 0; i < ap_threads_per_child; i++)
1126                     ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
1127                 
1128                 if (remaining_children_to_start
1129                     && child_slot < ap_daemons_limit) {
1130                     /* we're still doing a 1-for-1 replacement of dead
1131                      * children with new children
1132                      */
1133                     make_child(server_conf, child_slot, time(NULL));
1134                     --remaining_children_to_start;
1135                 }
1136 #ifdef HAS_OTHER_CHILD
1137             }
1138             else if (reap_other_child(pid, status) == 0) {
1139                 /* handled */
1140 #endif
1141             }
1142             else if (is_graceful) {
1143                 /* Great, we've probably just lost a slot in the
1144                     * scoreboard.  Somehow we don't know about this
1145                     * child.
1146                     */
1147                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, server_conf,
1148                             "long lost child came home! (pid %d)", pid);
1149             }
1150             /* Don't perform idle maintenance when a child dies,
1151              * only do it when there's a timeout.  Remember only a
1152              * finite number of children can die, and it's pretty
1153              * pathological for a lot to die suddenly.
1154              */
1155             continue;
1156         }
1157         else if (remaining_children_to_start) {
1158             /* we hit a 1 second timeout in which none of the previous
1159              * generation of children needed to be reaped... so assume
1160              * they're all done, and pick up the slack if any is left.
1161              */
1162             startup_children(remaining_children_to_start);
1163             remaining_children_to_start = 0;
1164             /* In any event we really shouldn't do the code below because
1165              * few of the servers we just started are in the IDLE state
1166              * yet, so we'd mistakenly create an extra server.
1167              */
1168             continue;
1169         }
1170
1171         perform_idle_server_maintenance();
1172     }
1173 }
1174
1175 int ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s)
1176 {
1177     int remaining_children_to_start;
1178     ap_status_t rv;
1179
1180     pconf = _pconf;
1181     server_conf = s;
1182     if (pipe(pipe_of_death) == -1) {
1183         ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1184                      (const server_rec*) server_conf,
1185                      "pipe: (pipe_of_death)");
1186         exit(1);
1187     }
1188
1189     if (fcntl(pipe_of_death[0], F_SETFD, O_NONBLOCK) == -1) {
1190         ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1191                      (const server_rec*) server_conf,
1192                      "fcntl: O_NONBLOCKing (pipe_of_death)");
1193         exit(1);
1194     }
1195     server_conf = s;
1196     if ((num_listensocks = setup_listeners(server_conf)) < 1) {
1197         /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1198         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1199             "no listening sockets available, shutting down");
1200         return 1;
1201     }
1202     ap_log_pid(pconf, ap_pid_fname);
1203
1204     /* Initialize cross-process accept lock */
1205     lock_fname = ap_psprintf(_pconf, "%s.%lu",
1206                              ap_server_root_relative(_pconf, lock_fname),
1207                              my_pid);
1208     rv = ap_create_lock(&process_accept_mutex, APR_MUTEX, APR_CROSS_PROCESS,
1209                    lock_fname, _pconf);
1210     if (rv != APR_SUCCESS) {
1211         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1212                      "Couldn't create cross-process lock");
1213         return 1;
1214     }
1215
1216
1217     if (!is_graceful) {
1218         reinit_scoreboard(pconf);
1219     }
1220
1221     set_signals();
1222     /* Don't thrash... */
1223     if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1224         max_spare_threads = min_spare_threads + ap_threads_per_child;
1225
1226     /* If we're doing a graceful_restart then we're going to see a lot
1227      * of children exiting immediately when we get into the main loop
1228      * below (because we just sent them SIGWINCH).  This happens pretty
1229      * rapidly... and for each one that exits we'll start a new one until
1230      * we reach at least daemons_min_free.  But we may be permitted to
1231      * start more than that, so we'll just keep track of how many we're
1232      * supposed to start up without the 1 second penalty between each fork.
1233      */
1234     remaining_children_to_start = ap_daemons_to_start;
1235     if (remaining_children_to_start > ap_daemons_limit) {
1236         remaining_children_to_start = ap_daemons_limit;
1237     }
1238     if (!is_graceful) {
1239         startup_children(remaining_children_to_start);
1240         remaining_children_to_start = 0;
1241     }
1242     else {
1243         /* give the system some time to recover before kicking into
1244             * exponential mode */
1245         hold_off_on_exponential_spawning = 10;
1246     }
1247
1248     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1249                 "%s configured -- resuming normal operations",
1250                 ap_get_server_version());
1251     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, server_conf,
1252                 "Server built: %s", ap_get_server_built());
1253     restart_pending = shutdown_pending = 0;
1254
1255     server_main_loop(remaining_children_to_start);
1256
1257     if (shutdown_pending) {
1258         /* Time to gracefully shut down:
1259          * Kill child processes, tell them to call child_exit, etc...
1260          */
1261         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1262             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "killpg SIGTERM");
1263         }
1264         reclaim_child_processes(1);             /* Start with SIGTERM */
1265     
1266         /* cleanup pid file on normal shutdown */
1267         {
1268             const char *pidfile = NULL;
1269             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1270             if ( pidfile != NULL && unlink(pidfile) == 0)
1271                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1272                          server_conf,
1273                          "removed PID file %s (pid=%ld)",
1274                          pidfile, (long)getpid());
1275         }
1276     
1277         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1278             "caught SIGTERM, shutting down");
1279     
1280         return 1;
1281     }
1282
1283     /* we've been told to restart */
1284     ap_signal(SIGHUP, SIG_IGN);
1285
1286     if (one_process) {
1287         /* not worth thinking about */
1288         return 1;
1289     }
1290
1291     /* advance to the next generation */
1292     /* XXX: we really need to make sure this new generation number isn't in
1293      * use by any of the children.
1294      */
1295     ++ap_my_generation;
1296     ap_scoreboard_image->global.running_generation = ap_my_generation;
1297     update_scoreboard_global();
1298
1299     if (is_graceful) {
1300         int i, j;
1301         char char_of_death = '!';
1302
1303         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1304                     "SIGWINCH received.  Doing graceful restart");
1305
1306         /* give the children the signal to die */
1307         for (i = 0; i < ap_daemons_limit;) {
1308             if (write(pipe_of_death[1], &char_of_death, 1) == -1) {
1309                 if (errno == EINTR) continue;
1310                 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "write pipe_of_death");
1311             }
1312             i++;
1313         }
1314
1315         /* This is mostly for debugging... so that we know what is still
1316          * gracefully dealing with existing request.
1317          */
1318         
1319         for (i = 0; i < ap_daemons_limit; ++i) {
1320             for (j = 0; j < ap_threads_per_child; j++) { 
1321                 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1322                     ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1323                 }
1324             } 
1325         }
1326     }
1327     else {
1328       /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
1329        * and a SIGHUP, we may as well use the same signal, because some user
1330        * pthreads are stealing signals from us left and right.
1331        */
1332         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1333             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, server_conf, "killpg SIGTERM");
1334         }
1335         reclaim_child_processes(1);             /* Start with SIGTERM */
1336         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, server_conf,
1337                     "SIGHUP received.  Attempting to restart");
1338     }
1339     if (!is_graceful) {
1340         ap_restart_time = time(NULL); 
1341     }
1342     return 0;
1343 }
1344
1345 static void mpmt_pthread_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1346 {
1347     static int restart_num = 0;
1348
1349     one_process = !!getenv("ONE_PROCESS");
1350
1351     /* sigh, want this only the second time around */
1352     if (restart_num++ == 1) {
1353         is_graceful = 0;
1354
1355         if (!one_process) {
1356             unixd_detach();
1357         }
1358         my_pid = getpid();
1359     }
1360
1361     unixd_pre_config();
1362     ap_listen_pre_config();
1363     ap_daemons_to_start = DEFAULT_START_DAEMON;
1364     min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1365     max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1366     ap_daemons_limit = HARD_SERVER_LIMIT;
1367     ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1368     ap_pid_fname = DEFAULT_PIDLOG;
1369     ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1370     lock_fname = DEFAULT_LOCKFILE;
1371     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1372     ap_extended_status = 0;
1373
1374     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1375 }
1376
1377 static void mpmt_pthread_hooks(void)
1378 {
1379     INIT_SIGLIST()
1380     one_process = 0;
1381 }
1382
1383
1384 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg) 
1385 {
1386     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1387     if (err != NULL) {
1388         return err;
1389     }
1390
1391     if (cmd->server->is_virtual) {
1392         return "PidFile directive not allowed in <VirtualHost>";
1393     }
1394     ap_pid_fname = arg;
1395     return NULL;
1396 }
1397
1398 static const char *set_scoreboard(cmd_parms *cmd, void *dummy, char *arg) 
1399 {
1400     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1401     if (err != NULL) {
1402         return err;
1403     }
1404
1405     ap_scoreboard_fname = arg;
1406     return NULL;
1407 }
1408
1409 static const char *set_lockfile(cmd_parms *cmd, void *dummy, char *arg) 
1410 {
1411     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1412     if (err != NULL) {
1413         return err;
1414     }
1415
1416     lock_fname = arg;
1417     return NULL;
1418 }
1419
1420 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, char *arg) 
1421 {
1422     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1423     if (err != NULL) {
1424         return err;
1425     }
1426
1427     ap_daemons_to_start = atoi(arg);
1428     return NULL;
1429 }
1430
1431 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, char *arg)
1432 {
1433     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1434     if (err != NULL) {
1435         return err;
1436     }
1437
1438     min_spare_threads = atoi(arg);
1439     if (min_spare_threads <= 0) {
1440        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1441                     "WARNING: detected MinSpareThreads set to non-positive.");
1442        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1443                     "Resetting to 1 to avoid almost certain Apache failure.");
1444        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1445                     "Please read the documentation.");
1446        min_spare_threads = 1;
1447     }
1448        
1449     return NULL;
1450 }
1451
1452 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, char *arg)
1453 {
1454     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1455     if (err != NULL) {
1456         return err;
1457     }
1458
1459     max_spare_threads = atoi(arg);
1460     return NULL;
1461 }
1462
1463 static const char *set_server_limit (cmd_parms *cmd, void *dummy, char *arg) 
1464 {
1465     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1466     if (err != NULL) {
1467         return err;
1468     }
1469
1470     ap_daemons_limit = atoi(arg);
1471     if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1472        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1473                     "WARNING: MaxClients of %d exceeds compile time limit "
1474                     "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1475        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1476                     " lowering MaxClients to %d.  To increase, please "
1477                     "see the", HARD_SERVER_LIMIT);
1478        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1479                     " HARD_SERVER_LIMIT define in src/include/httpd.h.");
1480        ap_daemons_limit = HARD_SERVER_LIMIT;
1481     } 
1482     else if (ap_daemons_limit < 1) {
1483         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1\n");
1484         ap_daemons_limit = 1;
1485     }
1486     return NULL;
1487 }
1488
1489 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg) 
1490 {
1491     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1492     if (err != NULL) {
1493         return err;
1494     }
1495
1496     ap_threads_per_child = atoi(arg);
1497     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1498         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1499                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1500                      "limit of %d threads,", ap_threads_per_child,
1501                      HARD_THREAD_LIMIT);
1502         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1503                      " lowering ThreadsPerChild to %d. To increase, please"
1504                      "see the", HARD_THREAD_LIMIT);
1505         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1506                      " HARD_THREAD_LIMIT define in src/include/httpd.h.");
1507     }
1508     else if (ap_threads_per_child < 1) {
1509         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1510                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1511         ap_threads_per_child = 1;
1512     }
1513     return NULL;
1514 }
1515
1516 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg) 
1517 {
1518     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1519     if (err != NULL) {
1520         return err;
1521     }
1522
1523     ap_max_requests_per_child = atoi(arg);
1524
1525     return NULL;
1526 }
1527
1528 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg) 
1529 {
1530     struct stat finfo;
1531     const char *fname;
1532     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1533     if (err != NULL) {
1534         return err;
1535     }
1536
1537     fname = ap_server_root_relative(cmd->pool, arg);
1538     if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1539         return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1540                           " does not exist or is not a directory", NULL);
1541     }
1542     ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1543     return NULL;
1544 }
1545
1546 static const command_rec mpmt_pthread_cmds[] = {
1547 UNIX_DAEMON_COMMANDS
1548 LISTEN_COMMANDS
1549 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1550     "A file for logging the server process ID"},
1551 { "ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF, TAKE1,
1552     "A file for Apache to maintain runtime process management information"},
1553 { "LockFile", set_lockfile, NULL, RSRC_CONF, TAKE1,
1554     "The lockfile used when Apache needs to lock the accept() call"},
1555 { "StartServers", set_daemons_to_start, NULL, RSRC_CONF, TAKE1,
1556   "Number of child processes launched at server startup" },
1557 { "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF, TAKE1,
1558   "Minimum number of idle children, to handle request spikes" },
1559 { "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF, TAKE1,
1560   "Maximum number of idle children" },
1561 { "MaxClients", set_server_limit, NULL, RSRC_CONF, TAKE1,
1562   "Maximum number of children alive at the same time" },
1563 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1564   "Number of threads each child creates" },
1565 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1566   "Maximum number of requests a particular child serves before dying." },
1567 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1568   "The location of the directory Apache changes to before dumping core" },
1569 { NULL }
1570 };
1571
1572 module MODULE_VAR_EXPORT mpm_mpmt_pthread_module = {
1573     MPM20_MODULE_STUFF,
1574     mpmt_pthread_pre_config,    /* run hook before the configuration is read */
1575     NULL,                       /* create per-directory config structure */
1576     NULL,                       /* merge per-directory config structures */
1577     NULL,                       /* create per-server config structure */
1578     NULL,                       /* merge per-server config structures */
1579     mpmt_pthread_cmds,          /* command ap_table_t */
1580     NULL,                       /* handlers */
1581     mpmt_pthread_hooks          /* register_hooks */
1582 };
1583