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