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