upload http
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / server / mpm / beos / beos.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* The new BeOS MPM!
18  *
19  * This one basically is a single process multi threaded model, but 
20  * I couldn't be bothered adding the spmt_ to the front of the name!
21  * Anyway, this is still under development so it isn't yet the default
22  * choice.
23  */
24  
25 #define CORE_PRIVATE 
26  
27 #include <kernel/OS.h>
28 #include <unistd.h>
29 #include <sys/socket.h>
30 #include <signal.h>
31
32 #include "apr_strings.h"
33 #include "apr_portable.h"
34 #include "httpd.h" 
35 #include "http_main.h" 
36 #include "http_log.h" 
37 #include "http_config.h"        /* for read_config */ 
38 #include "http_core.h"          /* for get_remote_host */ 
39 #include "http_connection.h"
40 #include "ap_mpm.h"
41 #include "beosd.h"
42 #include "ap_listen.h"
43 #include "scoreboard.h" 
44 #include "mpm_common.h"
45 #include "mpm.h"
46 #include "mpm_default.h"
47 #include "apr_thread_mutex.h"
48 #include "apr_poll.h"
49
50 extern int _kset_fd_limit_(int num);
51
52 /* Limit on the total --- clients will be locked out if more servers than
53  * this are needed.  It is intended solely to keep the server from crashing
54  * when things get out of hand.
55  *
56  * We keep a hard maximum number of servers, for two reasons:
57  * 1) in case something goes seriously wrong, we want to stop the server starting
58  *    threads ad infinitum and crashing the server (remember that BeOS has a 192
59  *    thread per team limit).
60  * 2) it keeps the size of the scoreboard file small
61  *    enough that we can read the whole thing without worrying too much about
62  *    the overhead.
63  */
64
65 /* we only ever have 1 main process running... */ 
66 #define HARD_SERVER_LIMIT 1
67
68 /* Limit on the threads per process.  Clients will be locked out if more than
69  * this  * HARD_SERVER_LIMIT are needed.
70  *
71  * We keep this for one reason it keeps the size of the scoreboard file small
72  * enough that we can read the whole thing without worrying too much about
73  * the overhead.
74  */
75 #ifdef NO_THREADS
76 #define HARD_THREAD_LIMIT 1
77 #endif
78 #ifndef HARD_THREAD_LIMIT
79 #define HARD_THREAD_LIMIT 50 
80 #endif
81
82 /*
83  * Actual definitions of config globals
84  */
85
86 static int ap_threads_to_start=0;
87 static int ap_max_requests_per_thread = 0;
88 static int min_spare_threads=0;
89 static int max_spare_threads=0;
90 static int ap_thread_limit=0;
91 static int num_listening_sockets = 0;
92 static apr_socket_t ** listening_sockets;
93 apr_thread_mutex_t *accept_mutex = NULL;
94
95 static apr_pool_t *pconf;               /* Pool for config stuff */
96 static apr_pool_t *pchild;              /* Pool for httpd child stuff */
97
98 static int server_pid; 
99 static int mpm_state = AP_MPMQ_STARTING;
100
101 /* Keep track of the number of worker threads currently active */
102 static int worker_thread_count;
103 apr_thread_mutex_t *worker_thread_count_mutex;
104
105 /* The structure used to pass unique initialization info to each thread */
106 typedef struct {
107     int slot;
108     apr_pool_t *tpool;
109 } proc_info;
110
111 static void check_restart(void *data);
112
113 /*
114  * The max child slot ever assigned, preserved across restarts.  Necessary
115  * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We use 
116  * this value to optimize routines that have to scan the entire scoreboard.
117  */
118 int ap_max_child_assigned = -1;
119 int ap_max_threads_limit = -1;
120
121 static apr_socket_t *udp_sock;
122 static apr_sockaddr_t *udp_sa;
123
124 /* shared http_main globals... */
125
126 server_rec *ap_server_conf;
127
128 /* one_process */
129 static int one_process = 0;
130
131 #ifdef DEBUG_SIGSTOP
132 int raise_sigstop_flags;
133 #endif
134
135 /* a clean exit from a child with proper cleanup 
136    static void clean_child_exit(int code) __attribute__ ((noreturn)); */
137 static void clean_child_exit(int code)
138 {
139     if (pchild)
140         apr_pool_destroy(pchild);
141     exit(code);
142 }
143
144 /* handle all varieties of core dumping signals */
145 static void sig_coredump(int sig)
146 {
147     chdir(ap_coredump_dir);
148     signal(sig, SIG_DFL);
149     kill(server_pid, sig);
150     /* At this point we've got sig blocked, because we're still inside
151      * the signal handler.  When we leave the signal handler it will
152      * be unblocked, and we'll take the signal... and coredump or whatever
153      * is appropriate for this particular Unix.  In addition the parent
154      * will see the real signal we received -- whereas if we called
155      * abort() here, the parent would only see SIGABRT.
156      */
157 }
158
159 /*****************************************************************
160  * Connection structures and accounting...
161  */
162
163 /* volatile just in case */
164 static int volatile shutdown_pending;
165 static int volatile restart_pending;
166 static int volatile is_graceful;
167 static int volatile child_fatal;
168 ap_generation_t volatile ap_my_generation = 0;
169
170 /*
171  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
172  * functions to initiate shutdown or restart without relying on signals. 
173  * Previously this was initiated in sig_term() and restart() signal handlers, 
174  * but we want to be able to start a shutdown/restart from other sources --
175  * e.g. on Win32, from the service manager. Now the service manager can
176  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
177  * these functions can also be called by the child processes, since global
178  * variables are no longer used to pass on the required action to the parent.
179  *
180  * These should only be called from the parent process itself, since the
181  * parent process will use the shutdown_pending and restart_pending variables
182  * to determine whether to shutdown or restart. The child process should
183  * call signal_parent() directly to tell the parent to die -- this will
184  * cause neither of those variable to be set, which the parent will
185  * assume means something serious is wrong (which it will be, for the
186  * child to force an exit) and so do an exit anyway.
187  */
188
189 static void ap_start_shutdown(void)
190 {
191     mpm_state = AP_MPMQ_STOPPING;
192  
193     if (shutdown_pending == 1) {
194         /* Um, is this _probably_ not an error, if the user has
195          * tried to do a shutdown twice quickly, so we won't
196          * worry about reporting it.
197          */
198         return;
199     }
200     shutdown_pending = 1;
201 }
202
203 /* do a graceful restart if graceful == 1 */
204 static void ap_start_restart(int graceful)
205 {
206     mpm_state = AP_MPMQ_STOPPING;
207
208     if (restart_pending == 1) {
209         /* Probably not an error - don't bother reporting it */
210         return;
211     }
212     restart_pending = 1;
213     is_graceful = graceful;
214 }
215
216 static void sig_term(int sig)
217 {
218     ap_start_shutdown();
219 }
220
221 static void restart(int sig)
222 {
223     ap_start_restart(sig == AP_SIG_GRACEFUL);
224 }
225
226 static void tell_workers_to_exit(void)
227 {
228     apr_size_t len;
229     int i = 0;
230
231     mpm_state = AP_MPMQ_STOPPING;
232
233     for (i = 0 ; i < ap_max_child_assigned; i++){
234         len = 4;
235         if (apr_sendto(udp_sock, udp_sa, 0, "die!", &len) != APR_SUCCESS)
236             break;
237     }   
238 }
239
240 static void set_signals(void)
241 {
242     struct sigaction sa;
243
244     sigemptyset(&sa.sa_mask);
245     sa.sa_flags = 0;
246
247     if (!one_process) {
248         sa.sa_handler = sig_coredump;
249
250         if (sigaction(SIGSEGV, &sa, NULL) < 0)
251             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
252         if (sigaction(SIGBUS, &sa, NULL) < 0)
253             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
254         if (sigaction(SIGABRT, &sa, NULL) < 0)
255             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
256         if (sigaction(SIGILL, &sa, NULL) < 0)
257             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
258         sa.sa_flags = 0;
259     }
260     sa.sa_handler = sig_term;
261     if (sigaction(SIGTERM, &sa, NULL) < 0)
262             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
263     if (sigaction(SIGINT, &sa, NULL) < 0)
264         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
265     
266     sa.sa_handler = SIG_IGN;
267     if (sigaction(SIGPIPE, &sa, NULL) < 0)
268         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
269
270     /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy 
271      * processing one */
272     sigaddset(&sa.sa_mask, SIGHUP);
273     sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
274     sa.sa_handler = restart;
275     if (sigaction(SIGHUP, &sa, NULL) < 0)
276         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
277     if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
278             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
279 }
280
281 /*****************************************************************
282  * Here follows a long bunch of generic server bookkeeping stuff...
283  */
284
285 int ap_graceful_stop_signalled(void)
286 {
287     /* XXX - Does this really work? - Manoj */
288     return is_graceful;
289 }
290
291 /*****************************************************************
292  * Child process main loop.
293  */
294
295 static void process_socket(apr_pool_t *p, apr_socket_t *sock,
296                            int my_child_num, apr_bucket_alloc_t *bucket_alloc)
297 {
298     conn_rec *current_conn;
299     long conn_id = my_child_num;
300     int csd;
301     ap_sb_handle_t *sbh;
302
303     (void)apr_os_sock_get(&csd, sock);
304     
305     if (csd >= FD_SETSIZE) {
306         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
307                      "filedescriptor (%u) larger than FD_SETSIZE (%u) "
308                      "found, you probably need to rebuild Apache with a "
309                      "larger FD_SETSIZE", csd, FD_SETSIZE);
310         apr_socket_close(sock);
311         return;
312     }
313
314     ap_create_sb_handle(&sbh, p, 0, my_child_num);
315     current_conn = ap_run_create_connection(p, ap_server_conf,
316                                             sock, conn_id, sbh,
317                                             bucket_alloc);
318
319     if (current_conn) {
320         ap_process_connection(current_conn, sock);
321         ap_lingering_close(current_conn);
322     }
323 }
324
325 static int32 worker_thread(void * dummy)
326 {
327     proc_info * ti = dummy;
328     int child_slot = ti->slot;
329     apr_pool_t *tpool = ti->tpool;
330     apr_allocator_t *allocator;
331     apr_socket_t *csd = NULL;
332     apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
333     apr_bucket_alloc_t *bucket_alloc;
334     apr_socket_t *sd = NULL;
335     apr_status_t rv = APR_EINIT;
336     int srv , n;
337     int curr_pollfd = 0, last_pollfd = 0;
338     sigset_t sig_mask;
339     int requests_this_child = ap_max_requests_per_thread;
340     apr_pollfd_t *pollset;
341     /* each worker thread is in control of its own destiny...*/
342     int this_worker_should_exit = 0; 
343     free(ti);
344
345     mpm_state = AP_MPMQ_STARTING;
346
347     on_exit_thread(check_restart, (void*)child_slot);
348           
349     /* block the signals for this thread */
350     sigfillset(&sig_mask);
351     sigprocmask(SIG_BLOCK, &sig_mask, NULL);
352
353     apr_allocator_create(&allocator);
354     apr_allocator_max_free_set(allocator, ap_max_mem_free);
355     apr_pool_create_ex(&ptrans, tpool, NULL, allocator);
356     apr_allocator_owner_set(allocator, ptrans);
357
358     apr_pool_tag(ptrans, "transaction");
359
360     bucket_alloc = apr_bucket_alloc_create_ex(allocator);
361
362     apr_thread_mutex_lock(worker_thread_count_mutex);
363     worker_thread_count++;
364     apr_thread_mutex_unlock(worker_thread_count_mutex);
365
366     (void) ap_update_child_status_from_indexes(0, child_slot, SERVER_STARTING,
367                                                (request_rec*)NULL);
368                                   
369     apr_poll_setup(&pollset, num_listening_sockets + 1, tpool);
370     for(n=0 ; n <= num_listening_sockets ; n++)
371         apr_poll_socket_add(pollset, listening_sockets[n], APR_POLLIN);
372
373     mpm_state = AP_MPMQ_RUNNING;
374
375     while (1) {
376         /* If we're here, then chances are (unless we're the first thread created) 
377          * we're going to be held up in the accept mutex, so doing this here
378          * shouldn't hurt performance.
379          */
380
381         this_worker_should_exit |= (ap_max_requests_per_thread != 0) && (requests_this_child <= 0);
382         
383         if (this_worker_should_exit) break;
384
385         (void) ap_update_child_status_from_indexes(0, child_slot, SERVER_READY,
386                                                    (request_rec*)NULL);
387
388         apr_thread_mutex_lock(accept_mutex);
389
390         while (!this_worker_should_exit) {
391             apr_int16_t event;
392             apr_status_t ret;
393
394             ret = apr_poll(pollset, num_listening_sockets + 1, &srv, -1);
395
396             if (ret != APR_SUCCESS) {
397                 if (APR_STATUS_IS_EINTR(ret)) {
398                     continue;
399                 }
400                 /* poll() will only return errors in catastrophic
401                  * circumstances. Let's try exiting gracefully, for now. */
402                 ap_log_error(APLOG_MARK, APLOG_ERR, ret, (const server_rec *)
403                              ap_server_conf, "apr_poll: (listen)");
404                 this_worker_should_exit = 1;
405             } else {
406                 /* if we've bailed in apr_poll what's the point of trying to use the data? */
407                 apr_poll_revents_get(&event, listening_sockets[0], pollset);
408
409                 if (event & APR_POLLIN){
410                     apr_sockaddr_t *rec_sa;
411                     apr_size_t len = 5;
412                     char *tmpbuf = apr_palloc(ptrans, sizeof(char) * 5);
413                     apr_sockaddr_info_get(&rec_sa, "127.0.0.1", APR_UNSPEC, 7772, 0, ptrans);
414                     
415                     if ((ret = apr_recvfrom(rec_sa, listening_sockets[0], 0, tmpbuf, &len))
416                         != APR_SUCCESS){
417                         ap_log_error(APLOG_MARK, APLOG_ERR, ret, NULL, 
418                             "error getting data from UDP!!");
419                     }else {
420                         /* add checking??? */              
421                     }
422                     this_worker_should_exit = 1;
423                 }
424             }
425           
426             if (this_worker_should_exit) break;
427
428             if (num_listening_sockets == 1) {
429                 sd = ap_listeners->sd;
430                 goto got_fd;
431             }
432             else {
433                 /* find a listener */
434                 curr_pollfd = last_pollfd;
435                 do {
436                     curr_pollfd++;
437
438                     if (curr_pollfd > num_listening_sockets)
439                         curr_pollfd = 1;
440                     
441                     /* Get the revent... */
442                     apr_poll_revents_get(&event, listening_sockets[curr_pollfd], pollset);
443                     
444                     if (event & APR_POLLIN) {
445                         last_pollfd = curr_pollfd;
446                         sd = listening_sockets[curr_pollfd];
447                         goto got_fd;
448                     }
449                 } while (curr_pollfd != last_pollfd);
450             }
451         }
452     got_fd:
453
454         if (!this_worker_should_exit) {
455             rv = apr_accept(&csd, sd, ptrans);
456
457             apr_thread_mutex_unlock(accept_mutex);
458             if (rv != APR_SUCCESS) {
459                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
460                   "apr_accept");
461             } else {
462                 process_socket(ptrans, csd, child_slot, bucket_alloc);
463                 requests_this_child--;
464             }
465         }
466         else {
467             apr_thread_mutex_unlock(accept_mutex);
468             break;
469         }
470         apr_pool_clear(ptrans);
471     }
472
473     ap_update_child_status_from_indexes(0, child_slot, SERVER_DEAD, (request_rec*)NULL);
474
475     apr_bucket_alloc_destroy(bucket_alloc);
476
477     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
478                  "worker_thread %ld exiting", find_thread(NULL));
479     
480     apr_thread_mutex_lock(worker_thread_count_mutex);
481     worker_thread_count--;
482     apr_thread_mutex_unlock(worker_thread_count_mutex);
483
484     return (0);
485 }
486
487 static int make_worker(int slot)
488 {
489     thread_id tid;
490     proc_info *my_info = (proc_info *)malloc(sizeof(proc_info)); /* freed by thread... */
491
492     if (my_info == NULL) {
493         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
494             "malloc: out of memory");
495         clean_child_exit(APEXIT_CHILDFATAL);
496     }
497     
498     my_info->slot = slot;
499     apr_pool_create(&my_info->tpool, pchild);
500     
501     if (slot + 1 > ap_max_child_assigned)
502             ap_max_child_assigned = slot + 1;
503
504     if (one_process) {
505         set_signals();
506         ap_scoreboard_image->parent[0].pid = getpid();
507         return 0;
508     }
509
510     (void) ap_update_child_status_from_indexes(0, slot, SERVER_STARTING, (request_rec*)NULL);
511     tid = spawn_thread(worker_thread, "apache_worker", B_NORMAL_PRIORITY,
512         my_info);
513     if (tid < B_NO_ERROR) {
514         ap_log_error(APLOG_MARK, APLOG_ERR, errno, NULL, 
515             "spawn_thread: Unable to start a new thread");
516         /* In case system resources are maxxed out, we don't want
517          * Apache running away with the CPU trying to fork over and
518          * over and over again. 
519          */
520         (void) ap_update_child_status_from_indexes(0, slot, SERVER_DEAD, 
521                                                    (request_rec*)NULL);
522         
523         sleep(10);
524         free(my_info);
525         
526         return -1;
527     }
528     resume_thread(tid);
529
530     ap_scoreboard_image->servers[0][slot].tid = tid;
531     return 0;
532 }
533
534 static void check_restart(void *data)
535 {
536     if (!restart_pending && !shutdown_pending) {
537         int slot = (int)data;
538         make_worker(slot);
539         ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, 
540             "spawning a new worker thread in slot %d", slot);
541     }
542 }
543
544 /* start up a bunch of children */
545 static void startup_threads(int number_to_start)
546 {
547     int i;
548
549     for (i = 0; number_to_start && i < ap_thread_limit; ++i) {
550         if (ap_scoreboard_image->servers[0][i].tid) {
551             continue;
552         }
553         if (make_worker(i) < 0) {
554             break;
555         }
556         --number_to_start;
557     }
558 }
559
560
561 /*
562  * spawn_rate is the number of children that will be spawned on the
563  * next maintenance cycle if there aren't enough idle servers.  It is
564  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
565  * without the need to spawn.
566  */
567 static int spawn_rate = 1;
568 #ifndef MAX_SPAWN_RATE
569 #define MAX_SPAWN_RATE  (32)
570 #endif
571 static int hold_off_on_exponential_spawning;
572
573 static void perform_idle_server_maintenance(void)
574 {
575     int i;
576     int free_length;
577     int free_slots[MAX_SPAWN_RATE];
578     int last_non_dead  = -1;
579
580     /* initialize the free_list */
581     free_length = 0;
582
583     for (i = 0; i < ap_thread_limit; ++i) {
584         if (ap_scoreboard_image->servers[0][i].tid == 0) {
585             if (free_length < spawn_rate) {
586                 free_slots[free_length] = i;
587                 ++free_length;
588             }
589         }
590         else {
591             last_non_dead = i;
592         }
593
594         if (i >= ap_max_child_assigned && free_length >= spawn_rate) {
595                  break;
596             }
597     }
598     ap_max_child_assigned = last_non_dead + 1;
599
600     if (free_length > 0) {
601         for (i = 0; i < free_length; ++i) {
602                 make_worker(free_slots[i]);
603             }
604             /* the next time around we want to spawn twice as many if this
605              * wasn't good enough, but not if we've just done a graceful
606              */
607             if (hold_off_on_exponential_spawning) {
608                 --hold_off_on_exponential_spawning;
609             } else if (spawn_rate < MAX_SPAWN_RATE) {
610                 spawn_rate *= 2;
611             }
612     } else {
613         spawn_rate = 1;
614     }
615 }
616
617 static void server_main_loop(int remaining_threads_to_start)
618 {
619     int child_slot;
620     apr_exit_why_e exitwhy;
621     int status;
622     apr_proc_t pid;
623     int i;
624
625     while (!restart_pending && !shutdown_pending) {
626
627         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
628          
629         if (pid.pid >= 0) {
630             if (ap_process_child_status(&pid, exitwhy, status) == APEXIT_CHILDFATAL) {
631                 shutdown_pending = 1;
632                 child_fatal = 1;
633                 return;
634             }
635             /* non-fatal death... note that it's gone in the scoreboard. */
636             child_slot = -1;
637             for (i = 0; i < ap_max_child_assigned; ++i) {
638                 if (ap_scoreboard_image->servers[0][i].tid == pid.pid) {
639                     child_slot = i;
640                     break;
641                 }
642             }
643             if (child_slot >= 0) {
644                 ap_scoreboard_image->servers[0][child_slot].tid = 0;
645                 (void) ap_update_child_status_from_indexes(0, child_slot, 
646                                                            SERVER_DEAD, 
647                                                            (request_rec*)NULL);
648                 
649                 if (remaining_threads_to_start
650                             && child_slot < ap_thread_limit) {
651                     /* we're still doing a 1-for-1 replacement of dead
652                      * children with new children
653                      */
654                     make_worker(child_slot);
655                     --remaining_threads_to_start;
656                         }
657 #if APR_HAS_OTHER_CHILD
658             }
659             else if (apr_proc_other_child_read(&pid, status) == 0) {
660                 /* handled */
661 #endif
662             }
663             else if (is_graceful) {
664                 /* Great, we've probably just lost a slot in the
665                  * scoreboard.  Somehow we don't know about this
666                  * child.
667                  */
668                  ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf,
669                                           "long lost child came home! (pid %ld)", pid.pid);
670             }
671             
672             /* Don't perform idle maintenance when a child dies,
673              * only do it when there's a timeout.  Remember only a
674              * finite number of children can die, and it's pretty
675              * pathological for a lot to die suddenly.
676              */
677              continue;
678          }
679              else if (remaining_threads_to_start) {
680              /* we hit a 1 second timeout in which none of the previous
681               * generation of children needed to be reaped... so assume
682               * they're all done, and pick up the slack if any is left.
683               */
684               startup_threads(remaining_threads_to_start);
685               remaining_threads_to_start = 0;
686               /* In any event we really shouldn't do the code below because
687                * few of the servers we just started are in the IDLE state
688                * yet, so we'd mistakenly create an extra server.
689                */
690               continue;
691          }
692          perform_idle_server_maintenance();
693     }
694 }
695
696 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
697 {
698     switch(query_code){
699         case AP_MPMQ_MAX_DAEMON_USED:
700             *result = ap_max_child_assigned;
701             return APR_SUCCESS;
702         case AP_MPMQ_IS_THREADED:
703             *result = AP_MPMQ_DYNAMIC;
704             return APR_SUCCESS;
705         case AP_MPMQ_IS_FORKED:
706             *result = AP_MPMQ_NOT_SUPPORTED;
707             return APR_SUCCESS;
708         case AP_MPMQ_HARD_LIMIT_DAEMONS:
709             *result = HARD_SERVER_LIMIT;
710             return APR_SUCCESS;
711         case AP_MPMQ_HARD_LIMIT_THREADS:
712             *result = HARD_THREAD_LIMIT;
713             return APR_SUCCESS;
714         case AP_MPMQ_MAX_THREADS:
715             *result = HARD_THREAD_LIMIT;
716             return APR_SUCCESS;
717         case AP_MPMQ_MIN_SPARE_DAEMONS:
718             *result = 0;
719             return APR_SUCCESS;
720         case AP_MPMQ_MIN_SPARE_THREADS:    
721             *result = max_spare_threads;
722             return APR_SUCCESS;
723         case AP_MPMQ_MAX_SPARE_DAEMONS:
724             *result = 0;
725             return APR_SUCCESS;
726         case AP_MPMQ_MAX_SPARE_THREADS:
727             *result = min_spare_threads;
728             return APR_SUCCESS;
729         case AP_MPMQ_MAX_REQUESTS_DAEMON:
730             *result = ap_max_requests_per_thread;
731             return APR_SUCCESS;
732         case AP_MPMQ_MAX_DAEMONS:
733             *result = HARD_SERVER_LIMIT;
734             return APR_SUCCESS;
735         case AP_MPMQ_MPM_STATE:
736             *result = mpm_state;
737             return APR_SUCCESS;
738     }
739     return APR_ENOTIMPL;
740 }
741
742 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
743 {
744     int remaining_threads_to_start, i,j;
745     apr_status_t rv;
746     ap_listen_rec *lr;    
747     pconf = _pconf;
748     ap_server_conf = s;
749
750     /* Increase the available pool of fd's.  This code from
751      * Joe Kloss <joek@be.com>
752      */
753     if( FD_SETSIZE > 128 && (i = _kset_fd_limit_( 128 )) < 0 ){
754         ap_log_error(APLOG_MARK, APLOG_ERR, i, s,
755             "could not set FD_SETSIZE (_kset_fd_limit_ failed)");
756     }
757
758     /* BeOS R5 doesn't support pipes on select() calls, so we use a 
759        UDP socket as these are supported in both R5 and BONE.  If we only cared
760        about BONE we'd use a pipe, but there it is.
761        As we have UDP support in APR, now use the APR functions and check all the
762        return values...
763       */
764     if (apr_sockaddr_info_get(&udp_sa, "127.0.0.1", APR_UNSPEC, 7772, 0, _pconf)
765         != APR_SUCCESS){
766         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
767             "couldn't create control socket information, shutting down");
768         return 1;
769     }
770     if (apr_socket_create(&udp_sock, udp_sa->family, SOCK_DGRAM,
771                       _pconf) != APR_SUCCESS){
772         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
773             "couldn't create control socket, shutting down");
774         return 1;
775     }
776     if (apr_bind(udp_sock, udp_sa) != APR_SUCCESS){
777         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
778             "couldn't bind UDP socket!");
779         return 1;
780     }
781  
782     if ((num_listening_sockets = ap_setup_listeners(ap_server_conf)) < 1) {
783         ap_log_error(APLOG_MARK, APLOG_ALERT, 0, s,
784             "no listening sockets available, shutting down");
785         return 1;
786     }
787
788     ap_log_pid(pconf, ap_pid_fname);
789
790     /*
791      * Create our locks... 
792      */
793     
794     /* accept_mutex
795      * used to lock around select so we only have one thread
796      * in select at a time
797      */
798     rv = apr_thread_mutex_create(&accept_mutex, 0, pconf);
799     if (rv != APR_SUCCESS) {
800         /* tsch tsch, can't have more than one thread in the accept loop
801            at a time so we need to fall on our sword... */
802         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
803                      "Couldn't create accept lock");
804         return 1;
805     }
806
807     /* worker_thread_count_mutex
808      * locks the worker_thread_count so we have ana ccurate count...
809      */
810     rv = apr_thread_mutex_create(&worker_thread_count_mutex, 0, pconf);
811     if (rv != APR_SUCCESS) {
812         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
813                      "Couldn't create worker thread count lock");
814         return 1;
815     }
816
817     /*
818      * Startup/shutdown... 
819      */
820     
821     if (!is_graceful) {
822         /* setup the scoreboard shared memory */
823         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
824             return 1;
825         }
826
827         for (i = 0; i < HARD_SERVER_LIMIT; i++) {
828             ap_scoreboard_image->parent[i].pid = 0;
829             for (j = 0;j < HARD_THREAD_LIMIT; j++)
830                 ap_scoreboard_image->servers[i][j].tid = 0;
831         }
832     }
833
834     if (HARD_SERVER_LIMIT == 1)
835         ap_scoreboard_image->parent[0].pid = getpid();
836
837     set_signals();
838
839     /* Sanity checks to avoid thrashing... */
840     if (max_spare_threads < min_spare_threads )
841         max_spare_threads = min_spare_threads;
842
843     /* If we're doing a graceful_restart then we're going to see a lot
844      * of threads exiting immediately when we get into the main loop
845      * below (because we just sent them AP_SIG_GRACEFUL).  This happens 
846      * pretty rapidly... and for each one that exits we'll start a new one 
847      * until we reach at least threads_min_free.  But we may be permitted to
848      * start more than that, so we'll just keep track of how many we're
849      * supposed to start up without the 1 second penalty between each fork.
850      */
851     remaining_threads_to_start = ap_threads_to_start;
852     /* sanity check on the number to start... */
853     if (remaining_threads_to_start > ap_thread_limit) {
854             remaining_threads_to_start = ap_thread_limit;
855     }
856
857     /* setup the child pool to use for the workers.  Each worker creates
858      * a seperate pool of its own to use.
859      */
860     apr_pool_create(&pchild, pconf);
861
862     /* Now that we have the child pool (pchild) we can allocate
863      * the listenfds and creat the pollset...
864      */
865     listening_sockets = apr_palloc(pchild,
866        sizeof(*listening_sockets) * (num_listening_sockets + 1));
867
868     listening_sockets[0] = udp_sock;
869     for (lr = ap_listeners, i = 1; i <= num_listening_sockets; lr = lr->next, ++i)
870             listening_sockets[i]=lr->sd;
871
872     /* we assume all goes OK...hmm might want to check that! */
873     /* if we're in one_process mode we don't want to start threads
874      * do we??
875      */
876     if (!is_graceful && !one_process) {
877             startup_threads(remaining_threads_to_start);
878             remaining_threads_to_start = 0;
879     }
880     else {
881             /* give the system some time to recover before kicking into
882              * exponential mode */
883         hold_off_on_exponential_spawning = 10;
884     }
885
886     /*
887      * record that we've entered the world !
888      */
889     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
890                 "%s configured -- resuming normal operations",
891                 ap_get_server_version());
892
893     ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
894                 "Server built: %s", ap_get_server_built());
895
896     restart_pending = shutdown_pending = 0;
897
898     /*
899      * main_loop until it's all over
900      */
901     if (!one_process) {
902         server_main_loop(remaining_threads_to_start);
903     
904         tell_workers_to_exit(); /* if we get here we're exiting... */
905         sleep(1); /* give them a brief chance to exit */
906     } else {
907         proc_info *my_info = (proc_info *)malloc(sizeof(proc_info));
908         my_info->slot = 0;
909         apr_pool_create(&my_info->tpool, pchild);
910         worker_thread(my_info);
911     }
912         
913     /* close the UDP socket we've been using... */
914     apr_socket_close(listening_sockets[0]);
915
916     if ((one_process || shutdown_pending) && !child_fatal) {
917         const char *pidfile = NULL;
918         pidfile = ap_server_root_relative (pconf, ap_pid_fname);
919         if ( pidfile != NULL && unlink(pidfile) == 0)
920             ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
921                          "removed PID file %s (pid=%ld)", pidfile, 
922                          (long)getpid());
923     }
924
925     if (one_process) {
926         return 1;
927     }
928         
929     /*
930      * If we get here we're shutting down...
931      */
932     if (shutdown_pending) {
933         /* Time to gracefully shut down:
934          * Kill child processes, tell them to call child_exit, etc...
935          */
936         if (beosd_killpg(getpgrp(), SIGTERM) < 0)
937             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
938              "killpg SIGTERM");
939       
940         /* use ap_reclaim_child_processes starting with SIGTERM */
941         ap_reclaim_child_processes(1);
942
943         if (!child_fatal) {         /* already recorded */
944             /* record the shutdown in the log */
945             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
946                          "caught SIGTERM, shutting down");
947         }
948     
949         return 1;
950     }
951
952     /* we've been told to restart */
953     signal(SIGHUP, SIG_IGN);
954
955     if (is_graceful) {
956         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
957                     AP_SIG_GRACEFUL_STRING " received.  Doing graceful restart");
958     }
959     else {
960         /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
961          * and a SIGHUP, we may as well use the same signal, because some user
962          * pthreads are stealing signals from us left and right.
963          */
964             
965         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
966             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
967                     "SIGHUP received.  Attempting to restart");
968     }
969     
970     /* just before we go, tidy up the locks we've created to prevent a 
971      * potential leak of semaphores... */
972     apr_thread_mutex_destroy(worker_thread_count_mutex);
973     apr_thread_mutex_destroy(accept_mutex);
974     
975     return 0;
976 }
977
978 static int beos_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
979 {
980     static int restart_num = 0;
981     int no_detach, debug, foreground;
982     apr_status_t rv;
983
984     mpm_state = AP_MPMQ_STARTING;
985
986     debug = ap_exists_config_define("DEBUG");
987
988     if (debug) {
989         foreground = one_process = 1;
990         no_detach = 0;
991     }
992     else
993     {
994         one_process = ap_exists_config_define("ONE_PROCESS");
995         no_detach = ap_exists_config_define("NO_DETACH");
996         foreground = ap_exists_config_define("FOREGROUND");
997     }
998
999     /* sigh, want this only the second time around */
1000     if (restart_num++ == 1) {
1001         is_graceful = 0;
1002         
1003         if (!one_process && !foreground) {
1004             rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1005                                            : APR_PROC_DETACH_DAEMONIZE);
1006             if (rv != APR_SUCCESS) {
1007                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1008                              "apr_proc_detach failed");
1009                 return HTTP_INTERNAL_SERVER_ERROR;
1010             }                  
1011         }
1012
1013         server_pid = getpid();
1014     }
1015
1016     beosd_pre_config();
1017     ap_listen_pre_config();
1018     ap_threads_to_start = DEFAULT_START_THREADS;
1019     min_spare_threads = DEFAULT_MIN_FREE_THREADS;
1020     max_spare_threads = DEFAULT_MAX_FREE_THREADS;
1021     ap_thread_limit = HARD_THREAD_LIMIT;
1022     ap_pid_fname = DEFAULT_PIDLOG;
1023     ap_max_requests_per_thread = DEFAULT_MAX_REQUESTS_PER_THREAD;
1024 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
1025         ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
1026 #endif
1027
1028     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1029
1030     return OK;
1031 }
1032
1033 static void beos_hooks(apr_pool_t *p)
1034 {
1035     one_process = 0;
1036     
1037     ap_hook_pre_config(beos_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST); 
1038 }
1039
1040 static const char *set_threads_to_start(cmd_parms *cmd, void *dummy, const char *arg) 
1041 {
1042     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1043     if (err != NULL) {
1044         return err;
1045     }
1046
1047     ap_threads_to_start = atoi(arg);
1048     if (ap_threads_to_start < 0) {
1049         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1050                      "StartThreads set to a value less than 0, reset to 1");
1051         ap_threads_to_start = 1;
1052     }
1053     return NULL;
1054 }
1055
1056 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1057 {
1058     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1059     if (err != NULL) {
1060         return err;
1061     }
1062
1063     min_spare_threads = atoi(arg);
1064     if (min_spare_threads <= 0) {
1065        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
1066                     "WARNING: detected MinSpareThreads set to non-positive.");
1067        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1068                     "Resetting to 1 to avoid almost certain Apache failure.");
1069        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
1070                     "Please read the documentation.");
1071        min_spare_threads = 1;
1072     }
1073        
1074     return NULL;
1075 }
1076
1077 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1078 {
1079     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1080     if (err != NULL) {
1081         return err;
1082     }
1083
1084     max_spare_threads = atoi(arg);
1085     return NULL;
1086 }
1087
1088 static const char *set_threads_limit (cmd_parms *cmd, void *dummy, const char *arg) 
1089 {
1090     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1091     if (err != NULL) {
1092         return err;
1093     }
1094
1095     ap_thread_limit = atoi(arg);
1096     if (ap_thread_limit > HARD_THREAD_LIMIT) {
1097        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
1098                     "WARNING: MaxClients of %d exceeds compile time limit "
1099                     "of %d servers,", ap_thread_limit, HARD_THREAD_LIMIT);
1100        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
1101                     " lowering MaxClients to %d.  To increase, please "
1102                     "see the", HARD_THREAD_LIMIT);
1103        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
1104                     " HARD_THREAD_LIMIT define in server/mpm/beos/mpm_default.h.");
1105        ap_thread_limit = HARD_THREAD_LIMIT;
1106     } 
1107     else if (ap_thread_limit < 1) {
1108         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
1109                      "WARNING: Require MaxClients > 0, setting to %d", HARD_THREAD_LIMIT);
1110         ap_thread_limit = HARD_THREAD_LIMIT;
1111     }
1112     return NULL;
1113 }
1114
1115 static const char *set_max_requests_per_thread (cmd_parms *cmd, void *dummy, const char *arg)
1116 {
1117     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1118     if (err != NULL) {
1119         return err;
1120     }
1121
1122     ap_max_requests_per_thread = atoi(arg);
1123     if (ap_max_requests_per_thread < 0) {
1124         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1125                      "WARNING: MaxRequestsPerThread was set below 0"
1126                      "reset to 0, but this may not be what you want.");
1127         ap_max_requests_per_thread = 0;
1128     }
1129
1130     return NULL;
1131 }
1132
1133 static const command_rec beos_cmds[] = {
1134 BEOS_DAEMON_COMMANDS,
1135 LISTEN_COMMANDS,
1136 AP_INIT_TAKE1( "StartThreads", set_threads_to_start, NULL, RSRC_CONF,
1137   "Number of threads to launch at server startup"),
1138 AP_INIT_TAKE1( "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1139   "Minimum number of idle children, to handle request spikes"),
1140 AP_INIT_TAKE1( "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1141   "Maximum number of idle children" ),
1142 AP_INIT_TAKE1( "MaxClients", set_threads_limit, NULL, RSRC_CONF, 
1143   "Maximum number of children alive at the same time (max threads)" ),
1144 AP_INIT_TAKE1( "MaxRequestsPerThread", set_max_requests_per_thread, NULL, RSRC_CONF,
1145   "Maximum number of requests served by a thread" ),
1146 { NULL }
1147 };
1148
1149 module AP_MODULE_DECLARE_DATA mpm_beos_module = {
1150     MPM20_MODULE_STUFF,
1151     NULL,                       /* hook to run before apache parses args */
1152     NULL,                       /* create per-directory config structure */
1153     NULL,                       /* merge per-directory config structures */
1154     NULL,                       /* create per-server config structure */
1155     NULL,                       /* merge per-server config structures */
1156     beos_cmds,          /* command apr_table_t */
1157     beos_hooks          /* register_hooks */
1158 };
1159