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