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