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