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