]> granicus.if.org Git - apache/blob - server/mpm/prefork/prefork.c
Implement apr_proc_detach changes and allow -DNO_DETACH in the multi-process
[apache] / server / mpm / prefork / prefork.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 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 #include "apr.h"
60 #include "apr_portable.h"
61 #include "apr_strings.h"
62 #include "apr_thread_proc.h"
63 #include "apr_signal.h"
64
65 #define APR_WANT_STDIO
66 #define APR_WANT_STRFUNC
67 #include "apr_want.h"
68
69 #if APR_HAVE_UNISTD_H
70 #include <unistd.h>
71 #endif
72 #if APR_HAVE_SYS_TYPES_H
73 #include <sys/types.h>
74 #endif
75
76 #define CORE_PRIVATE
77
78 #include "ap_config.h"
79 #include "httpd.h"
80 #include "mpm_default.h"
81 #include "http_main.h"
82 #include "http_log.h"
83 #include "http_config.h"
84 #include "http_core.h"          /* for get_remote_host */
85 #include "http_connection.h"
86 #include "scoreboard.h"
87 #include "ap_mpm.h"
88 #include "unixd.h"
89 #include "mpm_common.h"
90 #include "ap_listen.h"
91 #include "ap_mmn.h"
92
93 #ifdef HAVE_BSTRING_H
94 #include <bstring.h>            /* for IRIX, FD_SET calls bzero() */
95 #endif
96 #ifdef HAVE_TIME_H
97 #include <time.h>
98 #endif
99 #ifdef HAVE_SYS_PROCESSOR_H
100 #include <sys/processor.h> /* for bindprocessor() */
101 #endif
102
103 #include <signal.h>
104 #include <sys/times.h>
105
106 /* Limit on the total --- clients will be locked out if more servers than
107  * this are needed.  It is intended solely to keep the server from crashing
108  * when things get out of hand.
109  *
110  * We keep a hard maximum number of servers, for two reasons --- first off,
111  * in case something goes seriously wrong, we want to stop the fork bomb
112  * short of actually crashing the machine we're running on by filling some
113  * kernel table.  Secondly, it keeps the size of the scoreboard file small
114  * enough that we can read the whole thing without worrying too much about
115  * the overhead.
116  */
117 #ifndef DEFAULT_SERVER_LIMIT
118 #define DEFAULT_SERVER_LIMIT 256
119 #endif
120
121 /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT.  We want
122  * some sort of compile-time limit to help catch typos.
123  */
124 #ifndef MAX_SERVER_LIMIT
125 #define MAX_SERVER_LIMIT 20000
126 #endif
127
128 #ifndef HARD_THREAD_LIMIT
129 #define HARD_THREAD_LIMIT 1
130 #endif
131
132 /* config globals */
133
134 int ap_threads_per_child=0;         /* Worker threads per child */
135 static apr_proc_mutex_t *accept_mutex;
136 static int ap_daemons_to_start=0;
137 static int ap_daemons_min_free=0;
138 static int ap_daemons_max_free=0;
139 static int ap_daemons_limit=0;      /* MaxClients */
140 static int server_limit = DEFAULT_SERVER_LIMIT;
141 static int first_server_limit;
142 static int changed_limit_at_restart;
143
144 static ap_pod_t *pod;
145
146 /*
147  * The max child slot ever assigned, preserved across restarts.  Necessary
148  * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We 
149  * use this value to optimize routines that have to scan the entire scoreboard.
150  */
151 int ap_max_daemons_limit = -1;
152 server_rec *ap_server_conf;
153
154 /* one_process --- debugging mode variable; can be set from the command line
155  * with the -X flag.  If set, this gets you the child_main loop running
156  * in the process which originally started up (no detach, no make_child),
157  * which is a pretty nice debugging environment.  (You'll get a SIGHUP
158  * early in standalone_main; just continue through.  This is the server
159  * trying to kill off any child processes which it might have lying
160  * around --- Apache doesn't keep track of their pids, it just sends
161  * SIGHUP to the process group, ignoring it in the root process.
162  * Continue through and you'll be fine.).
163  */
164
165 static int one_process = 0;
166
167 static apr_pool_t *pconf;               /* Pool for config stuff */
168 static apr_pool_t *pchild;              /* Pool for httpd child stuff */
169
170 static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
171 static pid_t parent_pid;
172 #ifndef MULTITHREAD
173 static int my_child_num;
174 #endif
175
176 #ifdef TPF
177 int tpf_child = 0;
178 char tpf_server_name[INETD_SERVNAME_LENGTH+1];
179 #endif /* TPF */
180
181 static int die_now = 0;
182
183 #ifdef GPROF
184 /* 
185  * change directory for gprof to plop the gmon.out file
186  * configure in httpd.conf:
187  * GprofDir logs/   -> $ServerRoot/logs/gmon.out
188  * GprofDir logs/%  -> $ServerRoot/logs/gprof.$pid/gmon.out
189  */
190 static void chdir_for_gprof(void)
191 {
192     core_server_config *sconf = 
193         ap_get_module_config(ap_server_conf->module_config, &core_module);    
194     char *dir = sconf->gprof_dir;
195     const char *use_dir;
196
197     if(dir) {
198         apr_status_t res;
199         char buf[512];
200         int len = strlen(sconf->gprof_dir) - 1;
201         if(*(dir + len) == '%') {
202             dir[len] = '\0';
203             apr_snprintf(buf, sizeof(buf), "%sgprof.%d", dir, (int)getpid());
204         } 
205         use_dir = ap_server_root_relative(pconf, buf[0] ? buf : dir);
206         res = apr_dir_make(use_dir, 0755, pconf);
207         if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
208             ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
209                          "gprof: error creating directory %s", dir);
210         }
211     }
212     else {
213         use_dir = ap_server_root_relative(pconf, "logs");
214     }
215
216     chdir(use_dir);
217 }
218 #else
219 #define chdir_for_gprof()
220 #endif
221
222 /* XXX - I don't know if TPF will ever use this module or not, so leave
223  * the ap_check_signals calls in but disable them - manoj */
224 #define ap_check_signals() 
225
226 /* a clean exit from a child with proper cleanup */
227 static void clean_child_exit(int code) __attribute__ ((noreturn));
228 static void clean_child_exit(int code)
229 {
230     if (pchild) {
231         apr_pool_destroy(pchild);
232     }
233     ap_mpm_pod_close(pod);
234     chdir_for_gprof();
235     exit(code);
236 }
237
238 static void accept_mutex_on(void)
239 {
240     apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
241     if (rv != APR_SUCCESS) {
242         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "couldn't grab the accept mutex");
243         exit(APEXIT_CHILDFATAL);
244     }
245 }
246
247 static void accept_mutex_off(void)
248 {
249     apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
250     if (rv != APR_SUCCESS) {
251         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "couldn't release the accept mutex");
252         exit(APEXIT_CHILDFATAL);
253     }
254 }
255
256 /* On some architectures it's safe to do unserialized accept()s in the single
257  * Listen case.  But it's never safe to do it in the case where there's
258  * multiple Listen statements.  Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
259  * when it's safe in the single Listen case.
260  */
261 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
262 #define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
263 #else
264 #define SAFE_ACCEPT(stmt) do {stmt;} while(0)
265 #endif
266
267 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
268 {
269     switch(query_code){
270         case AP_MPMQ_MAX_DAEMON_USED:
271             *result = ap_daemons_limit;
272             return APR_SUCCESS;
273         case AP_MPMQ_IS_THREADED:
274             *result = AP_MPMQ_NOT_SUPPORTED;
275             return APR_SUCCESS;
276         case AP_MPMQ_IS_FORKED:
277             *result = AP_MPMQ_DYNAMIC;
278             return APR_SUCCESS;
279         case AP_MPMQ_HARD_LIMIT_DAEMONS:
280             *result = server_limit;
281             return APR_SUCCESS;
282         case AP_MPMQ_HARD_LIMIT_THREADS:
283             *result = HARD_THREAD_LIMIT;
284             return APR_SUCCESS;
285         case AP_MPMQ_MAX_THREADS:
286             *result = 0;
287             return APR_SUCCESS;
288         case AP_MPMQ_MIN_SPARE_DAEMONS:
289             *result = ap_daemons_min_free;
290             return APR_SUCCESS;
291         case AP_MPMQ_MIN_SPARE_THREADS:
292             *result = 0;
293             return APR_SUCCESS;
294         case AP_MPMQ_MAX_SPARE_DAEMONS:
295             *result = ap_daemons_max_free;
296             return APR_SUCCESS;
297         case AP_MPMQ_MAX_SPARE_THREADS:
298             *result = 0;
299             return APR_SUCCESS;
300         case AP_MPMQ_MAX_REQUESTS_DAEMON:
301             *result = ap_max_requests_per_child;
302             return APR_SUCCESS;
303         case AP_MPMQ_MAX_DAEMONS:
304             *result = ap_daemons_limit;
305             return APR_SUCCESS;
306     }
307     return APR_ENOTIMPL;
308 }
309
310 #if defined(NEED_WAITPID)
311 /*
312    Systems without a real waitpid sometimes lose a child's exit while waiting
313    for another.  Search through the scoreboard for missing children.
314  */
315 int reap_children(int *exitcode, apr_exit_why_e *status)
316 {
317     int n, pid;
318
319     for (n = 0; n < ap_max_daemons_limit; ++n) {
320         ap_sync_scoreboard_image();
321         if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
322                 kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
323             ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
324             /* just mark it as having a successful exit status */
325             *status = APR_PROC_EXIT;
326             *exitcode = 0;
327             return(pid);
328         }
329     }
330     return 0;
331 }
332 #endif
333
334 /* handle all varieties of core dumping signals */
335 static void sig_coredump(int sig)
336 {
337     chdir(ap_coredump_dir);
338     apr_signal(sig, SIG_DFL);
339     if (ap_my_pid == parent_pid) {
340             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
341                          0, ap_server_conf,
342                          "seg fault or similar nasty error detected "
343                          "in the parent process");
344     }
345     kill(getpid(), sig);
346     /* At this point we've got sig blocked, because we're still inside
347      * the signal handler.  When we leave the signal handler it will
348      * be unblocked, and we'll take the signal... and coredump or whatever
349      * is appropriate for this particular Unix.  In addition the parent
350      * will see the real signal we received -- whereas if we called
351      * abort() here, the parent would only see SIGABRT.
352      */
353 }
354
355 /*****************************************************************
356  * Connection structures and accounting...
357  */
358
359 static void just_die(int sig)
360 {
361     clean_child_exit(0);
362 }
363
364 /* volatile just in case */
365 static int volatile shutdown_pending;
366 static int volatile restart_pending;
367 static int volatile is_graceful;
368 ap_generation_t volatile ap_my_generation=0;
369
370 static void sig_term(int sig)
371 {
372     if (shutdown_pending == 1) {
373         /* Um, is this _probably_ not an error, if the user has
374          * tried to do a shutdown twice quickly, so we won't
375          * worry about reporting it.
376          */
377         return;
378     }
379     shutdown_pending = 1;
380 }
381
382 /* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
383  * in the parent process, unless running in ONE_PROCESS mode
384  */
385 static void restart(int sig)
386 {
387     if (restart_pending == 1) {
388         /* Probably not an error - don't bother reporting it */
389         return;
390     }
391     restart_pending = 1;
392     if ((is_graceful = (sig == AP_SIG_GRACEFUL))) {
393         apr_pool_cleanup_kill(pconf, NULL, ap_cleanup_scoreboard);
394     }
395 }
396
397 static void set_signals(void)
398 {
399 #ifndef NO_USE_SIGACTION
400     struct sigaction sa;
401
402     sigemptyset(&sa.sa_mask);
403     sa.sa_flags = 0;
404
405     if (!one_process) {
406         sa.sa_handler = sig_coredump;
407 #if defined(SA_ONESHOT)
408         sa.sa_flags = SA_ONESHOT;
409 #elif defined(SA_RESETHAND)
410         sa.sa_flags = SA_RESETHAND;
411 #endif
412         if (sigaction(SIGSEGV, &sa, NULL) < 0)
413             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
414 #ifdef SIGBUS
415         if (sigaction(SIGBUS, &sa, NULL) < 0)
416             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
417 #endif
418 #ifdef SIGABORT
419         if (sigaction(SIGABORT, &sa, NULL) < 0)
420             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
421 #endif
422 #ifdef SIGABRT
423         if (sigaction(SIGABRT, &sa, NULL) < 0)
424             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
425 #endif
426 #ifdef SIGILL
427         if (sigaction(SIGILL, &sa, NULL) < 0)
428             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
429 #endif
430         sa.sa_flags = 0;
431     }
432     sa.sa_handler = sig_term;
433     if (sigaction(SIGTERM, &sa, NULL) < 0)
434         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
435 #ifdef SIGINT
436     if (sigaction(SIGINT, &sa, NULL) < 0)
437         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
438 #endif
439 #ifdef SIGXCPU
440     sa.sa_handler = SIG_DFL;
441     if (sigaction(SIGXCPU, &sa, NULL) < 0)
442         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
443 #endif
444 #ifdef SIGXFSZ
445     sa.sa_handler = SIG_DFL;
446     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
447         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
448 #endif
449 #ifdef SIGPIPE
450     sa.sa_handler = SIG_IGN;
451     if (sigaction(SIGPIPE, &sa, NULL) < 0)
452         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
453 #endif
454
455     /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy 
456      * processing one */
457     sigaddset(&sa.sa_mask, SIGHUP);
458     sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
459     sa.sa_handler = restart;
460     if (sigaction(SIGHUP, &sa, NULL) < 0)
461         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
462     if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
463         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
464 #else
465     if (!one_process) {
466         apr_signal(SIGSEGV, sig_coredump);
467 #ifdef SIGBUS
468         apr_signal(SIGBUS, sig_coredump);
469 #endif /* SIGBUS */
470 #ifdef SIGABORT
471         apr_signal(SIGABORT, sig_coredump);
472 #endif /* SIGABORT */
473 #ifdef SIGABRT
474         apr_signal(SIGABRT, sig_coredump);
475 #endif /* SIGABRT */
476 #ifdef SIGILL
477         apr_signal(SIGILL, sig_coredump);
478 #endif /* SIGILL */
479 #ifdef SIGXCPU
480         apr_signal(SIGXCPU, SIG_DFL);
481 #endif /* SIGXCPU */
482 #ifdef SIGXFSZ
483         apr_signal(SIGXFSZ, SIG_DFL);
484 #endif /* SIGXFSZ */
485     }
486
487     apr_signal(SIGTERM, sig_term);
488 #ifdef SIGHUP
489     apr_signal(SIGHUP, restart);
490 #endif /* SIGHUP */
491 #ifdef AP_SIG_GRACEFUL
492     apr_signal(AP_SIG_GRACEFUL, restart);
493 #endif /* AP_SIG_GRACEFUL */
494 #ifdef SIGPIPE
495     apr_signal(SIGPIPE, SIG_IGN);
496 #endif /* SIGPIPE */
497
498 #endif
499 }
500
501 /*****************************************************************
502  * Child process main loop.
503  * The following vars are static to avoid getting clobbered by longjmp();
504  * they are really private to child_main.
505  */
506
507 static int requests_this_child;
508 static int num_listensocks = 0;
509 static ap_listen_rec *listensocks;
510
511 int ap_graceful_stop_signalled(void)
512 {
513     /* not ever called anymore... */
514     return 0;
515 }
516
517
518 static void child_main(int child_num_arg)
519 {
520     apr_pool_t *ptrans;
521     conn_rec *current_conn;
522     apr_status_t status = APR_EINIT;
523     int i;
524     ap_listen_rec *lr;
525     int curr_pollfd, last_pollfd = 0;
526     apr_pollfd_t *pollset;
527     int offset;
528     void *csd;
529     ap_sb_handle_t *sbh;
530     apr_status_t rv;
531
532     my_child_num = child_num_arg;
533     ap_my_pid = getpid();
534     csd = NULL;
535     requests_this_child = 0;
536
537     /* Get a sub context for global allocations in this child, so that
538      * we can have cleanups occur when the child exits.
539      */
540     apr_pool_create_ex(&pchild, pconf, NULL, APR_POOL_FNEW_ALLOCATOR);
541
542     apr_pool_create(&ptrans, pchild);
543     apr_pool_tag(ptrans, "transaction");
544
545     /* needs to be done before we switch UIDs so we have permissions */
546     ap_reopen_scoreboard(pchild, NULL, 0);
547     rv = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
548     if (rv != APR_SUCCESS) {
549         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
550                      "Couldn't initialize cross-process lock in child");
551         clean_child_exit(APEXIT_CHILDFATAL);
552     }
553
554     if (unixd_setup_child()) {
555         clean_child_exit(APEXIT_CHILDFATAL);
556     }
557
558     ap_run_child_init(pchild, ap_server_conf);
559
560     ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
561
562     (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
563
564     ap_sync_scoreboard_image();
565
566     /* Set up the pollfd array */
567     listensocks = apr_pcalloc(pchild,
568                             sizeof(*listensocks) * (num_listensocks));
569     for (lr = ap_listeners, i = 0; i < num_listensocks; lr = lr->next, i++) {
570         listensocks[i].accept_func = lr->accept_func;
571         listensocks[i].sd = lr->sd;
572     }
573
574     apr_poll_setup(&pollset, num_listensocks, pchild);
575     for (i = 0; i < num_listensocks; i++)
576         apr_poll_socket_add(pollset, listensocks[i].sd, APR_POLLIN);
577
578     while (!die_now) {
579         /*
580          * (Re)initialize this child to a pre-connection state.
581          */
582
583         current_conn = NULL;
584
585         apr_pool_clear(ptrans);
586
587         if ((ap_max_requests_per_child > 0
588              && requests_this_child++ >= ap_max_requests_per_child)) {
589             clean_child_exit(0);
590         }
591
592         (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
593
594         /*
595          * Wait for an acceptable connection to arrive.
596          */
597
598         /* Lock around "accept", if necessary */
599         SAFE_ACCEPT(accept_mutex_on());
600
601         if (num_listensocks == 1) {
602             offset = 0;
603         }
604         else {
605             /* multiple listening sockets - need to poll */
606             for (;;) {
607                 apr_status_t ret;
608                 apr_int16_t event;
609                 apr_int32_t n;
610
611                 ret = apr_poll(pollset, &n, -1);
612                 if (ret != APR_SUCCESS) {
613                     if (APR_STATUS_IS_EINTR(ret)) {
614                         continue;
615                     }
616                     /* Single Unix documents select as returning errnos
617                      * EBADF, EINTR, and EINVAL... and in none of those
618                      * cases does it make sense to continue.  In fact
619                      * on Linux 2.0.x we seem to end up with EFAULT
620                      * occasionally, and we'd loop forever due to it.
621                      */
622                     ap_log_error(APLOG_MARK, APLOG_ERR, ret, ap_server_conf,
623                              "apr_poll: (listen)");
624                     clean_child_exit(1);
625                 }
626                 /* find a listener */
627                 curr_pollfd = last_pollfd;
628                 do {
629                     curr_pollfd++;
630                     if (curr_pollfd >= num_listensocks) {
631                         curr_pollfd = 0;
632                     }
633                     /* XXX: Should we check for POLLERR? */
634                     apr_poll_revents_get(&event, listensocks[curr_pollfd].sd, pollset);
635                     if (event & APR_POLLIN) {
636                         last_pollfd = curr_pollfd;
637                         offset = curr_pollfd;
638                         goto got_fd;
639                     }
640                 } while (curr_pollfd != last_pollfd);
641
642                 continue;
643             }
644         }
645     got_fd:
646         /* if we accept() something we don't want to die, so we have to
647          * defer the exit
648          */
649         for (;;) {
650             ap_sync_scoreboard_image();
651             status = listensocks[offset].accept_func(&csd, 
652                                        &listensocks[offset], ptrans);
653
654             if (status == APR_SUCCESS) {
655                 break;
656             }
657             if (status == APR_EGENERAL) {
658                 /* resource shortage or should-not-occur occured */
659                 clean_child_exit(1);
660             }
661         }
662         SAFE_ACCEPT(accept_mutex_off());        /* unlock after "accept" */
663
664         /*
665          * We now have a connection, so set it up with the appropriate
666          * socket options, file descriptors, and read/write buffers.
667          */
668
669         current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh);
670         if (current_conn) {
671             ap_process_connection(current_conn, csd);
672             ap_lingering_close(current_conn);
673         }
674         
675         /* Check the pod after processing a connection so that we'll go away
676          * if a graceful restart occurred while we were processing the 
677          * connection.  Otherwise, we won't wake up until a real connection 
678          * comes in and we'll use the wrong config to process it and we may
679          * block in the wrong syscall (because the new generation is using a
680          * different accept mutex) and in general it is goofy.
681          */
682         if (!ap_mpm_pod_check(pod)) {
683             die_now = 1;
684         }
685         ap_sync_scoreboard_image();
686     }
687     clean_child_exit(0);
688 }
689
690
691 static int make_child(server_rec *s, int slot)
692 {
693     int pid;
694
695     if (slot + 1 > ap_max_daemons_limit) {
696         ap_max_daemons_limit = slot + 1;
697     }
698
699     if (one_process) {
700         apr_signal(SIGHUP, just_die);
701         /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
702         apr_signal(SIGINT, just_die);
703 #ifdef SIGQUIT
704         apr_signal(SIGQUIT, SIG_DFL);
705 #endif
706         apr_signal(SIGTERM, just_die);
707         child_main(slot);
708     }
709
710     (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
711                                                (request_rec *) NULL);
712
713
714 #ifdef _OSD_POSIX
715     /* BS2000 requires a "special" version of fork() before a setuid() call */
716     if ((pid = os_fork(unixd_config.user_name)) == -1) {
717 #elif defined(TPF)
718     if ((pid = os_fork(s, slot)) == -1) {
719 #else
720     if ((pid = fork()) == -1) {
721 #endif
722         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
723
724         /* fork didn't succeed. Fix the scoreboard or else
725          * it will say SERVER_STARTING forever and ever
726          */
727         (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
728                                                    (request_rec *) NULL);
729
730         /* In case system resources are maxxed out, we don't want
731            Apache running away with the CPU trying to fork over and
732            over and over again. */
733         sleep(10);
734
735         return -1;
736     }
737
738     if (!pid) {
739 #ifdef HAVE_BINDPROCESSOR
740         /* by default AIX binds to a single processor
741          * this bit unbinds children which will then bind to another cpu
742          */
743         int status = bindprocessor(BINDPROCESS, (int)getpid(), 
744                                    PROCESSOR_CLASS_ANY);
745         if (status != OK) {
746             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, errno, 
747                          ap_server_conf, "processor unbind failed %d", status);
748         }
749 #endif
750         RAISE_SIGSTOP(MAKE_CHILD);
751         AP_MONCONTROL(1);
752         /* Disable the parent's signal handlers and set up proper handling in
753          * the child.
754          */
755         apr_signal(SIGHUP, just_die);
756         apr_signal(SIGTERM, just_die);
757         /* The child process doesn't do anything for AP_SIG_GRACEFUL.  
758          * Instead, the pod is used for signalling graceful restart.
759          */
760         apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
761         child_main(slot);
762     }
763
764     ap_scoreboard_image->parent[slot].pid = pid;
765 #ifdef SCOREBOARD_FILE
766     lseek(scoreboard_fd, APR_XtOffsetOf(scoreboard, parent[slot]), 0);
767     force_write(scoreboard_fd, &ap_scoreboard_image->parent[slot],
768                 sizeof(process_score));
769 #endif
770
771     return 0;
772 }
773
774
775 /* start up a bunch of children */
776 static void startup_children(int number_to_start)
777 {
778     int i;
779
780     for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
781         if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
782             continue;
783         }
784         if (make_child(ap_server_conf, i) < 0) {
785             break;
786         }
787         --number_to_start;
788     }
789 }
790
791
792 /*
793  * idle_spawn_rate is the number of children that will be spawned on the
794  * next maintenance cycle if there aren't enough idle servers.  It is
795  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
796  * without the need to spawn.
797  */
798 static int idle_spawn_rate = 1;
799 #ifndef MAX_SPAWN_RATE
800 #define MAX_SPAWN_RATE  (32)
801 #endif
802 static int hold_off_on_exponential_spawning;
803
804 static void perform_idle_server_maintenance(apr_pool_t *p)
805 {
806     int i;
807     int to_kill;
808     int idle_count;
809     worker_score *ws;
810     int free_length;
811     int free_slots[MAX_SPAWN_RATE];
812     int last_non_dead;
813     int total_non_dead;
814
815     /* initialize the free_list */
816     free_length = 0;
817
818     to_kill = -1;
819     idle_count = 0;
820     last_non_dead = -1;
821     total_non_dead = 0;
822
823     ap_sync_scoreboard_image();
824     for (i = 0; i < ap_daemons_limit; ++i) {
825         int status;
826
827         if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
828             break;
829         ws = &ap_scoreboard_image->servers[i][0];
830         status = ws->status;
831         if (status == SERVER_DEAD) {
832             /* try to keep children numbers as low as possible */
833             if (free_length < idle_spawn_rate) {
834                 free_slots[free_length] = i;
835                 ++free_length;
836             }
837         }
838         else {
839             /* We consider a starting server as idle because we started it
840              * at least a cycle ago, and if it still hasn't finished starting
841              * then we're just going to swamp things worse by forking more.
842              * So we hopefully won't need to fork more if we count it.
843              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
844              */
845             if (status <= SERVER_READY) {
846                 ++ idle_count;
847                 /* always kill the highest numbered child if we have to...
848                  * no really well thought out reason ... other than observing
849                  * the server behaviour under linux where lower numbered children
850                  * tend to service more hits (and hence are more likely to have
851                  * their data in cpu caches).
852                  */
853                 to_kill = i;
854             }
855
856             ++total_non_dead;
857             last_non_dead = i;
858         }
859     }
860     ap_max_daemons_limit = last_non_dead + 1;
861     if (idle_count > ap_daemons_max_free) {
862         /* kill off one child... we use the pod because that'll cause it to
863          * shut down gracefully, in case it happened to pick up a request
864          * while we were counting
865          */
866         ap_mpm_pod_signal(pod);
867         idle_spawn_rate = 1;
868     }
869     else if (idle_count < ap_daemons_min_free) {
870         /* terminate the free list */
871         if (free_length == 0) {
872             /* only report this condition once */
873             static int reported = 0;
874
875             if (!reported) {
876                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
877                             "server reached MaxClients setting, consider"
878                             " raising the MaxClients setting");
879                 reported = 1;
880             }
881             idle_spawn_rate = 1;
882         }
883         else {
884             if (idle_spawn_rate >= 8) {
885                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
886                     "server seems busy, (you may need "
887                     "to increase StartServers, or Min/MaxSpareServers), "
888                     "spawning %d children, there are %d idle, and "
889                     "%d total children", idle_spawn_rate,
890                     idle_count, total_non_dead);
891             }
892             for (i = 0; i < free_length; ++i) {
893 #ifdef TPF
894         if (make_child(ap_server_conf, free_slots[i]) == -1) {
895             if(free_length == 1) {
896                 shutdown_pending = 1;
897                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, 0, ap_server_conf,
898                 "No active child processes: shutting down");
899             }
900         }
901 #else
902                 make_child(ap_server_conf, free_slots[i]);
903 #endif /* TPF */
904             }
905             /* the next time around we want to spawn twice as many if this
906              * wasn't good enough, but not if we've just done a graceful
907              */
908             if (hold_off_on_exponential_spawning) {
909                 --hold_off_on_exponential_spawning;
910             }
911             else if (idle_spawn_rate < MAX_SPAWN_RATE) {
912                 idle_spawn_rate *= 2;
913             }
914         }
915     }
916     else {
917         idle_spawn_rate = 1;
918     }
919 }
920
921 /*****************************************************************
922  * Executive routines.
923  */
924
925 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
926 {
927     int index;
928     int remaining_children_to_start;
929     apr_status_t rv;
930
931     ap_log_pid(pconf, ap_pid_fname);
932
933     first_server_limit = server_limit;
934     if (changed_limit_at_restart) {
935         ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, 0, s,
936                      "WARNING: Attempt to change ServerLimit "
937                      "ignored during restart");
938         changed_limit_at_restart = 0;
939     }
940
941     /* Initialize cross-process accept lock */
942     ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_OS_PROC_T_FMT,
943                                  ap_server_root_relative(_pconf, ap_lock_fname),
944                                  ap_my_pid);
945
946     rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname, 
947                                ap_accept_lock_mech, _pconf);
948     if (rv != APR_SUCCESS) {
949         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
950                      "Couldn't create accept lock");
951         return 1;
952     }
953
954 #if APR_USE_SYSVSEM_SERIALIZE
955     if (ap_accept_lock_mech == APR_LOCK_DEFAULT || 
956         ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
957 #else
958     if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
959 #endif
960         rv = unixd_set_proc_mutex_perms(accept_mutex);
961         if (rv != APR_SUCCESS) {
962             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
963                          "Couldn't set permissions on cross-process lock");
964             return 1;
965         }
966     }
967
968     if (!is_graceful) {
969         if (ap_run_pre_mpm(pconf, SB_SHARED) != OK) {
970             return 1;
971         }
972     }
973 #ifdef SCOREBOARD_FILE
974     else {
975         ap_scoreboard_fname = ap_server_root_relative(pconf, ap_scoreboard_fname);
976         ap_note_cleanups_for_fd(pconf, scoreboard_fd);
977     }
978 #endif
979
980     set_signals();
981
982     if (one_process) {
983         AP_MONCONTROL(1);
984     }
985
986     if (ap_daemons_max_free < ap_daemons_min_free + 1)  /* Don't thrash... */
987         ap_daemons_max_free = ap_daemons_min_free + 1;
988
989     /* If we're doing a graceful_restart then we're going to see a lot
990         * of children exiting immediately when we get into the main loop
991         * below (because we just sent them AP_SIG_GRACEFUL).  This happens pretty
992         * rapidly... and for each one that exits we'll start a new one until
993         * we reach at least daemons_min_free.  But we may be permitted to
994         * start more than that, so we'll just keep track of how many we're
995         * supposed to start up without the 1 second penalty between each fork.
996         */
997     remaining_children_to_start = ap_daemons_to_start;
998     if (remaining_children_to_start > ap_daemons_limit) {
999         remaining_children_to_start = ap_daemons_limit;
1000     }
1001     if (!is_graceful) {
1002         startup_children(remaining_children_to_start);
1003         remaining_children_to_start = 0;
1004     }
1005     else {
1006         /* give the system some time to recover before kicking into
1007             * exponential mode */
1008         hold_off_on_exponential_spawning = 10;
1009     }
1010
1011     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1012                 "%s configured -- resuming normal operations",
1013                 ap_get_server_version());
1014     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1015                 "Server built: %s", ap_get_server_built());
1016     restart_pending = shutdown_pending = 0;
1017
1018     while (!restart_pending && !shutdown_pending) {
1019         int child_slot;
1020         apr_exit_why_e exitwhy;
1021         int status, processed_status;
1022         /* this is a memory leak, but I'll fix it later. */
1023         apr_proc_t pid;
1024
1025         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
1026
1027         /* XXX: if it takes longer than 1 second for all our children
1028          * to start up and get into IDLE state then we may spawn an
1029          * extra child
1030          */
1031         if (pid.pid != -1) {
1032             processed_status = ap_process_child_status(&pid, exitwhy, status);
1033             if (processed_status == APEXIT_CHILDFATAL) {
1034                 return 1;
1035             }
1036
1037             /* non-fatal death... note that it's gone in the scoreboard. */
1038             ap_sync_scoreboard_image();
1039             child_slot = find_child_by_pid(&pid);
1040             if (child_slot >= 0) {
1041                 (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
1042                                                            (request_rec *) NULL);
1043                 if (processed_status == APEXIT_CHILDSICK) {
1044                     /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
1045                      * cut the fork rate to the minimum 
1046                      */
1047                     idle_spawn_rate = 1; 
1048                 }
1049                 else if (remaining_children_to_start
1050                     && child_slot < ap_daemons_limit) {
1051                     /* we're still doing a 1-for-1 replacement of dead
1052                         * children with new children
1053                         */
1054                     make_child(ap_server_conf, child_slot);
1055                     --remaining_children_to_start;
1056                 }
1057 #if APR_HAS_OTHER_CHILD
1058             }
1059             else if (apr_proc_other_child_read(&pid, status) == 0) {
1060                 /* handled */
1061 #endif
1062             }
1063             else if (is_graceful) {
1064                 /* Great, we've probably just lost a slot in the
1065                     * scoreboard.  Somehow we don't know about this
1066                     * child.
1067                     */
1068                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 
1069                             0, ap_server_conf,
1070                             "long lost child came home! (pid %ld)", (long)pid.pid);
1071             }
1072             /* Don't perform idle maintenance when a child dies,
1073                 * only do it when there's a timeout.  Remember only a
1074                 * finite number of children can die, and it's pretty
1075                 * pathological for a lot to die suddenly.
1076                 */
1077             continue;
1078         }
1079         else if (remaining_children_to_start) {
1080             /* we hit a 1 second timeout in which none of the previous
1081                 * generation of children needed to be reaped... so assume
1082                 * they're all done, and pick up the slack if any is left.
1083                 */
1084             startup_children(remaining_children_to_start);
1085             remaining_children_to_start = 0;
1086             /* In any event we really shouldn't do the code below because
1087                 * few of the servers we just started are in the IDLE state
1088                 * yet, so we'd mistakenly create an extra server.
1089                 */
1090             continue;
1091         }
1092
1093         perform_idle_server_maintenance(pconf);
1094 #ifdef TPF
1095     shutdown_pending = os_check_server(tpf_server_name);
1096     ap_check_signals();
1097     sleep(1);
1098 #endif /*TPF */
1099     }
1100
1101     if (shutdown_pending) {
1102         /* Time to gracefully shut down:
1103          * Kill child processes, tell them to call child_exit, etc...
1104          */
1105         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1106             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1107         }
1108         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
1109
1110         /* cleanup pid file on normal shutdown */
1111         {
1112             const char *pidfile = NULL;
1113             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1114             if ( pidfile != NULL && unlink(pidfile) == 0)
1115                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,
1116                                 0, ap_server_conf,
1117                                 "removed PID file %s (pid=%ld)",
1118                                 pidfile, (long)getpid());
1119         }
1120
1121         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1122                     "caught SIGTERM, shutting down");
1123         return 1;
1124     }
1125
1126     /* we've been told to restart */
1127     apr_signal(SIGHUP, SIG_IGN);
1128     if (one_process) {
1129         /* not worth thinking about */
1130         return 1;
1131     }
1132
1133     /* advance to the next generation */
1134     /* XXX: we really need to make sure this new generation number isn't in
1135      * use by any of the children.
1136      */
1137     ++ap_my_generation;
1138     ap_scoreboard_image->global->running_generation = ap_my_generation;
1139     update_scoreboard_global();
1140     
1141     if (is_graceful) {
1142         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1143                     "Graceful restart requested, doing restart");
1144
1145         /* kill off the idle ones */
1146         ap_mpm_pod_killpg(pod, ap_daemons_limit);
1147
1148 #ifndef SCOREBOARD_FILE
1149         /* This is mostly for debugging... so that we know what is still
1150             * gracefully dealing with existing request.  But we can't really
1151             * do it if we're in a SCOREBOARD_FILE because it'll cause
1152             * corruption too easily.
1153             */
1154         ap_sync_scoreboard_image();
1155         for (index = 0; index < ap_daemons_limit; ++index) {
1156             if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1157                 ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1158             }
1159         }
1160 #endif
1161     }
1162     else {
1163         /* Kill 'em off */
1164         if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
1165             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
1166         }
1167         ap_reclaim_child_processes(0);          /* Not when just starting up */
1168         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1169                     "SIGHUP received.  Attempting to restart");
1170     }
1171
1172     return 0;
1173 }
1174
1175 /* This really should be a post_config hook, but the error log is already
1176  * redirected by that point, so we need to do this in the open_logs phase.
1177  */
1178 static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1179 {
1180     apr_status_t rv;
1181
1182     pconf = p;
1183     ap_server_conf = s;
1184
1185     if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1186         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT|APLOG_STARTUP, 0, 
1187                      NULL, "no listening sockets available, shutting down");
1188         return DONE;
1189     }
1190
1191     if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1192         ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
1193                 "Could not open pipe-of-death.");
1194         return DONE;
1195     }
1196     return OK;
1197 }
1198
1199 static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1200 {
1201     static int restart_num = 0;
1202     int no_detach, debug;
1203     apr_status_t rv;
1204
1205     debug = ap_exists_config_define("DEBUG");
1206
1207     if (debug)
1208         no_detach = one_process = 1;
1209     else
1210     {
1211         no_detach = ap_exists_config_define("NO_DETACH");
1212         one_process = ap_exists_config_define("ONE_PROCESS");
1213     }
1214
1215     /* sigh, want this only the second time around */
1216     if (restart_num++ == 1) {
1217         is_graceful = 0;
1218
1219     if (!one_process) {
1220         rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1221                                        : APR_PROC_DETACH_DAEMONIZE);
1222         if (rv != APR_SUCCESS) {
1223             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1224                          "apr_proc_detach failed");
1225             return HTTP_INTERNAL_SERVER_ERROR;
1226         }
1227     }
1228
1229         parent_pid = ap_my_pid = getpid();
1230     }
1231
1232     unixd_pre_config(ptemp);
1233     ap_listen_pre_config();
1234     ap_daemons_to_start = DEFAULT_START_DAEMON;
1235     ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1236     ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1237     ap_daemons_limit = server_limit;
1238     ap_pid_fname = DEFAULT_PIDLOG;
1239     ap_lock_fname = DEFAULT_LOCKFILE;
1240     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1241     ap_extended_status = 0;
1242
1243     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1244
1245     return OK;
1246 }
1247
1248 static void prefork_hooks(apr_pool_t *p)
1249 {
1250     /* The prefork open_logs phase must run before the core's, or stderr
1251      * will be redirected to a file, and the messages won't print to the
1252      * console.
1253      */
1254     static const char *const aszSucc[] = {"core.c", NULL};
1255
1256 #ifdef AUX3
1257     (void) set42sig();
1258 #endif
1259
1260     ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
1261     ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1262 }
1263
1264 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg) 
1265 {
1266     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1267     if (err != NULL) {
1268         return err;
1269     }
1270
1271     ap_daemons_to_start = atoi(arg);
1272     return NULL;
1273 }
1274
1275 static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1276 {
1277     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1278     if (err != NULL) {
1279         return err;
1280     }
1281
1282     ap_daemons_min_free = atoi(arg);
1283     if (ap_daemons_min_free <= 0) {
1284        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1285                     "WARNING: detected MinSpareServers set to non-positive.");
1286        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1287                     "Resetting to 1 to avoid almost certain Apache failure.");
1288        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1289                     "Please read the documentation.");
1290        ap_daemons_min_free = 1;
1291     }
1292        
1293     return NULL;
1294 }
1295
1296 static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1297 {
1298     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1299     if (err != NULL) {
1300         return err;
1301     }
1302
1303     ap_daemons_max_free = atoi(arg);
1304     return NULL;
1305 }
1306
1307 static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg) 
1308 {
1309     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1310     if (err != NULL) {
1311         return err;
1312     }
1313
1314     ap_daemons_limit = atoi(arg);
1315     if (ap_daemons_limit > server_limit) {
1316        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1317                     "WARNING: MaxClients of %d exceeds ServerLimit value "
1318                     "of %d servers,", ap_daemons_limit, server_limit);
1319        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1320                     " lowering MaxClients to %d.  To increase, please "
1321                     "see the ServerLimit", server_limit);
1322        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1323                     " directive.");
1324        ap_daemons_limit = server_limit;
1325     } 
1326     else if (ap_daemons_limit < 1) {
1327         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1328                      "WARNING: Require MaxClients > 0, setting to 1");
1329         ap_daemons_limit = 1;
1330     }
1331     return NULL;
1332 }
1333
1334 static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg) 
1335 {
1336     int tmp_server_limit;
1337     
1338     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1339     if (err != NULL) {
1340         return err;
1341     }
1342
1343     tmp_server_limit = atoi(arg);
1344     /* you cannot change ServerLimit across a restart; ignore
1345      * any such attempts
1346      */
1347     if (first_server_limit &&
1348         tmp_server_limit != server_limit) {
1349         /* how do we log a message?  the error log is a bit bucket at this
1350          * point; we'll just have to set a flag so that ap_mpm_run()
1351          * logs a warning later
1352          */
1353         changed_limit_at_restart = 1;
1354         return NULL;
1355     }
1356     server_limit = tmp_server_limit;
1357     
1358     if (server_limit > MAX_SERVER_LIMIT) {
1359        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1360                     "WARNING: ServerLimit of %d exceeds compile time limit "
1361                     "of %d servers,", server_limit, MAX_SERVER_LIMIT);
1362        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1363                     " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
1364        server_limit = MAX_SERVER_LIMIT;
1365     } 
1366     else if (server_limit < 1) {
1367         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1368                      "WARNING: Require ServerLimit > 0, setting to 1");
1369         server_limit = 1;
1370     }
1371     return NULL;
1372 }
1373
1374 static const command_rec prefork_cmds[] = {
1375 UNIX_DAEMON_COMMANDS,
1376 LISTEN_COMMANDS,
1377 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1378               "Number of child processes launched at server startup"),
1379 AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1380               "Minimum number of idle children, to handle request spikes"),
1381 AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1382               "Maximum number of idle children"),
1383 AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1384               "Maximum number of children alive at the same time"),
1385 AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1386               "Maximum value of MaxClients for this run of Apache"),
1387 { NULL }
1388 };
1389
1390 module AP_MODULE_DECLARE_DATA mpm_prefork_module = {
1391     MPM20_MODULE_STUFF,
1392     NULL,                       /* hook to run before apache parses args */
1393     NULL,                       /* create per-directory config structure */
1394     NULL,                       /* merge per-directory config structures */
1395     NULL,                       /* create per-server config structure */
1396     NULL,                       /* merge per-server config structures */
1397     prefork_cmds,               /* command apr_table_t */
1398     prefork_hooks,              /* register hooks */
1399 };