]> granicus.if.org Git - apache/blob - server/mpm/mpmt_pthread/mpmt_pthread.c
*) continued header revamping
[apache] / server / mpm / mpmt_pthread / mpmt_pthread.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 #include "apr.h"
60 #include "apr_portable.h"
61 #include "apr_strings.h"
62 #include "apr_file_io.h"
63 #include "apr_thread_proc.h"
64
65 #if APR_HAVE_SYS_SOCKET_H
66 #include <sys/socket.h>
67 #endif
68 #if APR_HAVE_SYS_WAIT_H
69 #include <sys/wait.h> 
70 #endif
71
72 #define CORE_PRIVATE 
73  
74 #include "ap_config.h"
75 #include "httpd.h" 
76 #include "http_main.h" 
77 #include "http_log.h" 
78 #include "http_config.h"        /* for read_config */ 
79 #include "http_core.h"          /* for get_remote_host */ 
80 #include "http_connection.h"
81 #include "ap_mpm.h"
82 #include "unixd.h"
83 #include "mpm_common.h"
84 #include "ap_listen.h"
85 #include "scoreboard.h" 
86
87 #ifdef HAVE_NETINET_TCP_H
88 #include <netinet/tcp.h>
89 #endif
90
91 #include <pthread.h>
92 #include <signal.h>
93
94 /*
95  * Actual definitions of config globals
96  */
97
98 int ap_threads_per_child=0;         /* Worker threads per child */
99 int ap_max_requests_per_child=0;
100 static const char *ap_pid_fname=NULL;
101 static int ap_daemons_to_start=0;
102 static int min_spare_threads=0;
103 static int max_spare_threads=0;
104 static int ap_daemons_limit=0;
105 static int workers_may_exit = 0;
106 static int requests_this_child;
107 static int num_listensocks = 0;
108 static apr_socket_t **listensocks;
109
110 /* The structure used to pass unique initialization info to each thread */
111 typedef struct {
112     int pid;
113     int tid;
114     int sd;
115     apr_pool_t *tpool; /* "pthread" would be confusing */
116 } proc_info;
117
118 /*
119  * The max child slot ever assigned, preserved across restarts.  Necessary
120  * to deal with MaxClients changes across SIGWINCH restarts.  We use this
121  * value to optimize routines that have to scan the entire scoreboard.
122  */
123 int ap_max_daemons_limit = -1;
124
125 char ap_coredump_dir[MAX_STRING_LEN];
126
127 static apr_file_t *pipe_of_death_in = NULL;
128 static apr_file_t *pipe_of_death_out = NULL;
129 static pthread_mutex_t pipe_of_death_mutex;
130
131 /* *Non*-shared http_main globals... */
132
133 server_rec *ap_server_conf;
134
135 /* one_process --- debugging mode variable; can be set from the command line
136  * with the -X flag.  If set, this gets you the child_main loop running
137  * in the process which originally started up (no detach, no make_child),
138  * which is a pretty nice debugging environment.  (You'll get a SIGHUP
139  * early in standalone_main; just continue through.  This is the server
140  * trying to kill off any child processes which it might have lying
141  * around --- Apache doesn't keep track of their pids, it just sends
142  * SIGHUP to the process group, ignoring it in the root process.
143  * Continue through and you'll be fine.).
144  */
145
146 static int one_process = 0;
147
148 #ifdef DEBUG_SIGSTOP
149 int raise_sigstop_flags;
150 #endif
151
152 static apr_pool_t *pconf;               /* Pool for config stuff */
153 static apr_pool_t *pchild;              /* Pool for httpd child stuff */
154
155 unsigned int ap_my_pid; /* Linux getpid() doesn't work except in main 
156                            thread. Use this instead */
157 /* Keep track of the number of worker threads currently active */
158 static int worker_thread_count;
159 static pthread_mutex_t worker_thread_count_mutex;
160
161 /* Locks for accept serialization */
162 static apr_lock_t *accept_mutex;
163 static const char *lock_fname;
164
165 #ifdef NO_SERIALIZED_ACCEPT
166 #define SAFE_ACCEPT(stmt) APR_SUCCESS
167 #else
168 #define SAFE_ACCEPT(stmt) (stmt)
169 #endif
170
171 AP_DECLARE(int) ap_get_max_daemons(void)
172 {
173     return ap_max_daemons_limit;
174 }
175
176 /* a clean exit from a child with proper cleanup */ 
177 static void clean_child_exit(int code) __attribute__ ((noreturn));
178 void clean_child_exit(int code)
179 {
180     if (pchild) {
181         apr_pool_destroy(pchild);
182     }
183     exit(code);
184 }
185
186 /* handle all varieties of core dumping signals */
187 static void sig_coredump(int sig)
188 {
189     chdir(ap_coredump_dir);
190     apr_signal(sig, SIG_DFL);
191     kill(ap_my_pid, sig);
192     /* At this point we've got sig blocked, because we're still inside
193      * the signal handler.  When we leave the signal handler it will
194      * be unblocked, and we'll take the signal... and coredump or whatever
195      * is appropriate for this particular Unix.  In addition the parent
196      * will see the real signal we received -- whereas if we called
197      * abort() here, the parent would only see SIGABRT.
198      */
199 }
200
201 static void just_die(int sig)
202 {
203     clean_child_exit(0);
204 }
205
206 /*****************************************************************
207  * Connection structures and accounting...
208  */
209
210 /* volatile just in case */
211 static int volatile shutdown_pending;
212 static int volatile restart_pending;
213 static int volatile is_graceful;
214 ap_generation_t volatile ap_my_generation;
215
216 /*
217  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
218  * functions to initiate shutdown or restart without relying on signals. 
219  * Previously this was initiated in sig_term() and restart() signal handlers, 
220  * but we want to be able to start a shutdown/restart from other sources --
221  * e.g. on Win32, from the service manager. Now the service manager can
222  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
223  * these functions can also be called by the child processes, since global
224  * variables are no longer used to pass on the required action to the parent.
225  *
226  * These should only be called from the parent process itself, since the
227  * parent process will use the shutdown_pending and restart_pending variables
228  * to determine whether to shutdown or restart. The child process should
229  * call signal_parent() directly to tell the parent to die -- this will
230  * cause neither of those variable to be set, which the parent will
231  * assume means something serious is wrong (which it will be, for the
232  * child to force an exit) and so do an exit anyway.
233  */
234
235 static void ap_start_shutdown(void)
236 {
237     if (shutdown_pending == 1) {
238         /* Um, is this _probably_ not an error, if the user has
239          * tried to do a shutdown twice quickly, so we won't
240          * worry about reporting it.
241          */
242         return;
243     }
244     shutdown_pending = 1;
245 }
246
247 /* do a graceful restart if graceful == 1 */
248 static void ap_start_restart(int graceful)
249 {
250
251     if (restart_pending == 1) {
252         /* Probably not an error - don't bother reporting it */
253         return;
254     }
255     restart_pending = 1;
256     is_graceful = graceful;
257     if (is_graceful) {
258         apr_pool_cleanup_kill(pconf, NULL, ap_cleanup_scoreboard);
259     }
260 }
261
262 static void sig_term(int sig)
263 {
264     ap_start_shutdown();
265 }
266
267 static void restart(int sig)
268 {
269 #ifndef WIN32
270     ap_start_restart(sig == SIGWINCH);
271 #else
272     ap_start_restart(1);
273 #endif
274 }
275
276 static void set_signals(void)
277 {
278 #ifndef NO_USE_SIGACTION
279     struct sigaction sa;
280
281     sigemptyset(&sa.sa_mask);
282     sa.sa_flags = 0;
283
284     if (!one_process) {
285         sa.sa_handler = sig_coredump;
286 #if defined(SA_ONESHOT)
287         sa.sa_flags = SA_ONESHOT;
288 #elif defined(SA_RESETHAND)
289         sa.sa_flags = SA_RESETHAND;
290 #endif
291         if (sigaction(SIGSEGV, &sa, NULL) < 0)
292             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
293 #ifdef SIGBUS
294         if (sigaction(SIGBUS, &sa, NULL) < 0)
295             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
296 #endif
297 #ifdef SIGABORT
298         if (sigaction(SIGABORT, &sa, NULL) < 0)
299             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
300 #endif
301 #ifdef SIGABRT
302         if (sigaction(SIGABRT, &sa, NULL) < 0)
303             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
304 #endif
305 #ifdef SIGILL
306         if (sigaction(SIGILL, &sa, NULL) < 0)
307             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
308 #endif
309         sa.sa_flags = 0;
310     }
311     sa.sa_handler = sig_term;
312     if (sigaction(SIGTERM, &sa, NULL) < 0)
313         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
314 #ifdef SIGINT
315     if (sigaction(SIGINT, &sa, NULL) < 0)
316         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
317 #endif
318 #ifdef SIGXCPU
319     sa.sa_handler = SIG_DFL;
320     if (sigaction(SIGXCPU, &sa, NULL) < 0)
321         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
322 #endif
323 #ifdef SIGXFSZ
324     sa.sa_handler = SIG_DFL;
325     if (sigaction(SIGXFSZ, &sa, NULL) < 0)
326         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
327 #endif
328 #ifdef SIGPIPE
329     sa.sa_handler = SIG_IGN;
330     if (sigaction(SIGPIPE, &sa, NULL) < 0)
331         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
332 #endif
333
334     /* we want to ignore HUPs and WINCH while we're busy processing one */
335     sigaddset(&sa.sa_mask, SIGHUP);
336     sigaddset(&sa.sa_mask, SIGWINCH);
337     sa.sa_handler = restart;
338     if (sigaction(SIGHUP, &sa, NULL) < 0)
339         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
340     if (sigaction(SIGWINCH, &sa, NULL) < 0)
341         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGWINCH)");
342 #else
343     if (!one_process) {
344         apr_signal(SIGSEGV, sig_coredump);
345 #ifdef SIGBUS
346         apr_signal(SIGBUS, sig_coredump);
347 #endif /* SIGBUS */
348 #ifdef SIGABORT
349         apr_signal(SIGABORT, sig_coredump);
350 #endif /* SIGABORT */
351 #ifdef SIGABRT
352         apr_signal(SIGABRT, sig_coredump);
353 #endif /* SIGABRT */
354 #ifdef SIGILL
355         apr_signal(SIGILL, sig_coredump);
356 #endif /* SIGILL */
357 #ifdef SIGXCPU
358         apr_signal(SIGXCPU, SIG_DFL);
359 #endif /* SIGXCPU */
360 #ifdef SIGXFSZ
361         apr_signal(SIGXFSZ, SIG_DFL);
362 #endif /* SIGXFSZ */
363     }
364
365     apr_signal(SIGTERM, sig_term);
366 #ifdef SIGHUP
367     apr_signal(SIGHUP, restart);
368 #endif /* SIGHUP */
369 #ifdef SIGWINCH
370     apr_signal(SIGWINCH, restart);
371 #endif /* SIGWINCH */
372 #ifdef SIGPIPE
373     apr_signal(SIGPIPE, SIG_IGN);
374 #endif /* SIGPIPE */
375
376 #endif
377 }
378
379 /*****************************************************************
380  * Here follows a long bunch of generic server bookkeeping stuff...
381  */
382
383 int ap_graceful_stop_signalled(void)
384 {
385     /* XXX - Does this really work? - Manoj */
386     return is_graceful;
387 }
388
389 /*****************************************************************
390  * Child process main loop.
391  */
392
393 static void process_socket(apr_pool_t *p, apr_socket_t *sock, int my_child_num, int my_thread_num)
394 {
395     conn_rec *current_conn;
396     long conn_id = AP_ID_FROM_CHILD_THREAD(my_child_num, my_thread_num);
397     int csd;
398
399     (void) apr_os_sock_get(&csd, sock);
400
401     if (csd >= FD_SETSIZE) {
402         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
403                      "new file descriptor %d is too large; you probably need "
404                      "to rebuild Apache with a larger FD_SETSIZE "
405                      "(currently %d)", 
406                      csd, FD_SETSIZE);
407         apr_socket_close(sock);
408         return;
409     }
410
411     ap_sock_disable_nagle(sock);
412
413     (void) ap_update_child_status(my_child_num, my_thread_num,  
414                                   SERVER_BUSY_READ, (request_rec *) NULL);
415
416     current_conn = ap_new_connection(p, ap_server_conf, sock, conn_id);
417     if (current_conn) {
418         ap_process_connection(current_conn);
419         ap_lingering_close(current_conn);
420     }
421 }
422 /* Sets workers_may_exit if we received a character on the pipe_of_death */
423 static void check_pipe_of_death(void)
424 {
425     pthread_mutex_lock(&pipe_of_death_mutex);
426     if (!workers_may_exit) {
427         apr_status_t ret;
428         char pipe_read_char;
429         apr_size_t n = 1;
430
431         ret = apr_recv(listensocks[0], &pipe_read_char, &n);
432         if (APR_STATUS_IS_EAGAIN(ret)) {
433             /* It lost the lottery. It must continue to suffer
434              * through a life of servitude. */
435         }
436         else {
437             /* It won the lottery (or something else is very
438              * wrong). Embrace death with open arms. */
439             workers_may_exit = 1;
440         }
441     }
442     pthread_mutex_unlock(&pipe_of_death_mutex);
443 }
444
445 static void * worker_thread(void * dummy)
446 {
447     proc_info * ti = dummy;
448     int process_slot = ti->pid;
449     int thread_slot = ti->tid;
450     apr_pool_t *tpool = ti->tpool;
451     apr_socket_t *csd = NULL;
452     apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
453     apr_socket_t *sd = NULL;
454     int n;
455     int curr_pollfd, last_pollfd = 0;
456     apr_pollfd_t *pollset;
457     apr_status_t rv;
458
459     free(ti);
460
461     apr_pool_create(&ptrans, tpool);
462
463     pthread_mutex_lock(&worker_thread_count_mutex);
464     worker_thread_count++;
465     pthread_mutex_unlock(&worker_thread_count_mutex);
466
467     apr_poll_setup(&pollset, num_listensocks+1, tpool);
468     for(n=0 ; n <= num_listensocks ; ++n)
469         apr_poll_socket_add(pollset, listensocks[n], APR_POLLIN);
470
471     /* TODO: Switch to a system where threads reuse the results from earlier
472        poll calls - manoj */
473     while (1) {
474         workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
475         if (workers_may_exit) break;
476
477         (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY, 
478                                       (request_rec *) NULL);
479         if ((rv = SAFE_ACCEPT(apr_lock_aquire(accept_mutex)))
480             != APR_SUCCESS) {
481             ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
482                          "apr_lock_aquire failed. Attempting to shutdown "
483                          "process gracefully.");
484             workers_may_exit = 1;
485         }
486
487         while (!workers_may_exit) {
488             apr_status_t ret;
489             apr_int16_t event;
490
491             ret = apr_poll(pollset, &n, -1);
492             if (ret != APR_SUCCESS) {
493                 if (APR_STATUS_IS_EINTR(ret)) {
494                     continue;
495                 }
496
497                 /* apr_poll() will only return errors in catastrophic
498                  * circumstances. Let's try exiting gracefully, for now. */
499                 ap_log_error(APLOG_MARK, APLOG_ERR, ret, (const server_rec *)
500                              ap_server_conf, "apr_poll: (listen)");
501                 workers_may_exit = 1;
502             }
503
504             if (workers_may_exit) break;
505
506             apr_poll_revents_get(&event, listensocks[0], pollset);
507             if (event & APR_POLLIN) {
508                 /* A process got a signal on the shutdown pipe. Check if we're
509                  * the lucky process to die. */
510                 check_pipe_of_death();
511                 continue;
512             }
513
514             if (num_listensocks == 1) {
515                 sd = ap_listeners->sd;
516                 goto got_fd;
517             }
518             else {
519                 /* find a listener */
520                 curr_pollfd = last_pollfd;
521                 do {
522                     curr_pollfd++;
523                     if (curr_pollfd > num_listensocks) {
524                         curr_pollfd = 1;
525                     }
526                     /* XXX: Should we check for POLLERR? */
527                     apr_poll_revents_get(&event, listensocks[curr_pollfd], pollset);
528                     if (event & APR_POLLIN) {
529                         last_pollfd = curr_pollfd;
530                         sd=listensocks[curr_pollfd];
531                         goto got_fd;
532                     }
533                 } while (curr_pollfd != last_pollfd);
534             }
535         }
536     got_fd:
537         if (!workers_may_exit) {
538             if ((rv = apr_accept(&csd, sd, ptrans)) != APR_SUCCESS) {
539                 csd = NULL;
540                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, 
541                              "apr_accept");
542             }
543             if ((rv = SAFE_ACCEPT(apr_lock_release(accept_mutex)))
544                 != APR_SUCCESS) {
545                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
546                              "apr_lock_release failed. Attempting to shutdown "
547                              "process gracefully.");
548                 workers_may_exit = 1;
549             }
550             if (csd != NULL) {
551                 process_socket(ptrans, csd, process_slot, thread_slot);
552                 requests_this_child--;
553             }
554         }
555         else {
556             if ((rv = SAFE_ACCEPT(apr_lock_release(accept_mutex)))
557                 != APR_SUCCESS) {
558                 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
559                              "apr_lock_release failed. Attempting to shutdown "
560                              "process gracefully.");
561                 workers_may_exit = 1;
562             }
563             break;
564         }
565         apr_clear_pool(ptrans);
566     }
567
568     apr_pool_destroy(tpool);
569     ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
570         (request_rec *) NULL);
571     pthread_mutex_lock(&worker_thread_count_mutex);
572     worker_thread_count--;
573     if (worker_thread_count == 0) {
574         /* All the threads have exited, now finish the shutdown process
575          * by signalling the sigwait thread */
576         kill(ap_my_pid, SIGTERM);
577     }
578     pthread_mutex_unlock(&worker_thread_count_mutex);
579
580     return NULL;
581 }
582
583
584 static void child_main(int child_num_arg)
585 {
586     sigset_t sig_mask;
587     int signal_received;
588     pthread_t thread;
589     pthread_attr_t thread_attr;
590     int i;
591     int my_child_num = child_num_arg;
592     proc_info *my_info = NULL;
593     ap_listen_rec *lr;
594     apr_status_t rv;
595
596
597     ap_my_pid = getpid();
598     apr_pool_create(&pchild, pconf);
599
600     /*stuff to do before we switch id's, so we have permissions.*/
601     reopen_scoreboard(pchild);
602
603     rv = SAFE_ACCEPT(apr_lock_child_init(&accept_mutex, lock_fname,
604                      pchild));
605     if (rv != APR_SUCCESS) {
606         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
607                      "Couldn't initialize cross-process lock in child");
608         clean_child_exit(APEXIT_CHILDFATAL);
609     }
610
611     if (unixd_setup_child()) {
612         clean_child_exit(APEXIT_CHILDFATAL);
613     }
614
615     ap_child_init_hook(pchild, ap_server_conf);
616
617     /*done with init critical section */
618
619     /* All threads should mask signals out, accoring to sigwait(2) man page */
620     sigfillset(&sig_mask);
621
622 #ifdef SIGPROCMASK_SETS_THREAD_MASK
623     if (sigprocmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
624         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "sigprocmask");
625     }
626 #else
627     if ((rv = pthread_sigmask(SIG_SETMASK, &sig_mask, NULL)) != 0) {
628 #ifdef PTHREAD_SETS_ERRNO
629         rv = errno;
630 #endif
631         ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, "pthread_sigmask");
632     }
633 #endif
634
635     requests_this_child = ap_max_requests_per_child;
636     
637     /* Set up the pollfd array */
638     listensocks = apr_pcalloc(pchild,
639                             sizeof(*listensocks) * (num_listensocks + 1));
640 #if APR_FILES_AS_SOCKETS
641     apr_socket_from_file(&listensocks[0], pipe_of_death_in);
642 #endif
643     for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
644         listensocks[i]=lr->sd;
645
646     /* Setup worker threads */
647
648     worker_thread_count = 0;
649     pthread_mutex_init(&worker_thread_count_mutex, NULL);
650     pthread_mutex_init(&pipe_of_death_mutex, NULL);
651     pthread_attr_init(&thread_attr);
652 #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR
653     {
654         int on = 1;
655
656         pthread_attr_setdetachstate(&thread_attr, &on);
657     }
658 #else
659     pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
660 #endif
661     for (i=0; i < ap_threads_per_child; i++) {
662
663         my_info = (proc_info *)malloc(sizeof(proc_info));
664         if (my_info == NULL) {
665             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
666                          "malloc: out of memory");
667             clean_child_exit(APEXIT_CHILDFATAL);
668         }
669         my_info->pid = my_child_num;
670         my_info->tid = i;
671         my_info->sd = 0;
672         apr_pool_create(&my_info->tpool, pchild);
673         
674         /* We are creating threads right now */
675         (void) ap_update_child_status(my_child_num, i, SERVER_STARTING, 
676                                       (request_rec *) NULL);
677 #ifndef NO_THREADS
678         if ((rv = pthread_create(&thread, &thread_attr, worker_thread, my_info))) {
679 #ifdef PTHREAD_SETS_ERRNO
680             rv = errno;
681 #endif
682             ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
683                          "pthread_create: unable to create worker thread");
684             /* In case system resources are maxxed out, we don't want
685                Apache running away with the CPU trying to fork over and
686                over and over again if we exit. */
687             sleep(10);
688             clean_child_exit(APEXIT_CHILDFATAL);
689         }
690 #else
691         worker_thread(my_info);
692         /* The SIGTERM shouldn't let us reach this point, but just in case... */
693         clean_child_exit(APEXIT_OK);
694 #endif
695
696         /* We let each thread update it's own scoreboard entry.  This is done
697          * because it let's us deal with tid better.
698          */
699     }
700
701     pthread_attr_destroy(&thread_attr);
702
703     /* This thread will be the one responsible for handling signals */
704     sigemptyset(&sig_mask);
705     sigaddset(&sig_mask, SIGTERM);
706     sigaddset(&sig_mask, SIGINT);
707     ap_sigwait(&sig_mask, &signal_received);
708     switch (signal_received) {
709         case SIGTERM:
710         case SIGINT:
711             just_die(signal_received);
712             break;
713         default:
714             ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
715             "received impossible signal: %d", signal_received);
716             just_die(SIGTERM);
717     }
718 }
719
720 static int make_child(server_rec *s, int slot) 
721 {
722     int pid;
723
724     if (slot + 1 > ap_max_daemons_limit) {
725         ap_max_daemons_limit = slot + 1;
726     }
727
728     if (one_process) {
729         set_signals();
730         ap_scoreboard_image->parent[slot].pid = getpid();
731         child_main(slot);
732     }
733
734     /* Tag this slot as occupied so that perform_idle_server_maintenance
735      * doesn't try to steal it */
736     (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
737
738     if ((pid = fork()) == -1) {
739         ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
740
741         /* fork didn't succeed. Fix the scoreboard or else
742          * it will say SERVER_STARTING forever and ever
743          */
744         (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
745
746         /* In case system resources are maxxed out, we don't want
747            Apache running away with the CPU trying to fork over and
748            over and over again. */
749         sleep(10);
750
751         return -1;
752     }
753
754     if (!pid) {
755 #ifdef AIX_BIND_PROCESSOR
756       /* By default, AIX binds to a single processor.  This bit unbinds
757          children which will then bind to another CPU.
758       */
759 #include <sys/processor.h>
760         int status = bindprocessor(BINDPROCESS, (int)getpid(),
761                                PROCESSOR_CLASS_ANY);
762         if (status != OK)
763             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, errno, ap_server_conf,
764                          "processor unbind failed %d", status);
765 #endif
766
767         RAISE_SIGSTOP(MAKE_CHILD);
768
769         apr_signal(SIGTERM, just_die);
770         child_main(slot);
771
772         return 0;
773     }
774     /* else */
775     ap_scoreboard_image->parent[slot].pid = pid;
776     return 0;
777 }
778
779 /* start up a bunch of children */
780 static void startup_children(int number_to_start)
781 {
782     int i;
783
784     for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
785         if (ap_scoreboard_image->parent[i].pid != 0) {
786             continue;
787         }
788         if (make_child(ap_server_conf, i) < 0) {
789             break;
790         }
791         --number_to_start;
792     }
793 }
794
795
796 /*
797  * idle_spawn_rate is the number of children that will be spawned on the
798  * next maintenance cycle if there aren't enough idle servers.  It is
799  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
800  * without the need to spawn.
801  */
802 static int idle_spawn_rate = 1;
803 #ifndef MAX_SPAWN_RATE
804 #define MAX_SPAWN_RATE  (32)
805 #endif
806 static int hold_off_on_exponential_spawning;
807
808 static void perform_idle_server_maintenance(void)
809 {
810     int i, j;
811     int idle_thread_count;
812     short_score *ss;
813     int free_length;
814     int free_slots[MAX_SPAWN_RATE];
815     int last_non_dead;
816     int total_non_dead;
817     apr_size_t one = 1;
818     apr_status_t rv;
819
820     /* initialize the free_list */
821     free_length = 0;
822
823     idle_thread_count = 0;
824     last_non_dead = -1;
825     total_non_dead = 0;
826
827     ap_sync_scoreboard_image();
828     for (i = 0; i < ap_daemons_limit; ++i) {
829         /* Initialization to satisfy the compiler. It doesn't know
830          * that ap_threads_per_child is always > 0 */
831         int status = SERVER_DEAD;
832         int any_dying_threads = 0;
833         int all_dead_threads = 1;
834         int idle_thread_addition = 0;
835
836         if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
837             break;
838         for (j = 0; j < ap_threads_per_child; j++) {
839             ss = &ap_scoreboard_image->servers[i][j];
840             status = ss->status;
841
842             any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
843                                     || (status == SERVER_GRACEFUL);
844             all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
845
846             /* We consider a starting server as idle because we started it
847              * at least a cycle ago, and if it still hasn't finished starting
848              * then we're just going to swamp things worse by forking more.
849              * So we hopefully won't need to fork more if we count it.
850              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
851              */
852             if (status <= SERVER_READY) {
853                 ++idle_thread_addition;
854             }
855         }
856         if (all_dead_threads && free_length < idle_spawn_rate) {
857             free_slots[free_length] = i;
858             ++free_length;
859         }
860         if (!all_dead_threads) {
861             last_non_dead = i;
862         }
863         if (!any_dying_threads) {
864             ++total_non_dead;
865             idle_thread_count += idle_thread_addition;
866         }
867     }
868     ap_max_daemons_limit = last_non_dead + 1;
869
870     if (idle_thread_count > max_spare_threads) {
871         /* Kill off one child */
872         char char_of_death = '!';
873         if ((rv = apr_file_write(pipe_of_death_out, &char_of_death, &one)) != APR_SUCCESS) {
874             ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, "write pipe_of_death");
875         }
876         idle_spawn_rate = 1;
877     }
878     else if (idle_thread_count < min_spare_threads) {
879         /* terminate the free list */
880         if (free_length == 0) {
881             /* only report this condition once */
882             static int reported = 0;
883             
884             if (!reported) {
885                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
886                              "server reached MaxClients setting, consider"
887                              " raising the MaxClients setting");
888                 reported = 1;
889             }
890             idle_spawn_rate = 1;
891         }
892         else {
893             
894             if (idle_spawn_rate >= 8) {
895                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
896                              "server seems busy, (you may need "
897                              "to increase StartServers, ThreadsPerChild "
898                              "or Min/MaxSpareThreads), "
899                              "spawning %d children, there are around %d idle "
900                              "threads, and %d total children", idle_spawn_rate,
901                              idle_thread_count, total_non_dead);
902             }
903             for (i = 0; i < free_length; ++i) {
904                 make_child(ap_server_conf, free_slots[i]);
905             }
906             /* the next time around we want to spawn twice as many if this
907              * wasn't good enough, but not if we've just done a graceful
908              */
909             if (hold_off_on_exponential_spawning) {
910                 --hold_off_on_exponential_spawning;
911             }
912             else if (idle_spawn_rate < MAX_SPAWN_RATE) {
913                 idle_spawn_rate *= 2;
914             }
915         }
916     }
917     else {
918       idle_spawn_rate = 1;
919     }
920 }
921
922 static void server_main_loop(int remaining_children_to_start)
923 {
924     int child_slot;
925     apr_wait_t status;
926     apr_proc_t pid;
927     int i;
928
929     while (!restart_pending && !shutdown_pending) {
930         ap_wait_or_timeout(&status, &pid, pconf);
931         
932         if (pid.pid != -1) {
933             ap_process_child_status(&pid, status);
934             /* non-fatal death... note that it's gone in the scoreboard. */
935             child_slot = find_child_by_pid(&pid);
936             if (child_slot >= 0) {
937                 for (i = 0; i < ap_threads_per_child; i++)
938                     ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
939                 
940                 if (remaining_children_to_start
941                     && child_slot < ap_daemons_limit) {
942                     /* we're still doing a 1-for-1 replacement of dead
943                      * children with new children
944                      */
945                     make_child(ap_server_conf, child_slot);
946                     --remaining_children_to_start;
947                 }
948 #if APR_HAS_OTHER_CHILD
949             }
950             else if (apr_proc_other_child_read(&pid, status) == 0) {
951                 /* handled */
952 #endif
953             }
954             else if (is_graceful) {
955                 /* Great, we've probably just lost a slot in the
956                  * scoreboard.  Somehow we don't know about this child.
957                  */
958                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
959                              ap_server_conf,
960                              "long lost child came home! (pid %ld)",
961                              (long)pid.pid);
962             }
963             /* Don't perform idle maintenance when a child dies,
964              * only do it when there's a timeout.  Remember only a
965              * finite number of children can die, and it's pretty
966              * pathological for a lot to die suddenly.
967              */
968             continue;
969         }
970         else if (remaining_children_to_start) {
971             /* we hit a 1 second timeout in which none of the previous
972              * generation of children needed to be reaped... so assume
973              * they're all done, and pick up the slack if any is left.
974              */
975             startup_children(remaining_children_to_start);
976             remaining_children_to_start = 0;
977             /* In any event we really shouldn't do the code below because
978              * few of the servers we just started are in the IDLE state
979              * yet, so we'd mistakenly create an extra server.
980              */
981             continue;
982         }
983
984         perform_idle_server_maintenance();
985     }
986 }
987
988 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
989 {
990     int remaining_children_to_start;
991     apr_status_t rv;
992     apr_size_t one = 1;
993
994     pconf = _pconf;
995     ap_server_conf = s;
996     rv = apr_file_pipe_create(&pipe_of_death_in, &pipe_of_death_out, pconf);
997     if (rv != APR_SUCCESS) {
998         ap_log_error(APLOG_MARK, APLOG_ERR, rv,
999                      (const server_rec*) ap_server_conf,
1000                      "apr_file_pipe_create (pipe_of_death)");
1001         exit(1);
1002     }
1003
1004     if ((rv = apr_file_pipe_timeout_set(pipe_of_death_in, 0)) != APR_SUCCESS) {
1005         ap_log_error(APLOG_MARK, APLOG_ERR, rv,
1006                      (const server_rec*) ap_server_conf,
1007                      "apr_file_pipe_timeout_set (pipe_of_death)");
1008         exit(1);
1009     }
1010     ap_server_conf = s;
1011     if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1012         /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1013         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1014             "no listening sockets available, shutting down");
1015         return 1;
1016     }
1017     ap_log_pid(pconf, ap_pid_fname);
1018
1019     /* Initialize cross-process accept lock */
1020     lock_fname = apr_psprintf(_pconf, "%s.%u",
1021                              ap_server_root_relative(_pconf, lock_fname),
1022                              ap_my_pid);
1023     rv = apr_lock_create(&accept_mutex, APR_MUTEX, APR_LOCKALL,
1024                    lock_fname, _pconf);
1025     if (rv != APR_SUCCESS) {
1026         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1027                      "Couldn't create accept lock");
1028         return 1;
1029     }
1030
1031
1032     if (!is_graceful) {
1033         ap_create_scoreboard(pconf, SB_SHARED);
1034     }
1035
1036     set_signals();
1037     /* Don't thrash... */
1038     if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1039         max_spare_threads = min_spare_threads + ap_threads_per_child;
1040
1041     /* If we're doing a graceful_restart then we're going to see a lot
1042      * of children exiting immediately when we get into the main loop
1043      * below (because we just sent them SIGWINCH).  This happens pretty
1044      * rapidly... and for each one that exits we'll start a new one until
1045      * we reach at least daemons_min_free.  But we may be permitted to
1046      * start more than that, so we'll just keep track of how many we're
1047      * supposed to start up without the 1 second penalty between each fork.
1048      */
1049     remaining_children_to_start = ap_daemons_to_start;
1050     if (remaining_children_to_start > ap_daemons_limit) {
1051         remaining_children_to_start = ap_daemons_limit;
1052     }
1053     if (!is_graceful) {
1054         startup_children(remaining_children_to_start);
1055         remaining_children_to_start = 0;
1056     }
1057     else {
1058         /* give the system some time to recover before kicking into
1059             * exponential mode */
1060         hold_off_on_exponential_spawning = 10;
1061     }
1062
1063     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1064                 "%s configured -- resuming normal operations",
1065                 ap_get_server_version());
1066     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1067                 "Server built: %s", ap_get_server_built());
1068     restart_pending = shutdown_pending = 0;
1069
1070     server_main_loop(remaining_children_to_start);
1071
1072     if (shutdown_pending) {
1073         /* Time to gracefully shut down:
1074          * Kill child processes, tell them to call child_exit, etc...
1075          */
1076         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1077             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1078         }
1079         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
1080     
1081         /* cleanup pid file on normal shutdown */
1082         {
1083             const char *pidfile = NULL;
1084             pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1085             if ( pidfile != NULL && unlink(pidfile) == 0)
1086                 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1087                          ap_server_conf,
1088                          "removed PID file %s (pid=%ld)",
1089                          pidfile, (long)getpid());
1090         }
1091     
1092         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1093             "caught SIGTERM, shutting down");
1094     
1095         return 1;
1096     }
1097
1098     /* we've been told to restart */
1099     apr_signal(SIGHUP, SIG_IGN);
1100
1101     if (one_process) {
1102         /* not worth thinking about */
1103         return 1;
1104     }
1105
1106     /* advance to the next generation */
1107     /* XXX: we really need to make sure this new generation number isn't in
1108      * use by any of the children.
1109      */
1110     ++ap_my_generation;
1111     ap_scoreboard_image->global.running_generation = ap_my_generation;
1112     update_scoreboard_global();
1113
1114     if (is_graceful) {
1115         int i, j;
1116         char char_of_death = '!';
1117
1118         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1119                     "SIGWINCH received.  Doing graceful restart");
1120
1121         /* give the children the signal to die */
1122         for (i = 0; i < ap_daemons_limit;) {
1123             if ((rv = apr_file_write(pipe_of_death_in, &char_of_death, &one)) != APR_SUCCESS) {
1124                 if (APR_STATUS_IS_EINTR(rv)) continue;
1125                 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, "write pipe_of_death");
1126             }
1127             i++;
1128         }
1129
1130         /* This is mostly for debugging... so that we know what is still
1131          * gracefully dealing with existing request.
1132          */
1133         
1134         for (i = 0; i < ap_daemons_limit; ++i) {
1135             for (j = 0; j < ap_threads_per_child; j++) { 
1136                 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1137                     ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1138                 }
1139             } 
1140         }
1141     }
1142     else {
1143       /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
1144        * and a SIGHUP, we may as well use the same signal, because some user
1145        * pthreads are stealing signals from us left and right.
1146        */
1147         if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1148             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1149         }
1150         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
1151         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1152                     "SIGHUP received.  Attempting to restart");
1153     }
1154     return 0;
1155 }
1156
1157 static void mpmt_pthread_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
1158 {
1159     static int restart_num = 0;
1160     int no_detach = 0;
1161
1162     one_process = !!ap_exists_config_define("ONE_PROCESS");
1163     no_detach = !!ap_exists_config_define("NO_DETACH");
1164
1165     /* sigh, want this only the second time around */
1166     if (restart_num++ == 1) {
1167         is_graceful = 0;
1168
1169         if (!one_process && !no_detach) {
1170             apr_proc_detach();
1171         }
1172         ap_my_pid = getpid();
1173     }
1174
1175     unixd_pre_config(ptemp);
1176     ap_listen_pre_config();
1177     ap_daemons_to_start = DEFAULT_START_DAEMON;
1178     min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1179     max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1180     ap_daemons_limit = HARD_SERVER_LIMIT;
1181     ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1182     ap_pid_fname = DEFAULT_PIDLOG;
1183     ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1184     lock_fname = DEFAULT_LOCKFILE;
1185     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1186     ap_extended_status = 0;
1187
1188     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1189 }
1190
1191 static void mpmt_pthread_hooks(apr_pool_t *p)
1192 {
1193     INIT_SIGLIST()
1194     one_process = 0;
1195
1196     ap_hook_pre_config(mpmt_pthread_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1197 }
1198
1199
1200 static const char *set_pidfile(cmd_parms *cmd, void *dummy, const char *arg) 
1201 {
1202     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1203     if (err != NULL) {
1204         return err;
1205     }
1206
1207     if (cmd->server->is_virtual) {
1208         return "PidFile directive not allowed in <VirtualHost>";
1209     }
1210     ap_pid_fname = arg;
1211     return NULL;
1212 }
1213
1214 static const char *set_scoreboard(cmd_parms *cmd, void *dummy,
1215                                   const char *arg) 
1216 {
1217     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1218     if (err != NULL) {
1219         return err;
1220     }
1221
1222     ap_scoreboard_fname = arg;
1223     return NULL;
1224 }
1225
1226 static const char *set_lockfile(cmd_parms *cmd, void *dummy, const char *arg) 
1227 {
1228     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1229     if (err != NULL) {
1230         return err;
1231     }
1232
1233     lock_fname = arg;
1234     return NULL;
1235 }
1236
1237 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy,
1238                                         const char *arg) 
1239 {
1240     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1241     if (err != NULL) {
1242         return err;
1243     }
1244
1245     ap_daemons_to_start = atoi(arg);
1246     return NULL;
1247 }
1248
1249 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy,
1250                                          const char *arg)
1251 {
1252     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1253     if (err != NULL) {
1254         return err;
1255     }
1256
1257     min_spare_threads = atoi(arg);
1258     if (min_spare_threads <= 0) {
1259        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1260                     "WARNING: detected MinSpareThreads set to non-positive.");
1261        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1262                     "Resetting to 1 to avoid almost certain Apache failure.");
1263        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1264                     "Please read the documentation.");
1265        min_spare_threads = 1;
1266     }
1267        
1268     return NULL;
1269 }
1270
1271 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy,
1272                                          const char *arg)
1273 {
1274     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1275     if (err != NULL) {
1276         return err;
1277     }
1278
1279     max_spare_threads = atoi(arg);
1280     return NULL;
1281 }
1282
1283 static const char *set_server_limit (cmd_parms *cmd, void *dummy,
1284                                      const char *arg) 
1285 {
1286     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1287     if (err != NULL) {
1288         return err;
1289     }
1290
1291     ap_daemons_limit = atoi(arg);
1292     if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1293        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1294                     "WARNING: MaxClients of %d exceeds compile time limit "
1295                     "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1296        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1297                     " lowering MaxClients to %d.  To increase, please "
1298                     "see the", HARD_SERVER_LIMIT);
1299        ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1300                     " HARD_SERVER_LIMIT define in %s.",
1301                     AP_MPM_HARD_LIMITS_FILE);
1302        ap_daemons_limit = HARD_SERVER_LIMIT;
1303     } 
1304     else if (ap_daemons_limit < 1) {
1305         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1");
1306         ap_daemons_limit = 1;
1307     }
1308     return NULL;
1309 }
1310
1311 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy,
1312                                           const char *arg) 
1313 {
1314     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1315     if (err != NULL) {
1316         return err;
1317     }
1318
1319     ap_threads_per_child = atoi(arg);
1320     if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1321         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1322                      "WARNING: ThreadsPerChild of %d exceeds compile time"
1323                      "limit of %d threads,", ap_threads_per_child,
1324                      HARD_THREAD_LIMIT);
1325         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1326                      " lowering ThreadsPerChild to %d. To increase, please"
1327                      " see the", HARD_THREAD_LIMIT);
1328         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1329                      " HARD_THREAD_LIMIT define in %s.",
1330                      AP_MPM_HARD_LIMITS_FILE);
1331     }
1332     else if (ap_threads_per_child < 1) {
1333         ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
1334                      "WARNING: Require ThreadsPerChild > 0, setting to 1");
1335         ap_threads_per_child = 1;
1336     }
1337     return NULL;
1338 }
1339
1340 static const char *set_max_requests(cmd_parms *cmd, void *dummy,
1341                                     const char *arg) 
1342 {
1343     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1344     if (err != NULL) {
1345         return err;
1346     }
1347
1348     ap_max_requests_per_child = atoi(arg);
1349
1350     return NULL;
1351 }
1352
1353 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy,
1354                                     const char *arg) 
1355 {
1356     apr_finfo_t finfo;
1357     const char *fname;
1358     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1359     if (err != NULL) {
1360         return err;
1361     }
1362
1363     fname = ap_server_root_relative(cmd->pool, arg);
1364     if ((apr_stat(&finfo, fname, APR_FINFO_TYPE, cmd->pool) != APR_SUCCESS) 
1365         || (finfo.filetype != APR_DIR)) {
1366         return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname, 
1367                           " does not exist or is not a directory", NULL);
1368     }
1369     apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1370     return NULL;
1371 }
1372
1373 static const command_rec mpmt_pthread_cmds[] = {
1374 UNIX_DAEMON_COMMANDS
1375 LISTEN_COMMANDS
1376 AP_INIT_TAKE1("PidFile", set_pidfile, NULL, RSRC_CONF,
1377     "A file for logging the server process ID"),
1378 AP_INIT_TAKE1("ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF,
1379     "A file for Apache to maintain runtime process management information"),
1380 AP_INIT_TAKE1("LockFile", set_lockfile, NULL, RSRC_CONF,
1381     "The lockfile used when Apache needs to lock the accept() call"),
1382 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1383   "Number of child processes launched at server startup"),
1384 AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1385   "Minimum number of idle children, to handle request spikes"),
1386 AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1387   "Maximum number of idle children"),
1388 AP_INIT_TAKE1("MaxClients", set_server_limit, NULL, RSRC_CONF,
1389   "Maximum number of children alive at the same time"),
1390 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
1391   "Number of threads each child creates"),
1392 AP_INIT_TAKE1("MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF,
1393   "Maximum number of requests a particular child serves before dying."),
1394 AP_INIT_TAKE1("CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF,
1395   "The location of the directory Apache changes to before dumping core"),
1396 { NULL }
1397 };
1398
1399 module AP_MODULE_DECLARE_DATA mpm_mpmt_pthread_module = {
1400     MPM20_MODULE_STUFF,
1401     NULL,                       /* hook to run before apache parses args */
1402     NULL,                       /* create per-directory config structure */
1403     NULL,                       /* merge per-directory config structures */
1404     NULL,                       /* create per-server config structure */
1405     NULL,                       /* merge per-server config structures */
1406     mpmt_pthread_cmds,          /* command apr_table_t */
1407     mpmt_pthread_hooks          /* register_hooks */
1408 };
1409