]> granicus.if.org Git - apache/blob - server/mpm/worker/worker.c
write a debug message to the log when we're stuck in the sicko state
[apache] / server / mpm / worker / worker.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 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 /* The purpose of this MPM is to fix the design flaws in the threaded
60  * model.  Because of the way that pthreads and mutex locks interact,
61  * it is basically impossible to cleanly gracefully shutdown a child
62  * process if multiple threads are all blocked in accept.  This model
63  * fixes those problems.
64  */
65
66 #include "apr.h"
67 #include "apr_portable.h"
68 #include "apr_strings.h"
69 #include "apr_file_io.h"
70 #include "apr_thread_proc.h"
71 #include "apr_signal.h"
72 #include "apr_thread_mutex.h"
73 #include "apr_proc_mutex.h"
74 #define APR_WANT_STRFUNC
75 #include "apr_want.h"
76
77 #if APR_HAVE_UNISTD_H
78 #include <unistd.h>
79 #endif
80 #if APR_HAVE_SYS_SOCKET_H
81 #include <sys/socket.h>
82 #endif
83 #if APR_HAVE_SYS_WAIT_H
84 #include <sys/wait.h> 
85 #endif
86 #ifdef HAVE_SYS_PROCESSOR_H
87 #include <sys/processor.h> /* for bindprocessor() */
88 #endif
89
90 #if !APR_HAS_THREADS
91 #error The Worker MPM requires APR threads, but they are unavailable.
92 #endif
93
94 #define CORE_PRIVATE 
95  
96 #include "ap_config.h"
97 #include "httpd.h" 
98 #include "http_main.h" 
99 #include "http_log.h" 
100 #include "http_config.h"        /* for read_config */ 
101 #include "http_core.h"          /* for get_remote_host */ 
102 #include "http_connection.h"
103 #include "ap_mpm.h"
104 #include "pod.h"
105 #include "mpm_common.h"
106 #include "ap_listen.h"
107 #include "scoreboard.h" 
108 #include "fdqueue.h"
109 #include "mpm_default.h"
110
111 #include <signal.h>
112 #include <limits.h>             /* for INT_MAX */
113
114 /* Limit on the total --- clients will be locked out if more servers than
115  * this are needed.  It is intended solely to keep the server from crashing
116  * when things get out of hand.
117  *
118  * We keep a hard maximum number of servers, for two reasons --- first off,
119  * in case something goes seriously wrong, we want to stop the fork bomb
120  * short of actually crashing the machine we're running on by filling some
121  * kernel table.  Secondly, it keeps the size of the scoreboard file small
122  * enough that we can read the whole thing without worrying too much about
123  * the overhead.
124  */
125 #ifndef DEFAULT_SERVER_LIMIT
126 #define DEFAULT_SERVER_LIMIT 16
127 #endif
128
129 /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT.  We want
130  * some sort of compile-time limit to help catch typos.
131  */
132 #ifndef MAX_SERVER_LIMIT
133 #define MAX_SERVER_LIMIT 20000
134 #endif
135
136 /* Limit on the threads per process.  Clients will be locked out if more than
137  * this  * server_limit are needed.
138  *
139  * We keep this for one reason it keeps the size of the scoreboard file small
140  * enough that we can read the whole thing without worrying too much about
141  * the overhead.
142  */
143 #ifndef DEFAULT_THREAD_LIMIT
144 #define DEFAULT_THREAD_LIMIT 64 
145 #endif
146
147 /* Admin can't tune ThreadLimit beyond MAX_THREAD_LIMIT.  We want
148  * some sort of compile-time limit to help catch typos.
149  */
150 #ifndef MAX_THREAD_LIMIT
151 #define MAX_THREAD_LIMIT 20000
152 #endif
153
154 /*
155  * Actual definitions of config globals
156  */
157
158 int ap_threads_per_child = 0;         /* Worker threads per child */
159 static int ap_daemons_to_start = 0;
160 static int min_spare_threads = 0;
161 static int max_spare_threads = 0;
162 static int ap_daemons_limit = 0;
163 static int server_limit = DEFAULT_SERVER_LIMIT;
164 static int first_server_limit;
165 static int thread_limit = DEFAULT_THREAD_LIMIT;
166 static int first_thread_limit;
167 static int changed_limit_at_restart;
168 static int dying = 0;
169 static int workers_may_exit = 0;
170 static int requests_this_child;
171 static int num_listensocks = 0;
172 static int resource_shortage = 0;
173 static fd_queue_t *worker_queue;
174
175 /* The structure used to pass unique initialization info to each thread */
176 typedef struct {
177     int pid;
178     int tid;
179     int sd;
180 } proc_info;
181
182 /* Structure used to pass information to the thread responsible for 
183  * creating the rest of the threads.
184  */
185 typedef struct {
186     apr_thread_t **threads;
187     apr_thread_t *listener;
188     int child_num_arg;
189     apr_threadattr_t *threadattr;
190 } thread_starter;
191
192 #define ID_FROM_CHILD_THREAD(c, t)    ((c * thread_limit) + t)
193
194 /*
195  * The max child slot ever assigned, preserved across restarts.  Necessary
196  * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We 
197  * use this value to optimize routines that have to scan the entire 
198  * scoreboard.
199  */
200 int ap_max_daemons_limit = -1;
201
202 static ap_pod_t *pod;
203
204 /* *Non*-shared http_main globals... */
205
206 server_rec *ap_server_conf;
207
208 /* The worker MPM respects a couple of runtime flags that can aid
209  * in debugging. Setting the -DNO_DETACH flag will prevent the root process
210  * from detaching from its controlling terminal. Additionally, setting
211  * the -DONE_PROCESS flag (which implies -DNO_DETACH) will get you the
212  * child_main loop running in the process which originally started up.
213  * This gives you a pretty nice debugging environment.  (You'll get a SIGHUP
214  * early in standalone_main; just continue through.  This is the server
215  * trying to kill off any child processes which it might have lying
216  * around --- Apache doesn't keep track of their pids, it just sends
217  * SIGHUP to the process group, ignoring it in the root process.
218  * Continue through and you'll be fine.).
219  */
220
221 static int one_process = 0;
222
223 #ifdef DEBUG_SIGSTOP
224 int raise_sigstop_flags;
225 #endif
226
227 static apr_pool_t *pconf;                 /* Pool for config stuff */
228 static apr_pool_t *pchild;                /* Pool for httpd child stuff */
229
230 static pid_t ap_my_pid; /* Linux getpid() doesn't work except in main 
231                            thread. Use this instead */
232 static pid_t parent_pid;
233 static apr_os_thread_t *listener_os_thread;
234
235 /* Locks for accept serialization */
236 static apr_proc_mutex_t *accept_mutex;
237
238 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
239 #define SAFE_ACCEPT(stmt) (ap_listeners->next ? (stmt) : APR_SUCCESS)
240 #else
241 #define SAFE_ACCEPT(stmt) (stmt)
242 #endif
243
244 /* The LISTENER_SIGNAL signal will be sent from the main thread to the 
245  * listener thread to wake it up for graceful termination (what a child 
246  * process from an old generation does when the admin does "apachectl 
247  * graceful").  This signal will be blocked in all threads of a child
248  * process except for the listener thread.
249  */
250 #define LISTENER_SIGNAL     SIGHUP
251
252 static void wakeup_listener(void)
253 {
254     /*
255      * we should just be able to "kill(ap_my_pid, LISTENER_SIGNAL)" and wake
256      * up the listener thread since it is the only thread with SIGHUP
257      * unblocked, but that doesn't work on Linux
258      */
259     pthread_kill(*listener_os_thread, LISTENER_SIGNAL);
260 }
261
262 static void signal_workers(void)
263 {
264     workers_may_exit = 1;
265
266     /* in case we weren't called from the listener thread, wake up the
267      * listener thread
268      */
269     wakeup_listener();
270
271     /* XXX: This will happen naturally on a graceful, and we don't care 
272      * otherwise.
273     ap_queue_signal_all_wakeup(worker_queue); */
274     ap_queue_interrupt_all(worker_queue);
275 }
276
277 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
278 {
279     switch(query_code){
280         case AP_MPMQ_MAX_DAEMON_USED:
281             *result = ap_max_daemons_limit;
282             return APR_SUCCESS;
283         case AP_MPMQ_IS_THREADED:
284             *result = AP_MPMQ_STATIC;
285             return APR_SUCCESS;
286         case AP_MPMQ_IS_FORKED:
287             *result = AP_MPMQ_DYNAMIC;
288             return APR_SUCCESS;
289         case AP_MPMQ_HARD_LIMIT_DAEMONS:
290             *result = server_limit;
291             return APR_SUCCESS;
292         case AP_MPMQ_HARD_LIMIT_THREADS:
293             *result = thread_limit;
294             return APR_SUCCESS;
295         case AP_MPMQ_MAX_THREADS:
296             *result = ap_threads_per_child;
297             return APR_SUCCESS;
298         case AP_MPMQ_MIN_SPARE_DAEMONS:
299             *result = 0;
300             return APR_SUCCESS;
301         case AP_MPMQ_MIN_SPARE_THREADS:    
302             *result = min_spare_threads;
303             return APR_SUCCESS;
304         case AP_MPMQ_MAX_SPARE_DAEMONS:
305             *result = 0;
306             return APR_SUCCESS;
307         case AP_MPMQ_MAX_SPARE_THREADS:
308             *result = max_spare_threads;
309             return APR_SUCCESS;
310         case AP_MPMQ_MAX_REQUESTS_DAEMON:
311             *result = ap_max_requests_per_child;
312             return APR_SUCCESS;
313         case AP_MPMQ_MAX_DAEMONS:
314             *result = ap_daemons_limit;
315             return APR_SUCCESS;
316     }
317     return APR_ENOTIMPL;
318 }
319
320 /* a clean exit from a child with proper cleanup */ 
321 static void clean_child_exit(int code) __attribute__ ((noreturn));
322 static void clean_child_exit(int code)
323 {
324     if (pchild) {
325         apr_pool_destroy(pchild);
326     }
327     exit(code);
328 }
329
330 /* handle all varieties of core dumping signals */
331 static void sig_coredump(int sig)
332 {
333     apr_filepath_set(ap_coredump_dir, pconf);
334     apr_signal(sig, SIG_DFL);
335     if (ap_my_pid == parent_pid) {
336         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
337                      0, ap_server_conf,
338                      "seg fault or similar nasty error detected "
339                      "in the parent process");
340         
341         /* XXX we can probably add some rudimentary cleanup code here,
342          * like getting rid of the pid file.  If any additional bad stuff
343          * happens, we are protected from recursive errors taking down the
344          * system since this function is no longer the signal handler   GLA
345          */
346     }
347     kill(ap_my_pid, sig);
348     /* At this point we've got sig blocked, because we're still inside
349      * the signal handler.  When we leave the signal handler it will
350      * be unblocked, and we'll take the signal... and coredump or whatever
351      * is appropriate for this particular Unix.  In addition the parent
352      * will see the real signal we received -- whereas if we called
353      * abort() here, the parent would only see SIGABRT.
354      */
355 }
356
357 static void just_die(int sig)
358 {
359     clean_child_exit(0);
360 }
361
362 /*****************************************************************
363  * Connection structures and accounting...
364  */
365
366 /* volatile just in case */
367 static int volatile shutdown_pending;
368 static int volatile restart_pending;
369 static int volatile is_graceful;
370 static volatile int child_fatal;
371 ap_generation_t volatile ap_my_generation;
372
373 /*
374  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
375  * functions to initiate shutdown or restart without relying on signals. 
376  * Previously this was initiated in sig_term() and restart() signal handlers, 
377  * but we want to be able to start a shutdown/restart from other sources --
378  * e.g. on Win32, from the service manager. Now the service manager can
379  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
380  * these functions can also be called by the child processes, since global
381  * variables are no longer used to pass on the required action to the parent.
382  *
383  * These should only be called from the parent process itself, since the
384  * parent process will use the shutdown_pending and restart_pending variables
385  * to determine whether to shutdown or restart. The child process should
386  * call signal_parent() directly to tell the parent to die -- this will
387  * cause neither of those variable to be set, which the parent will
388  * assume means something serious is wrong (which it will be, for the
389  * child to force an exit) and so do an exit anyway.
390  */
391
392 static void ap_start_shutdown(void)
393 {
394     if (shutdown_pending == 1) {
395         /* Um, is this _probably_ not an error, if the user has
396          * tried to do a shutdown twice quickly, so we won't
397          * worry about reporting it.
398          */
399         return;
400     }
401     shutdown_pending = 1;
402 }
403
404 /* do a graceful restart if graceful == 1 */
405 static void ap_start_restart(int graceful)
406 {
407
408     if (restart_pending == 1) {
409         /* Probably not an error - don't bother reporting it */
410         return;
411     }
412     restart_pending = 1;
413     is_graceful = graceful;
414     if (is_graceful) {
415         apr_pool_cleanup_kill(pconf, NULL, ap_cleanup_scoreboard);
416     }
417 }
418
419 static void sig_term(int sig)
420 {
421     ap_start_shutdown();
422 }
423
424 static void restart(int sig)
425 {
426     ap_start_restart(sig == AP_SIG_GRACEFUL);
427 }
428
429 static void set_signals(void)
430 {
431 #ifndef NO_USE_SIGACTION
432     struct sigaction sa;
433
434     sigemptyset(&sa.sa_mask);
435     sa.sa_flags = 0;
436
437     if (!one_process) {
438         sa.sa_handler = sig_coredump;
439 #if defined(SA_ONESHOT)
440         sa.sa_flags = SA_ONESHOT;
441 #elif defined(SA_RESETHAND)
442         sa.sa_flags = SA_RESETHAND;
443 #endif
444         if (sigaction(SIGSEGV, &sa, NULL) < 0)
445             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
446                          "sigaction(SIGSEGV)");
447 #ifdef SIGBUS
448         if (sigaction(SIGBUS, &sa, NULL) < 0)
449             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
450                          "sigaction(SIGBUS)");
451 #endif
452 #ifdef SIGABORT
453         if (sigaction(SIGABORT, &sa, NULL) < 0)
454             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
455                          "sigaction(SIGABORT)");
456 #endif
457 #ifdef SIGABRT
458         if (sigaction(SIGABRT, &sa, NULL) < 0)
459             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
460                          "sigaction(SIGABRT)");
461 #endif
462 #ifdef SIGILL
463         if (sigaction(SIGILL, &sa, NULL) < 0)
464             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
465                          "sigaction(SIGILL)");
466 #endif
467         sa.sa_flags = 0;
468     }
469     sa.sa_handler = sig_term;
470     if (sigaction(SIGTERM, &sa, NULL) < 0)
471         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
472                      "sigaction(SIGTERM)");
473 #ifdef SIGINT
474     if (sigaction(SIGINT, &sa, NULL) < 0)
475         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
476                      "sigaction(SIGINT)");
477 #endif
478 #ifdef SIGXCPU
479     sa.sa_handler = SIG_DFL;
480     if (sigaction(SIGXCPU, &sa, NULL) < 0)
481         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
482                      "sigaction(SIGXCPU)");
483 #endif
484 #ifdef SIGXFSZ
485     sa.sa_handler = SIG_DFL;
486     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
487         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
488                      "sigaction(SIGXFSZ)");
489 #endif
490 #ifdef SIGPIPE
491     sa.sa_handler = SIG_IGN;
492     if (sigaction(SIGPIPE, &sa, NULL) < 0)
493         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
494                      "sigaction(SIGPIPE)");
495 #endif
496
497     /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy 
498      * processing one */
499     sigaddset(&sa.sa_mask, SIGHUP);
500     sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
501     sa.sa_handler = restart;
502     if (sigaction(SIGHUP, &sa, NULL) < 0)
503         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
504                      "sigaction(SIGHUP)");
505     if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
506         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, 
507                      "sigaction(" AP_SIG_GRACEFUL_STRING ")");
508 #else
509     if (!one_process) {
510         apr_signal(SIGSEGV, sig_coredump);
511 #ifdef SIGBUS
512         apr_signal(SIGBUS, sig_coredump);
513 #endif /* SIGBUS */
514 #ifdef SIGABORT
515         apr_signal(SIGABORT, sig_coredump);
516 #endif /* SIGABORT */
517 #ifdef SIGABRT
518         apr_signal(SIGABRT, sig_coredump);
519 #endif /* SIGABRT */
520 #ifdef SIGILL
521         apr_signal(SIGILL, sig_coredump);
522 #endif /* SIGILL */
523 #ifdef SIGXCPU
524         apr_signal(SIGXCPU, SIG_DFL);
525 #endif /* SIGXCPU */
526 #ifdef SIGXFSZ
527         apr_signal(SIGXFSZ, SIG_DFL);
528 #endif /* SIGXFSZ */
529     }
530
531     apr_signal(SIGTERM, sig_term);
532 #ifdef SIGHUP
533     apr_signal(SIGHUP, restart);
534 #endif /* SIGHUP */
535 #ifdef AP_SIG_GRACEFUL
536     apr_signal(AP_SIG_GRACEFUL, restart);
537 #endif /* AP_SIG_GRACEFUL */
538 #ifdef SIGPIPE
539     apr_signal(SIGPIPE, SIG_IGN);
540 #endif /* SIGPIPE */
541
542 #endif
543 }
544
545 /*****************************************************************
546  * Here follows a long bunch of generic server bookkeeping stuff...
547  */
548
549 int ap_graceful_stop_signalled(void)
550     /* XXX this is really a bad confusing obsolete name
551      * maybe it should be ap_mpm_process_exiting?
552      */
553 {
554     return workers_may_exit;
555 }
556
557 /*****************************************************************
558  * Child process main loop.
559  */
560
561 static void process_socket(apr_pool_t *p, apr_socket_t *sock, int my_child_num,
562                            int my_thread_num)
563 {
564     conn_rec *current_conn;
565     long conn_id = ID_FROM_CHILD_THREAD(my_child_num, my_thread_num);
566     int csd;
567     ap_sb_handle_t *sbh;
568
569     ap_create_sb_handle(&sbh, p, my_child_num, my_thread_num);
570     apr_os_sock_get(&csd, sock);
571
572     if (csd >= FD_SETSIZE) {
573         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
574                      "new file descriptor %d is too large; you probably need "
575                      "to rebuild Apache with a larger FD_SETSIZE "
576                      "(currently %d)", 
577                      csd, FD_SETSIZE);
578         apr_socket_close(sock);
579         return;
580     }
581
582     current_conn = ap_run_create_connection(p, ap_server_conf, sock, conn_id, sbh);
583     if (current_conn) {
584         ap_process_connection(current_conn, sock);
585         ap_lingering_close(current_conn);
586     }
587 }
588
589 /* requests_this_child has gone to zero or below.  See if the admin coded
590    "MaxRequestsPerChild 0", and keep going in that case.  Doing it this way
591    simplifies the hot path in worker_thread */
592 static void check_infinite_requests(void)
593 {
594     if (ap_max_requests_per_child) {
595         signal_workers();
596     }
597     else {
598         /* wow! if you're executing this code, you may have set a record.
599          * either this child process has served over 2 billion requests, or
600          * you're running a threaded 2.0 on a 16 bit machine.  
601          *
602          * I'll buy pizza and beers at Apachecon for the first person to do
603          * the former without cheating (dorking with INT_MAX, or running with
604          * uncommitted performance patches, for example).    
605          *
606          * for the latter case, you probably deserve a beer too.   Greg Ames
607          */
608             
609         requests_this_child = INT_MAX;      /* keep going */ 
610     }
611 }
612
613 static void unblock_the_listener(int sig)
614 {
615     /* XXX If specifying SIG_IGN is guaranteed to unblock a syscall,
616      *     then we don't need this goofy function.
617      */
618 }
619
620 static void *listener_thread(apr_thread_t *thd, void * dummy)
621 {
622     proc_info * ti = dummy;
623     int process_slot = ti->pid;
624     int thread_slot = ti->tid;
625     apr_pool_t *tpool = apr_thread_pool_get(thd);
626     void *csd = NULL;
627     apr_pool_t *ptrans;                /* Pool for per-transaction stuff */
628     apr_pool_t *recycled_pool = NULL;
629     int n;
630     apr_pollfd_t *pollset;
631     apr_status_t rv;
632     ap_listen_rec *lr, *last_lr = ap_listeners;
633     struct sigaction sa;
634     sigset_t sig_mask;
635
636     free(ti);
637
638     apr_poll_setup(&pollset, num_listensocks, tpool);
639     for(lr = ap_listeners ; lr != NULL ; lr = lr->next)
640         apr_poll_socket_add(pollset, lr->sd, APR_POLLIN);
641
642     sigemptyset(&sig_mask);
643     /* Unblock the signal used to wake this thread up, and set a handler for
644      * it.
645      */
646     sigaddset(&sig_mask, LISTENER_SIGNAL);
647 #if defined(SIGPROCMASK_SETS_THREAD_MASK)
648     sigprocmask(SIG_UNBLOCK, &sig_mask, NULL);
649 #else
650     pthread_sigmask(SIG_UNBLOCK, &sig_mask, NULL);
651 #endif
652     sigemptyset(&sa.sa_mask);
653     sa.sa_flags = 0;
654     sa.sa_handler = unblock_the_listener;
655     sigaction(LISTENER_SIGNAL, &sa, NULL);
656
657     /* TODO: Switch to a system where threads reuse the results from earlier
658        poll calls - manoj */
659     while (1) {
660         /* TODO: requests_this_child should be synchronized - aaron */
661         if (requests_this_child <= 0) {
662             check_infinite_requests();
663         }
664         if (workers_may_exit) break;
665
666         if ((rv = SAFE_ACCEPT(apr_proc_mutex_lock(accept_mutex)))
667             != APR_SUCCESS) {
668             int level = APLOG_EMERG;
669
670             if (workers_may_exit) {
671                 break;
672             }
673             if (ap_scoreboard_image->parent[process_slot].generation != 
674                 ap_scoreboard_image->global->running_generation) {
675                 level = APLOG_DEBUG; /* common to get these at restart time */
676             }
677             ap_log_error(APLOG_MARK, level, rv, ap_server_conf,
678                          "apr_proc_mutex_lock failed. Attempting to shutdown "
679                          "process gracefully.");
680             signal_workers();
681             break;                    /* skip the lock release */
682         }
683
684         if (!ap_listeners->next) {
685             /* Only one listener, so skip the poll */
686             lr = ap_listeners;
687         }
688         else {
689             while (!workers_may_exit) {
690                 apr_status_t ret;
691                 apr_int16_t event;
692
693                 ret = apr_poll(pollset, &n, -1);
694                 if (ret != APR_SUCCESS) {
695                     if (APR_STATUS_IS_EINTR(ret)) {
696                         continue;
697                     }
698
699                     /* apr_poll() will only return errors in catastrophic
700                      * circumstances. Let's try exiting gracefully, for now. */
701                     ap_log_error(APLOG_MARK, APLOG_ERR, ret, (const server_rec *)
702                                  ap_server_conf, "apr_poll: (listen)");
703                     signal_workers();
704                 }
705
706                 if (workers_may_exit) break;
707
708                 /* find a listener */
709                 lr = last_lr;
710                 do {
711                     lr = lr->next;
712                     if (lr == NULL) {
713                         lr = ap_listeners;
714                     }
715                     /* XXX: Should we check for POLLERR? */
716                     apr_poll_revents_get(&event, lr->sd, pollset);
717                     if (event & APR_POLLIN) {
718                         last_lr = lr;
719                         goto got_fd;
720                     }
721                 } while (lr != last_lr);
722             }
723         }
724     got_fd:
725         if (!workers_may_exit) {
726             /* create a new transaction pool for each accepted socket */
727             if (recycled_pool == NULL) {
728                 apr_allocator_t *allocator;
729
730                 apr_allocator_create(&allocator);
731                 apr_pool_create_ex(&ptrans, NULL, NULL, allocator);
732                 apr_allocator_set_owner(allocator, ptrans);
733             }
734             else {
735                 ptrans = recycled_pool;
736             }
737             apr_pool_tag(ptrans, "transaction");
738             rv = lr->accept_func(&csd, lr, ptrans);
739
740             /* If we were interrupted for whatever reason, just start
741              * the main loop over again.
742              */
743             if (APR_STATUS_IS_EINTR(rv)) {
744                 continue;
745             }
746             if (rv == APR_EGENERAL) {
747                 /* E[NM]FILE, ENOMEM, etc */
748                 resource_shortage = 1;
749                 signal_workers();
750             }
751             if ((rv = SAFE_ACCEPT(apr_proc_mutex_unlock(accept_mutex)))
752                 != APR_SUCCESS) {
753                 int level = APLOG_EMERG;
754
755                 if (workers_may_exit) {
756                     break;
757                 }
758                 if (ap_scoreboard_image->parent[process_slot].generation != 
759                     ap_scoreboard_image->global->running_generation) {
760                     level = APLOG_DEBUG; /* common to get these at restart time */
761                 }
762                 ap_log_error(APLOG_MARK, level, rv, ap_server_conf,
763                              "apr_proc_mutex_unlock failed. Attempting to "
764                              "shutdown process gracefully.");
765                 signal_workers();
766             }
767             if (csd != NULL) {
768                 rv = ap_queue_push(worker_queue, csd, ptrans,
769                                    &recycled_pool);
770                 if (rv) {
771                     /* trash the connection; we couldn't queue the connected
772                      * socket to a worker 
773                      */
774                     apr_socket_close(csd);
775                     ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
776                                  "ap_queue_push failed");
777                 }
778             }
779         }
780         else {
781             if ((rv = SAFE_ACCEPT(apr_proc_mutex_unlock(accept_mutex)))
782                 != APR_SUCCESS) {
783                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
784                              "apr_proc_mutex_unlock failed. Attempting to "
785                              "shutdown process gracefully.");
786                 signal_workers();
787             }
788             break;
789         }
790     }
791
792     ap_update_child_status_from_indexes(process_slot, thread_slot, 
793                                         (dying) ? SERVER_DEAD : SERVER_GRACEFUL,
794                                         (request_rec *) NULL);
795     dying = 1;
796     ap_scoreboard_image->parent[process_slot].quiescing = 1;
797     kill(ap_my_pid, SIGTERM);
798
799     apr_thread_exit(thd, APR_SUCCESS);
800     return NULL;
801 }
802
803 static void * APR_THREAD_FUNC worker_thread(apr_thread_t *thd, void * dummy)
804 {
805     proc_info * ti = dummy;
806     int process_slot = ti->pid;
807     int thread_slot = ti->tid;
808     apr_socket_t *csd = NULL;
809     apr_pool_t *last_ptrans = NULL;
810     apr_pool_t *ptrans;                /* Pool for per-transaction stuff */
811     apr_status_t rv;
812
813     free(ti);
814
815     ap_update_child_status_from_indexes(process_slot, thread_slot, SERVER_STARTING, NULL);
816     while (!workers_may_exit) {
817         ap_update_child_status_from_indexes(process_slot, thread_slot, SERVER_READY, NULL);
818         rv = ap_queue_pop(worker_queue, &csd, &ptrans, last_ptrans);
819         last_ptrans = NULL;
820
821         /* We get APR_EINTR whenever ap_queue_pop() has been interrupted
822          * from an explicit call to ap_queue_interrupt_all(). This allows
823          * us to unblock threads stuck in ap_queue_pop() when a shutdown
824          * is pending. */
825         if (rv == APR_EINTR || !csd) {
826             continue;
827         }
828         process_socket(ptrans, csd, process_slot, thread_slot);
829         requests_this_child--; /* FIXME: should be synchronized - aaron */
830         apr_pool_clear(ptrans);
831         last_ptrans = ptrans;
832     }
833
834     ap_update_child_status_from_indexes(process_slot, thread_slot,
835         (dying) ? SERVER_DEAD : SERVER_GRACEFUL, (request_rec *) NULL);
836
837     apr_thread_exit(thd, APR_SUCCESS);
838     return NULL;
839 }
840
841 static int check_signal(int signum)
842 {
843     switch (signum) {
844     case SIGTERM:
845     case SIGINT:
846         return 1;
847     }
848     return 0;
849 }
850
851 /* XXX under some circumstances not understood, children can get stuck
852  *     in start_threads forever trying to take over slots which will
853  *     never be cleaned up; for now there is an APLOG_DEBUG message issued
854  *     every so often when this condition occurs
855  */
856 static void * APR_THREAD_FUNC start_threads(apr_thread_t *thd, void *dummy)
857 {
858     thread_starter *ts = dummy;
859     apr_thread_t **threads = ts->threads;
860     apr_threadattr_t *thread_attr = ts->threadattr;
861     int child_num_arg = ts->child_num_arg;
862     int my_child_num = child_num_arg;
863     proc_info *my_info = NULL;
864     apr_status_t rv;
865     int i = 0;
866     int threads_created = 0;
867     int loops;
868     int prev_threads_created;
869
870     /* We must create the fd queues before we start up the listener
871      * and worker threads. */
872     worker_queue = apr_pcalloc(pchild, sizeof(*worker_queue));
873     rv = ap_queue_init(worker_queue, ap_threads_per_child, pchild);
874     if (rv != APR_SUCCESS) {
875         ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
876                      "ap_queue_init() failed");
877         clean_child_exit(APEXIT_CHILDFATAL);
878     }
879
880     my_info = (proc_info *)malloc(sizeof(proc_info));
881     my_info->pid = my_child_num;
882     my_info->tid = i;
883     my_info->sd = 0;
884     rv = apr_thread_create(&ts->listener, thread_attr, listener_thread,
885                            my_info, pchild);
886     if (rv != APR_SUCCESS) {
887         ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
888                      "apr_thread_create: unable to create listener thread");
889         /* In case system resources are maxxed out, we don't want
890          * Apache running away with the CPU trying to fork over and
891          * over and over again if we exit.
892          * XXX Jeff doesn't see how Apache is going to try to fork again since
893          * the exit code is APEXIT_CHILDFATAL
894          */
895         apr_sleep(10 * APR_USEC_PER_SEC);
896         clean_child_exit(APEXIT_CHILDFATAL);
897     }
898     apr_os_thread_get(&listener_os_thread, ts->listener);
899     loops = prev_threads_created = 0;
900     while (1) {
901         /* ap_threads_per_child does not include the listener thread */
902         for (i = 0; i < ap_threads_per_child; i++) {
903             int status = ap_scoreboard_image->servers[child_num_arg][i].status;
904
905             if (status != SERVER_GRACEFUL && status != SERVER_DEAD) {
906                 continue;
907             }
908
909             my_info = (proc_info *)malloc(sizeof(proc_info));
910             if (my_info == NULL) {
911                 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
912                              "malloc: out of memory");
913                 clean_child_exit(APEXIT_CHILDFATAL);
914             }
915             my_info->pid = my_child_num;
916             my_info->tid = i;
917             my_info->sd = 0;
918         
919             /* We are creating threads right now */
920             ap_update_child_status_from_indexes(my_child_num, i,
921                                                 SERVER_STARTING, NULL);
922             /* We let each thread update its own scoreboard entry.  This is
923              * done because it lets us deal with tid better.
924              */
925             rv = apr_thread_create(&threads[i], thread_attr, 
926                                    worker_thread, my_info, pchild);
927             if (rv != APR_SUCCESS) {
928                 ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
929                     "apr_thread_create: unable to create worker thread");
930                 /* In case system resources are maxxed out, we don't want
931                    Apache running away with the CPU trying to fork over and
932                    over and over again if we exit. */
933                 apr_sleep(10 * APR_USEC_PER_SEC);
934                 clean_child_exit(APEXIT_CHILDFATAL);
935             }
936             threads_created++;
937         }
938         if (workers_may_exit || threads_created == ap_threads_per_child) {
939             break;
940         }
941         /* wait for previous generation to clean up an entry */
942         apr_sleep(1 * APR_USEC_PER_SEC);
943         ++loops;
944         if (loops % 120 == 0) { /* every couple of minutes */
945             if (prev_threads_created == threads_created) {
946                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
947                              "child %" APR_PID_T_FMT " isn't taking over "
948                              "slots very quickly (%d of %d)",
949                              ap_my_pid, threads_created, ap_threads_per_child);
950             }
951             prev_threads_created = threads_created;
952         }
953     }
954     
955     /* What state should this child_main process be listed as in the 
956      * scoreboard...?
957      *  ap_update_child_status_from_indexes(my_child_num, i, SERVER_STARTING, 
958      *                                      (request_rec *) NULL);
959      * 
960      *  This state should be listed separately in the scoreboard, in some kind
961      *  of process_status, not mixed in with the worker threads' status.   
962      *  "life_status" is almost right, but it's in the worker's structure, and 
963      *  the name could be clearer.   gla
964      */
965     apr_thread_exit(thd, APR_SUCCESS);
966     return NULL;
967 }
968
969 static void join_workers(apr_thread_t *listener, apr_thread_t **threads)
970 {
971     int i;
972     apr_status_t rv, thread_rv;
973
974     if (listener) {
975         int iter;
976         
977         /* deal with a rare timing window which affects waking up the
978          * listener thread...  if the signal sent to the listener thread
979          * is delivered between the time it verifies that the
980          * workers_may_exit flag is clear and the time it enters a
981          * blocking syscall, the signal didn't do any good...  work around
982          * that by sleeping briefly and sending it again
983          */
984
985         iter = 0;
986         while (iter < 10 && pthread_kill(*listener_os_thread, 0) == 0) {
987             /* listener not dead yet */
988             apr_sleep(APR_USEC_PER_SEC / 2);
989             wakeup_listener();
990             ++iter;
991         }
992         if (iter >= 10) {
993             ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
994                          "the listener thread didn't exit");
995         }
996         else {
997             rv = apr_thread_join(&thread_rv, listener);
998             if (rv != APR_SUCCESS) {
999                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1000                              "apr_thread_join: unable to join listener thread");
1001             }
1002         }
1003     }
1004     
1005     for (i = 0; i < ap_threads_per_child; i++) {
1006         if (threads[i]) { /* if we ever created this thread */
1007             rv = apr_thread_join(&thread_rv, threads[i]);
1008             if (rv != APR_SUCCESS) {
1009                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1010                              "apr_thread_join: unable to join worker "
1011                              "thread %d",
1012                              i);
1013             }
1014         }
1015     }
1016 }
1017
1018 static void join_start_thread(apr_thread_t *start_thread_id)
1019 {
1020     apr_status_t rv, thread_rv;
1021
1022     workers_may_exit = 1; /* start thread may not want to exit until this
1023                            * is set
1024                            */
1025     rv = apr_thread_join(&thread_rv, start_thread_id);
1026     if (rv != APR_SUCCESS) {
1027         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
1028                      "apr_thread_join: unable to join the start "
1029                      "thread");
1030     }
1031 }
1032
1033 static void child_main(int child_num_arg)
1034 {
1035     apr_thread_t **threads;
1036     apr_status_t rv;
1037     thread_starter *ts;
1038     apr_threadattr_t *thread_attr;
1039     apr_thread_t *start_thread_id;
1040
1041     ap_my_pid = getpid();
1042     apr_pool_create(&pchild, pconf);
1043
1044     /*stuff to do before we switch id's, so we have permissions.*/
1045     ap_reopen_scoreboard(pchild, NULL, 0);
1046
1047     rv = SAFE_ACCEPT(apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname,
1048                                                pchild));
1049     if (rv != APR_SUCCESS) {
1050         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
1051                      "Couldn't initialize cross-process lock in child");
1052         clean_child_exit(APEXIT_CHILDFATAL);
1053     }
1054
1055     if (unixd_setup_child()) {
1056         clean_child_exit(APEXIT_CHILDFATAL);
1057     }
1058
1059     ap_run_child_init(pchild, ap_server_conf);
1060
1061     /* done with init critical section */
1062
1063     /* Just use the standard apr_setup_signal_thread to block all signals
1064      * from being received.  The child processes no longer use signals for
1065      * any communication with the parent process.
1066      */
1067     rv = apr_setup_signal_thread();
1068     if (rv != APR_SUCCESS) {
1069         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
1070                      "Couldn't initialize signal thread");
1071         clean_child_exit(APEXIT_CHILDFATAL);
1072     }
1073
1074     if (ap_max_requests_per_child) {
1075         requests_this_child = ap_max_requests_per_child;
1076     }
1077     else {
1078         /* coding a value of zero means infinity */
1079         requests_this_child = INT_MAX;
1080     }
1081     
1082     /* Setup worker threads */
1083
1084     /* clear the storage; we may not create all our threads immediately, 
1085      * and we want a 0 entry to indicate a thread which was not created
1086      */
1087     threads = (apr_thread_t **)calloc(1, 
1088                                 sizeof(apr_thread_t *) * ap_threads_per_child);
1089     if (threads == NULL) {
1090         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
1091                      "malloc: out of memory");
1092         clean_child_exit(APEXIT_CHILDFATAL);
1093     }
1094
1095     ts = (thread_starter *)apr_palloc(pchild, sizeof(*ts));
1096
1097     apr_threadattr_create(&thread_attr, pchild);
1098     /* 0 means PTHREAD_CREATE_JOINABLE */
1099     apr_threadattr_detach_set(thread_attr, 0);
1100
1101     ts->threads = threads;
1102     ts->listener = NULL;
1103     ts->child_num_arg = child_num_arg;
1104     ts->threadattr = thread_attr;
1105
1106     rv = apr_thread_create(&start_thread_id, thread_attr, start_threads,
1107                            ts, pchild);
1108     if (rv != APR_SUCCESS) {
1109         ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
1110                      "apr_thread_create: unable to create worker thread");
1111         /* In case system resources are maxxed out, we don't want
1112            Apache running away with the CPU trying to fork over and
1113            over and over again if we exit. */
1114         apr_sleep(10 * APR_USEC_PER_SEC);
1115         clean_child_exit(APEXIT_CHILDFATAL);
1116     }
1117
1118     /* If we are only running in one_process mode, we will want to
1119      * still handle signals. */
1120     if (one_process) {
1121         /* Set up a signal handler for this thread. */
1122         apr_signal_thread(check_signal);
1123         /* make sure the start thread has finished; signal_workers() 
1124          * and join_workers() depend on that
1125          */
1126         join_start_thread(start_thread_id);
1127         signal_workers(); /* helps us terminate a little more quickly when
1128                            * the dispatch of the signal thread
1129                            * beats the Pipe of Death and the browsers
1130                            */
1131         /* A terminating signal was received. Now join each of the
1132          * workers to clean them up.
1133          *   If the worker already exited, then the join frees
1134          *   their resources and returns.
1135          *   If the worker hasn't exited, then this blocks until
1136          *   they have (then cleans up).
1137          */
1138         join_workers(ts->listener, threads);
1139     }
1140     else { /* !one_process */
1141         /* Watch for any messages from the parent over the POD */
1142         while (1) {
1143             rv = ap_mpm_pod_check(pod);
1144             if (rv == AP_GRACEFUL || rv == AP_RESTART) {
1145                 /* make sure the start thread has finished; 
1146                  * signal_workers() and join_workers depend on that
1147                  */
1148                 join_start_thread(start_thread_id);
1149                 signal_workers();
1150                 break;
1151             }
1152         }
1153
1154         if (rv == AP_GRACEFUL) {
1155             /* A terminating signal was received. Now join each of the
1156              * workers to clean them up.
1157              *   If the worker already exited, then the join frees
1158              *   their resources and returns.
1159              *   If the worker hasn't exited, then this blocks until
1160              *   they have (then cleans up).
1161              */
1162             join_workers(ts->listener, threads);
1163         }
1164     }
1165
1166     free(threads);
1167
1168     clean_child_exit(resource_shortage ? APEXIT_CHILDSICK : 0);
1169 }
1170
1171 static int make_child(server_rec *s, int slot) 
1172 {
1173     int pid;
1174
1175     if (slot + 1 > ap_max_daemons_limit) {
1176         ap_max_daemons_limit = slot + 1;
1177     }
1178
1179     if (one_process) {
1180         set_signals();
1181         ap_scoreboard_image->parent[slot].pid = getpid();
1182         child_main(slot);
1183     }
1184
1185     if ((pid = fork()) == -1) {
1186         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, 
1187                      "fork: Unable to fork new process");
1188
1189         /* fork didn't succeed. Fix the scoreboard or else
1190          * it will say SERVER_STARTING forever and ever
1191          */
1192         ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD, NULL);
1193
1194         /* In case system resources are maxxed out, we don't want
1195            Apache running away with the CPU trying to fork over and
1196            over and over again. */
1197         apr_sleep(10 * APR_USEC_PER_SEC);
1198
1199         return -1;
1200     }
1201
1202     if (!pid) {
1203 #ifdef HAVE_BINDPROCESSOR
1204         /* By default, AIX binds to a single processor.  This bit unbinds
1205          * children which will then bind to another CPU.
1206          */
1207         int status = bindprocessor(BINDPROCESS, (int)getpid(),
1208                                PROCESSOR_CLASS_ANY);
1209         if (status != OK)
1210             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, errno, 
1211                          ap_server_conf,
1212                          "processor unbind failed %d", status);
1213 #endif
1214         RAISE_SIGSTOP(MAKE_CHILD);
1215
1216         apr_signal(SIGTERM, just_die);
1217         child_main(slot);
1218
1219         clean_child_exit(0);
1220     }
1221     /* else */
1222     ap_scoreboard_image->parent[slot].quiescing = 0;
1223     ap_scoreboard_image->parent[slot].pid = pid;
1224     return 0;
1225 }
1226
1227 /* start up a bunch of children */
1228 static void startup_children(int number_to_start)
1229 {
1230     int i;
1231
1232     for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
1233         if (ap_scoreboard_image->parent[i].pid != 0) {
1234             continue;
1235         }
1236         if (make_child(ap_server_conf, i) < 0) {
1237             break;
1238         }
1239         --number_to_start;
1240     }
1241 }
1242
1243
1244 /*
1245  * idle_spawn_rate is the number of children that will be spawned on the
1246  * next maintenance cycle if there aren't enough idle servers.  It is
1247  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
1248  * without the need to spawn.
1249  */
1250 static int idle_spawn_rate = 1;
1251 #ifndef MAX_SPAWN_RATE
1252 #define MAX_SPAWN_RATE        (32)
1253 #endif
1254 static int hold_off_on_exponential_spawning;
1255
1256 static void perform_idle_server_maintenance(void)
1257 {
1258     int i, j;
1259     int idle_thread_count;
1260     worker_score *ws;
1261     process_score *ps;
1262     int free_length;
1263     int totally_free_length = 0;
1264     int free_slots[MAX_SPAWN_RATE];
1265     int last_non_dead;
1266     int total_non_dead;
1267
1268     /* initialize the free_list */
1269     free_length = 0;
1270
1271     idle_thread_count = 0;
1272     last_non_dead = -1;
1273     total_non_dead = 0;
1274
1275     ap_sync_scoreboard_image();
1276     for (i = 0; i < ap_daemons_limit; ++i) {
1277         /* Initialization to satisfy the compiler. It doesn't know
1278          * that ap_threads_per_child is always > 0 */
1279         int status = SERVER_DEAD;
1280         int any_dying_threads = 0;
1281         int any_dead_threads = 0;
1282         int all_dead_threads = 1;
1283
1284         if (i >= ap_max_daemons_limit && totally_free_length == idle_spawn_rate)
1285             break;
1286         ps = &ap_scoreboard_image->parent[i];
1287         for (j = 0; j < ap_threads_per_child; j++) {
1288             ws = &ap_scoreboard_image->servers[i][j];
1289             status = ws->status;
1290
1291             /* XXX any_dying_threads is probably no longer needed    GLA */
1292             any_dying_threads = any_dying_threads || 
1293                                 (status == SERVER_GRACEFUL);
1294             any_dead_threads = any_dead_threads || (status == SERVER_DEAD);
1295             all_dead_threads = all_dead_threads &&
1296                                    (status == SERVER_DEAD ||
1297                                     status == SERVER_GRACEFUL);
1298
1299             /* We consider a starting server as idle because we started it
1300              * at least a cycle ago, and if it still hasn't finished starting
1301              * then we're just going to swamp things worse by forking more.
1302              * So we hopefully won't need to fork more if we count it.
1303              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
1304              */
1305             if (status <= SERVER_READY && status != SERVER_DEAD &&
1306                     !ps->quiescing &&
1307                     ps->generation == ap_my_generation &&
1308                  /* XXX the following shouldn't be necessary if we clean up 
1309                   *     properly after seg faults, but we're not yet    GLA 
1310                   */     
1311                     ps->pid != 0) {
1312                 ++idle_thread_count;
1313             }
1314         }
1315         if (any_dead_threads && totally_free_length < idle_spawn_rate 
1316                 && (!ps->pid               /* no process in the slot */
1317                     || ps->quiescing)) {   /* or at least one is going away */
1318             if (all_dead_threads) {
1319                 /* great! we prefer these, because the new process can
1320                  * start more threads sooner.  So prioritize this slot 
1321                  * by putting it ahead of any slots with active threads.
1322                  *
1323                  * first, make room by moving a slot that's potentially still
1324                  * in use to the end of the array
1325                  */
1326                 free_slots[free_length] = free_slots[totally_free_length];
1327                 free_slots[totally_free_length++] = i;
1328             }
1329             else {
1330                 /* slot is still in use - back of the bus
1331                  */
1332             free_slots[free_length] = i;
1333             }
1334             ++free_length;
1335         }
1336         /* XXX if (!ps->quiescing)     is probably more reliable  GLA */
1337         if (!any_dying_threads) {
1338             last_non_dead = i;
1339             ++total_non_dead;
1340         }
1341     }
1342     ap_max_daemons_limit = last_non_dead + 1;
1343
1344     if (idle_thread_count > max_spare_threads) {
1345         /* Kill off one child */
1346         ap_mpm_pod_signal(pod, TRUE);
1347         idle_spawn_rate = 1;
1348     }
1349     else if (idle_thread_count < min_spare_threads) {
1350         /* terminate the free list */
1351         if (free_length == 0) {
1352             /* only report this condition once */
1353             static int reported = 0;
1354             
1355             if (!reported) {
1356                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, 
1357                              ap_server_conf,
1358                              "server reached MaxClients setting, consider"
1359                              " raising the MaxClients setting");
1360                 reported = 1;
1361             }
1362             idle_spawn_rate = 1;
1363         }
1364         else {
1365             if (free_length > idle_spawn_rate) {
1366                 free_length = idle_spawn_rate;
1367             }
1368             if (idle_spawn_rate >= 8) {
1369                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, 
1370                              ap_server_conf,
1371                              "server seems busy, (you may need "
1372                              "to increase StartServers, ThreadsPerChild "
1373                              "or Min/MaxSpareThreads), "
1374                              "spawning %d children, there are around %d idle "
1375                              "threads, and %d total children", free_length,
1376                              idle_thread_count, total_non_dead);
1377             }
1378             for (i = 0; i < free_length; ++i) {
1379                 make_child(ap_server_conf, free_slots[i]);
1380             }
1381             /* the next time around we want to spawn twice as many if this
1382              * wasn't good enough, but not if we've just done a graceful
1383              */
1384             if (hold_off_on_exponential_spawning) {
1385                 --hold_off_on_exponential_spawning;
1386             }
1387             else if (idle_spawn_rate < MAX_SPAWN_RATE) {
1388                 idle_spawn_rate *= 2;
1389             }
1390         }
1391     }
1392     else {
1393       idle_spawn_rate = 1;
1394     }
1395 }
1396
1397 static void server_main_loop(int remaining_children_to_start)
1398 {
1399     int child_slot;
1400     apr_exit_why_e exitwhy;
1401     int status, processed_status;
1402     apr_proc_t pid;
1403     int i;
1404
1405     while (!restart_pending && !shutdown_pending) {
1406         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
1407         
1408         if (pid.pid != -1) {
1409             processed_status = ap_process_child_status(&pid, exitwhy, status);
1410             if (processed_status == APEXIT_CHILDFATAL) {
1411                 shutdown_pending = 1;
1412                 child_fatal = 1;
1413                 return;
1414             }
1415             /* non-fatal death... note that it's gone in the scoreboard. */
1416             child_slot = find_child_by_pid(&pid);
1417             if (child_slot >= 0) {
1418                 for (i = 0; i < ap_threads_per_child; i++)
1419                     ap_update_child_status_from_indexes(child_slot, i, SERVER_DEAD, 
1420                                                         (request_rec *) NULL);
1421                 
1422                 ap_scoreboard_image->parent[child_slot].pid = 0;
1423                 ap_scoreboard_image->parent[child_slot].quiescing = 0;
1424                 if (processed_status == APEXIT_CHILDSICK) {
1425                     /* resource shortage, minimize the fork rate */
1426                     idle_spawn_rate = 1;
1427                 }
1428                 else if (remaining_children_to_start
1429                     && child_slot < ap_daemons_limit) {
1430                     /* we're still doing a 1-for-1 replacement of dead
1431                      * children with new children
1432                      */
1433                     make_child(ap_server_conf, child_slot);
1434                     --remaining_children_to_start;
1435                 }
1436 #if APR_HAS_OTHER_CHILD
1437             }
1438             else if (apr_proc_other_child_read(&pid, status) == 0) {
1439                 /* handled */
1440 #endif
1441             }
1442             else if (is_graceful) {
1443                 /* Great, we've probably just lost a slot in the
1444                  * scoreboard.  Somehow we don't know about this child.
1445                  */
1446                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
1447                              ap_server_conf,
1448                              "long lost child came home! (pid %ld)",
1449                              (long)pid.pid);
1450             }
1451             /* Don't perform idle maintenance when a child dies,
1452              * only do it when there's a timeout.  Remember only a
1453              * finite number of children can die, and it's pretty
1454              * pathological for a lot to die suddenly.
1455              */
1456             continue;
1457         }
1458         else if (remaining_children_to_start) {
1459             /* we hit a 1 second timeout in which none of the previous
1460              * generation of children needed to be reaped... so assume
1461              * they're all done, and pick up the slack if any is left.
1462              */
1463             startup_children(remaining_children_to_start);
1464             remaining_children_to_start = 0;
1465             /* In any event we really shouldn't do the code below because
1466              * few of the servers we just started are in the IDLE state
1467              * yet, so we'd mistakenly create an extra server.
1468              */
1469             continue;
1470         }
1471
1472         perform_idle_server_maintenance();
1473     }
1474 }
1475
1476 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
1477 {
1478     int remaining_children_to_start;
1479     apr_status_t rv;
1480
1481     ap_log_pid(pconf, ap_pid_fname);
1482
1483     first_server_limit = server_limit;
1484     first_thread_limit = thread_limit;
1485     if (changed_limit_at_restart) {
1486         ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, 0, s,
1487                      "WARNING: Attempt to change ServerLimit or ThreadLimit "
1488                      "ignored during restart");
1489         changed_limit_at_restart = 0;
1490     }
1491     
1492     /* Initialize cross-process accept lock */
1493     ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT,
1494                                  ap_server_root_relative(_pconf, ap_lock_fname),
1495                                  ap_my_pid);
1496
1497     rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname, 
1498                                ap_accept_lock_mech, _pconf);
1499     if (rv != APR_SUCCESS) {
1500         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1501                      "Couldn't create accept lock");
1502         return 1;
1503     }
1504
1505 #if APR_USE_SYSVSEM_SERIALIZE
1506     if (ap_accept_lock_mech == APR_LOCK_DEFAULT || 
1507         ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
1508 #else
1509     if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
1510 #endif
1511         rv = unixd_set_proc_mutex_perms(accept_mutex);
1512         if (rv != APR_SUCCESS) {
1513             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1514                          "Couldn't set permissions on cross-process lock");
1515             return 1;
1516         }
1517     }
1518
1519     if (!is_graceful) {
1520         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
1521             return 1;
1522         }
1523         /* fix the generation number in the global score; we just got a new,
1524          * cleared scoreboard
1525          */
1526         ap_scoreboard_image->global->running_generation = ap_my_generation;
1527         update_scoreboard_global();
1528     }
1529
1530     set_signals();
1531     /* Don't thrash... */
1532     if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1533         max_spare_threads = min_spare_threads + ap_threads_per_child;
1534
1535     /* If we're doing a graceful_restart then we're going to see a lot
1536      * of children exiting immediately when we get into the main loop
1537      * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
1538      * rapidly... and for each one that exits we'll start a new one until
1539      * we reach at least daemons_min_free.  But we may be permitted to
1540      * start more than that, so we'll just keep track of how many we're
1541      * supposed to start up without the 1 second penalty between each fork.
1542      */
1543     remaining_children_to_start = ap_daemons_to_start;
1544     if (remaining_children_to_start > ap_daemons_limit) {
1545         remaining_children_to_start = ap_daemons_limit;
1546     }
1547     if (!is_graceful) {
1548         startup_children(remaining_children_to_start);
1549         remaining_children_to_start = 0;
1550     }
1551     else {
1552         /* give the system some time to recover before kicking into
1553             * exponential mode */
1554         hold_off_on_exponential_spawning = 10;
1555     }
1556
1557     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1558                 "%s configured -- resuming normal operations",
1559                 ap_get_server_version());
1560     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1561                 "Server built: %s", ap_get_server_built());
1562 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
1563     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1564                 "AcceptMutex: %s", ap_mpm_show_accept_lock_mech());
1565 #endif
1566     restart_pending = shutdown_pending = 0;
1567
1568     server_main_loop(remaining_children_to_start);
1569
1570     if (shutdown_pending) {
1571         /* Time to gracefully shut down:
1572          * Kill child processes, tell them to call child_exit, etc...
1573          * (By "gracefully" we don't mean graceful in the same sense as 
1574          * "apachectl graceful" where we allow old connections to finish.)
1575          */
1576         ap_mpm_pod_killpg(pod, ap_daemons_limit, FALSE);
1577         ap_reclaim_child_processes(1);                /* Start with SIGTERM */
1578
1579         if (!child_fatal) {
1580             /* cleanup pid file on normal shutdown */
1581             const char *pidfile = NULL;
1582             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1583             if ( pidfile != NULL && unlink(pidfile) == 0)
1584                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1585                              ap_server_conf,
1586                              "removed PID file %s (pid=%ld)",
1587                              pidfile, (long)getpid());
1588     
1589             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0,
1590                          ap_server_conf, "caught SIGTERM, shutting down");
1591         }
1592         return 1;
1593     }
1594
1595     /* we've been told to restart */
1596     apr_signal(SIGHUP, SIG_IGN);
1597
1598     if (one_process) {
1599         /* not worth thinking about */
1600         return 1;
1601     }
1602
1603     /* advance to the next generation */
1604     /* XXX: we really need to make sure this new generation number isn't in
1605      * use by any of the children.
1606      */
1607     ++ap_my_generation;
1608     ap_scoreboard_image->global->running_generation = ap_my_generation;
1609     update_scoreboard_global();
1610     
1611     if (is_graceful) {
1612         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1613                      AP_SIG_GRACEFUL_STRING " received.  Doing graceful restart");
1614         /* wake up the children...time to die.  But we'll have more soon */
1615         ap_mpm_pod_killpg(pod, ap_daemons_limit, TRUE);
1616     
1617
1618         /* This is mostly for debugging... so that we know what is still
1619          * gracefully dealing with existing request.
1620          */
1621         
1622     }
1623     else {
1624         /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
1625          * and a SIGHUP, we may as well use the same signal, because some user
1626          * pthreads are stealing signals from us left and right.
1627          */
1628         ap_mpm_pod_killpg(pod, ap_daemons_limit, FALSE);
1629
1630         ap_reclaim_child_processes(1);                /* Start with SIGTERM */
1631         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1632                     "SIGHUP received.  Attempting to restart");
1633     }
1634
1635     return 0;
1636 }
1637
1638 /* This really should be a post_config hook, but the error log is already
1639  * redirected by that point, so we need to do this in the open_logs phase.
1640  */
1641 static int worker_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1642 {
1643     apr_status_t rv;
1644
1645     pconf = p;
1646     ap_server_conf = s;
1647
1648     if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1649         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT|APLOG_STARTUP, 0,
1650                      NULL, "no listening sockets available, shutting down");
1651         return DONE;
1652     }
1653
1654     if (!one_process) {
1655         if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1656             ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
1657                     "Could not open pipe-of-death.");
1658             return DONE;
1659         }
1660     }
1661     return OK;
1662 }
1663
1664 static int worker_pre_config(apr_pool_t *pconf, apr_pool_t *plog, 
1665                              apr_pool_t *ptemp)
1666 {
1667     static int restart_num = 0;
1668     int no_detach, debug;
1669     ap_directive_t *pdir;
1670     ap_directive_t *max_clients = NULL;
1671     apr_status_t rv;
1672
1673     /* make sure that "ThreadsPerChild" gets set before "MaxClients" */
1674     for (pdir = ap_conftree; pdir != NULL; pdir = pdir->next) {
1675         if (strncasecmp(pdir->directive, "ThreadsPerChild", 15) == 0) {
1676             if (!max_clients) {
1677                 break; /* we're in the clear, got ThreadsPerChild first */
1678             }
1679             else {
1680                 /* now to swap the data */
1681                 ap_directive_t temp;
1682
1683                 temp.directive = pdir->directive;
1684                 temp.args = pdir->args;
1685                 /* Make sure you don't change 'next', or you may get loops! */
1686                 /* XXX: first_child, parent, and data can never be set
1687                  * for these directives, right? -aaron */
1688                 temp.filename = pdir->filename;
1689                 temp.line_num = pdir->line_num;
1690
1691                 pdir->directive = max_clients->directive;
1692                 pdir->args = max_clients->args;
1693                 pdir->filename = max_clients->filename;
1694                 pdir->line_num = max_clients->line_num;
1695                 
1696                 max_clients->directive = temp.directive;
1697                 max_clients->args = temp.args;
1698                 max_clients->filename = temp.filename;
1699                 max_clients->line_num = temp.line_num;
1700                 break;
1701             }
1702         }
1703         else if (!max_clients
1704                  && strncasecmp(pdir->directive, "MaxClients", 10) == 0) {
1705             max_clients = pdir;
1706         }
1707     }
1708
1709     debug = ap_exists_config_define("DEBUG");
1710
1711     if (debug) {
1712         no_detach = one_process = 1;
1713     }
1714     else {
1715         one_process = ap_exists_config_define("ONE_PROCESS");
1716         no_detach = ap_exists_config_define("NO_DETACH");
1717     }
1718
1719     /* sigh, want this only the second time around */
1720     if (restart_num++ == 1) {
1721         is_graceful = 0;
1722
1723         if (!one_process) {
1724             rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1725                                            : APR_PROC_DETACH_DAEMONIZE);
1726             if (rv != APR_SUCCESS) {
1727                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1728                              "apr_proc_detach failed");
1729                 return HTTP_INTERNAL_SERVER_ERROR;
1730             }
1731         }
1732         parent_pid = ap_my_pid = getpid();
1733     }
1734
1735     unixd_pre_config(ptemp);
1736     ap_listen_pre_config();
1737     ap_daemons_to_start = DEFAULT_START_DAEMON;
1738     min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1739     max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1740     ap_daemons_limit = server_limit;
1741     ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1742     ap_pid_fname = DEFAULT_PIDLOG;
1743     ap_lock_fname = DEFAULT_LOCKFILE;
1744     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1745     ap_extended_status = 0;
1746
1747     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1748
1749     return OK;
1750 }
1751
1752 static void worker_hooks(apr_pool_t *p)
1753 {
1754     /* The worker open_logs phase must run before the core's, or stderr
1755      * will be redirected to a file, and the messages won't print to the
1756      * console.
1757      */
1758     static const char *const aszSucc[] = {"core.c", NULL};
1759     one_process = 0;
1760
1761     ap_hook_open_logs(worker_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
1762     ap_hook_pre_config(worker_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1763 }
1764
1765 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy,
1766                                         const char *arg) 
1767 {
1768     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1769     if (err != NULL) {
1770         return err;
1771     }
1772
1773     ap_daemons_to_start = atoi(arg);
1774     return NULL;
1775 }
1776
1777 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy,
1778                                          const char *arg)
1779 {
1780     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1781     if (err != NULL) {
1782         return err;
1783     }
1784
1785     min_spare_threads = atoi(arg);
1786     if (min_spare_threads <= 0) {
1787        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1788                     "WARNING: detected MinSpareThreads set to non-positive.");
1789        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1790                     "Resetting to 1 to avoid almost certain Apache failure.");
1791        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1792                     "Please read the documentation.");
1793        min_spare_threads = 1;
1794     }
1795        
1796     return NULL;
1797 }
1798
1799 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy,
1800                                          const char *arg)
1801 {
1802     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1803     if (err != NULL) {
1804         return err;
1805     }
1806
1807     max_spare_threads = atoi(arg);
1808     return NULL;
1809 }
1810
1811 static const char *set_max_clients (cmd_parms *cmd, void *dummy,
1812                                      const char *arg) 
1813 {
1814     int max_clients;
1815     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1816     if (err != NULL) {
1817         return err;
1818     }
1819
1820     /* It is ok to use ap_threads_per_child here because we are
1821      * sure that it gets set before MaxClients in the pre_config stage. */
1822     max_clients = atoi(arg);
1823     if (max_clients < ap_threads_per_child) {
1824        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1825                     "WARNING: MaxClients (%d) must be at least as large",
1826                     max_clients);
1827        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1828                     " large as ThreadsPerChild (%d). Automatically",
1829                     ap_threads_per_child);
1830        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1831                     " increasing MaxClients to %d.",
1832                     ap_threads_per_child);
1833        max_clients = ap_threads_per_child;
1834     }
1835     ap_daemons_limit = max_clients / ap_threads_per_child;
1836     if ((max_clients > 0) && (max_clients % ap_threads_per_child)) {
1837        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1838                     "WARNING: MaxClients (%d) is not an integer multiple",
1839                     max_clients);
1840        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1841                     " of ThreadsPerChild (%d), lowering MaxClients to %d",
1842                     ap_threads_per_child,
1843                     ap_daemons_limit * ap_threads_per_child);
1844        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1845                     " for a maximum of %d child processes,",
1846                     ap_daemons_limit);
1847        max_clients = ap_daemons_limit * ap_threads_per_child; 
1848     }
1849     if (ap_daemons_limit > server_limit) {
1850        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1851                     "WARNING: MaxClients of %d would require %d servers,",
1852                     max_clients, ap_daemons_limit);
1853        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1854                     " and would exceed the ServerLimit value of %d.",
1855                     server_limit);
1856        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1857                     " Automatically lowering MaxClients to %d.  To increase,",
1858                     server_limit);
1859        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1860                     " please see the ServerLimit directive.");
1861        ap_daemons_limit = server_limit;
1862     } 
1863     else if (ap_daemons_limit < 1) {
1864         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1865                      "WARNING: Require MaxClients > 0, setting to 1");
1866         ap_daemons_limit = 1;
1867     }
1868     return NULL;
1869 }
1870
1871 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy,
1872                                           const char *arg) 
1873 {
1874     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1875     if (err != NULL) {
1876         return err;
1877     }
1878
1879     ap_threads_per_child = atoi(arg);
1880     if (ap_threads_per_child > thread_limit) {
1881         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1882                      "WARNING: ThreadsPerChild of %d exceeds ThreadLimit "
1883                      "value of %d", ap_threads_per_child,
1884                      thread_limit);
1885         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1886                      "threads, lowering ThreadsPerChild to %d. To increase, please"
1887                      " see the", thread_limit);
1888         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1889                      " ThreadLimit directive.");
1890         ap_threads_per_child = thread_limit;
1891     }
1892     else if (ap_threads_per_child < 1) {
1893         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1894                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1895         ap_threads_per_child = 1;
1896     }
1897     return NULL;
1898 }
1899
1900 static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg) 
1901 {
1902     int tmp_server_limit;
1903     
1904     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1905     if (err != NULL) {
1906         return err;
1907     }
1908
1909     tmp_server_limit = atoi(arg);
1910     /* you cannot change ServerLimit across a restart; ignore
1911      * any such attempts
1912      */
1913     if (first_server_limit &&
1914         tmp_server_limit != server_limit) {
1915         /* how do we log a message?  the error log is a bit bucket at this
1916          * point; we'll just have to set a flag so that ap_mpm_run()
1917          * logs a warning later
1918          */
1919         changed_limit_at_restart = 1;
1920         return NULL;
1921     }
1922     server_limit = tmp_server_limit;
1923     
1924     if (server_limit > MAX_SERVER_LIMIT) {
1925        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1926                     "WARNING: ServerLimit of %d exceeds compile time limit "
1927                     "of %d servers,", server_limit, MAX_SERVER_LIMIT);
1928        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1929                     " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
1930        server_limit = MAX_SERVER_LIMIT;
1931     } 
1932     else if (server_limit < 1) {
1933         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1934                      "WARNING: Require ServerLimit > 0, setting to 1");
1935         server_limit = 1;
1936     }
1937     return NULL;
1938 }
1939
1940 static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg) 
1941 {
1942     int tmp_thread_limit;
1943     
1944     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1945     if (err != NULL) {
1946         return err;
1947     }
1948
1949     tmp_thread_limit = atoi(arg);
1950     /* you cannot change ThreadLimit across a restart; ignore
1951      * any such attempts
1952      */
1953     if (first_thread_limit &&
1954         tmp_thread_limit != thread_limit) {
1955         /* how do we log a message?  the error log is a bit bucket at this
1956          * point; we'll just have to set a flag so that ap_mpm_run()
1957          * logs a warning later
1958          */
1959         changed_limit_at_restart = 1;
1960         return NULL;
1961     }
1962     thread_limit = tmp_thread_limit;
1963     
1964     if (thread_limit > MAX_THREAD_LIMIT) {
1965        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1966                     "WARNING: ThreadLimit of %d exceeds compile time limit "
1967                     "of %d servers,", thread_limit, MAX_THREAD_LIMIT);
1968        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1969                     " lowering ThreadLimit to %d.", MAX_THREAD_LIMIT);
1970        thread_limit = MAX_THREAD_LIMIT;
1971     } 
1972     else if (thread_limit < 1) {
1973         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1974                      "WARNING: Require ThreadLimit > 0, setting to 1");
1975         thread_limit = 1;
1976     }
1977     return NULL;
1978 }
1979
1980 static const command_rec worker_cmds[] = {
1981 UNIX_DAEMON_COMMANDS,
1982 LISTEN_COMMANDS,
1983 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1984   "Number of child processes launched at server startup"),
1985 AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1986   "Minimum number of idle children, to handle request spikes"),
1987 AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1988   "Maximum number of idle children"),
1989 AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1990   "Maximum number of children alive at the same time"),
1991 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
1992   "Number of threads each child creates"),
1993 AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1994   "Maximum value of MaxClients for this run of Apache"),
1995 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
1996   "Maximum worker threads in a server for this run of Apache"),
1997 { NULL }
1998 };
1999
2000 module AP_MODULE_DECLARE_DATA mpm_worker_module = {
2001     MPM20_MODULE_STUFF,
2002     NULL,                       /* hook to run before apache parses args */
2003     NULL,                       /* create per-directory config structure */
2004     NULL,                       /* merge per-directory config structures */
2005     NULL,                       /* create per-server config structure */
2006     NULL,                       /* merge per-server config structures */
2007     worker_cmds,                /* command apr_table_t */
2008     worker_hooks                /* register_hooks */
2009 };
2010