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