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