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