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