]> granicus.if.org Git - apache/blob - server/mpm/beos/beos.c
Create pmain pool and run modules' child_init hooks when entering
[apache] / 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 BeOS MPM!
18  *
19  * This is a single process, with multiple worker threads.
20  *
21  * Under testing I found that given the inability of BeOS to handle threads
22  * and forks it didn't make sense to try and have a set of "children" threads
23  * that spawned the "worker" threads, so just missed out the middle mand and
24  * somehow arrived here.
25  *
26  * For 2.1 this has been rewritten to have simpler logic, though there is still
27  * some simplification that can be done. It's still a work in progress!
28  *
29  * TODO Items
30  *
31  * - on exit most worker threads segfault trying to access a kernel page.
32  */
33
34 #define CORE_PRIVATE
35
36 #include <kernel/OS.h>
37 #include <unistd.h>
38 #include <sys/socket.h>
39 #include <signal.h>
40
41 #include "apr_strings.h"
42 #include "apr_portable.h"
43 #include "httpd.h"
44 #include "http_main.h"
45 #include "http_log.h"
46 #include "http_config.h"        /* for read_config */
47 #include "http_core.h"          /* for get_remote_host */
48 #include "http_connection.h"
49 #include "ap_mpm.h"
50 #include "beosd.h"
51 #include "ap_listen.h"
52 #include "scoreboard.h"
53 #include "mpm_common.h"
54 #include "mpm.h"
55 #include "mpm_default.h"
56 #include "apr_thread_mutex.h"
57 #include "apr_poll.h"
58
59 extern int _kset_fd_limit_(int num);
60
61 /* Limit on the total --- clients will be locked out if more servers than
62  * this are needed.  It is intended solely to keep the server from crashing
63  * when things get out of hand.
64  *
65  * We keep a hard maximum number of servers, for two reasons:
66  * 1) in case something goes seriously wrong, we want to stop the server starting
67  *    threads ad infinitum and crashing the server (remember that BeOS has a 192
68  *    thread per team limit).
69  * 2) it keeps the size of the scoreboard file small
70  *    enough that we can read the whole thing without worrying too much about
71  *    the overhead.
72  */
73
74 /* we only ever have 1 main process running... */
75 #define HARD_SERVER_LIMIT 1
76
77 /* Limit on the threads per process.  Clients will be locked out if more than
78  * this  * HARD_SERVER_LIMIT are needed.
79  *
80  * We keep this for one reason it keeps the size of the scoreboard file small
81  * enough that we can read the whole thing without worrying too much about
82  * the overhead.
83  */
84 #ifdef NO_THREADS
85 #define HARD_THREAD_LIMIT 1
86 #endif
87 #ifndef HARD_THREAD_LIMIT
88 #define HARD_THREAD_LIMIT 50
89 #endif
90
91 /*
92  * Actual definitions of config globals
93  */
94
95 static int ap_threads_to_start=0;
96 static int ap_max_requests_per_thread = 0;
97 static int min_spare_threads=0;
98 static int max_spare_threads=0;
99 static int ap_thread_limit=0;
100 static int num_listening_sockets = 0;
101 static int mpm_state = AP_MPMQ_STARTING;
102 apr_thread_mutex_t *accept_mutex = NULL;
103
104 static apr_pool_t *pconf;    /* Pool for config stuff */
105 static apr_pool_t *pmain;    /* Pool for httpd child stuff */
106
107 static int server_pid;
108
109
110 /*
111  * The max child slot ever assigned, preserved across restarts.  Necessary
112  * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We use
113  * this value to optimize routines that have to scan the entire scoreboard.
114  */
115 int ap_max_child_assigned = -1;
116 int ap_max_threads_limit = -1;
117
118 static apr_socket_t *udp_sock;
119 static apr_sockaddr_t *udp_sa;
120
121 server_rec *ap_server_conf;
122
123 /* one_process */
124 static int one_process = 0;
125
126 #ifdef DEBUG_SIGSTOP
127 int raise_sigstop_flags;
128 #endif
129
130 static void check_restart(void *data);
131
132 /* When a worker thread gets to the end of it's life it dies with an
133  * exit value of the code supplied to this function. The thread has
134  * already had check_restart() registered to be called when dying, so
135  * we don't concern ourselves with restarting at all here. We do however
136  * mark the scoreboard slot as belonging to a dead server and zero out
137  * it's thread_id.
138  *
139  * TODO - use the status we set to determine if we need to restart the
140  *        thread.
141  */
142 static void clean_child_exit(int code, int slot)
143 {
144     (void) ap_update_child_status_from_indexes(0, slot, SERVER_DEAD,
145                                                (request_rec*)NULL);
146     ap_scoreboard_image->servers[0][slot].tid = 0;
147     exit_thread(code);
148 }
149
150 /* proper cleanup when returning from ap_mpm_run() */
151 static void mpm_main_cleanup(void)
152 {
153     if (pmain) {
154         apr_pool_destroy(pmain);
155     }
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     /* If the user tries to shut us down twice in quick succession then we
192      * may well get triggered while we are working through previous attempt
193      * to shutdown. We won't worry about even reporting it as it seems a little
194      * pointless.
195      */
196     if (shutdown_pending == 1)
197         return;
198
199     shutdown_pending = 1;
200 }
201
202 /* do a graceful restart if graceful == 1 */
203 static void ap_start_restart(int graceful)
204 {
205     if (restart_pending == 1) {
206         /* Probably not an error - don't bother reporting it */
207         return;
208     }
209     restart_pending = 1;
210     is_graceful = graceful;
211 }
212
213 /* sig_coredump attempts to handle all the potential signals we
214  * may get that should result in a core dump. This is called from
215  * the signal handler routine, so when we enter we are essentially blocked
216  * on the signal. Once we exit we will allow the signal to be processed by
217  * system, which may or may not produce a .core file. All this function does
218  * is try and respect the users wishes about where that file should be
219  * located (chdir) and then signal the parent with the signal.
220  *
221  * If we called abort() the parent would only see SIGABRT which doesn't provide
222  * as much information.
223  */
224 static void sig_coredump(int sig)
225 {
226     chdir(ap_coredump_dir);
227     signal(sig, SIG_DFL);
228     kill(server_pid, sig);
229 }
230
231 static void sig_term(int sig)
232 {
233     ap_start_shutdown();
234 }
235
236 static void restart(int sig)
237 {
238     ap_start_restart(sig == AP_SIG_GRACEFUL);
239 }
240
241 /* Handle queries about our inner workings... */
242 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
243 {
244     switch(query_code){
245         case AP_MPMQ_MAX_DAEMON_USED:
246             *result = ap_max_child_assigned;
247             return APR_SUCCESS;
248         case AP_MPMQ_IS_THREADED:
249             *result = AP_MPMQ_DYNAMIC;
250             return APR_SUCCESS;
251         case AP_MPMQ_IS_FORKED:
252             *result = AP_MPMQ_NOT_SUPPORTED;
253             return APR_SUCCESS;
254         case AP_MPMQ_HARD_LIMIT_DAEMONS:
255             *result = HARD_SERVER_LIMIT;
256             return APR_SUCCESS;
257         case AP_MPMQ_HARD_LIMIT_THREADS:
258             *result = HARD_THREAD_LIMIT;
259             return APR_SUCCESS;
260         case AP_MPMQ_MAX_THREADS:
261             *result = HARD_THREAD_LIMIT;
262             return APR_SUCCESS;
263         case AP_MPMQ_MIN_SPARE_DAEMONS:
264             *result = 0;
265             return APR_SUCCESS;
266         case AP_MPMQ_MIN_SPARE_THREADS:
267             *result = max_spare_threads;
268             return APR_SUCCESS;
269         case AP_MPMQ_MAX_SPARE_DAEMONS:
270             *result = 0;
271             return APR_SUCCESS;
272         case AP_MPMQ_MAX_SPARE_THREADS:
273             *result = min_spare_threads;
274             return APR_SUCCESS;
275         case AP_MPMQ_MAX_REQUESTS_DAEMON:
276             *result = ap_max_requests_per_thread;
277             return APR_SUCCESS;
278         case AP_MPMQ_MAX_DAEMONS:
279             *result = HARD_SERVER_LIMIT;
280             return APR_SUCCESS;
281         case AP_MPMQ_MPM_STATE:
282             *result = mpm_state;
283             return APR_SUCCESS;
284     }
285     return APR_ENOTIMPL;
286 }
287
288 /* This accepts a connection and allows us to handle the error codes better than
289  * the previous code, while also making it more obvious.
290  */
291 static apr_status_t beos_accept(void **accepted, ap_listen_rec *lr, apr_pool_t *ptrans)
292 {
293     apr_socket_t *csd;
294     apr_status_t status;
295     int sockdes;
296
297     *accepted = NULL;
298     status = apr_socket_accept(&csd, lr->sd, ptrans);
299     if (status == APR_SUCCESS) {
300         *accepted = csd;
301         apr_os_sock_get(&sockdes, csd);
302         return status;
303     }
304
305     if (APR_STATUS_IS_EINTR(status)) {
306         return status;
307     }
308         /* This switch statement provides us with better error details. */
309     switch (status) {
310 #ifdef ECONNABORTED
311         case ECONNABORTED:
312 #endif
313 #ifdef ETIMEDOUT
314         case ETIMEDOUT:
315 #endif
316 #ifdef EHOSTUNREACH
317         case EHOSTUNREACH:
318 #endif
319 #ifdef ENETUNREACH
320         case ENETUNREACH:
321 #endif
322             break;
323 #ifdef ENETDOWN
324         case ENETDOWN:
325             /*
326              * When the network layer has been shut down, there
327              * is not much use in simply exiting: the parent
328              * would simply re-create us (and we'd fail again).
329              * Use the CHILDFATAL code to tear the server down.
330              * @@@ Martin's idea for possible improvement:
331              * A different approach would be to define
332              * a new APEXIT_NETDOWN exit code, the reception
333              * of which would make the parent shutdown all
334              * children, then idle-loop until it detected that
335              * the network is up again, and restart the children.
336              * Ben Hyde noted that temporary ENETDOWN situations
337              * occur in mobile IP.
338              */
339             ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf,
340                          "apr_socket_accept: giving up.");
341             return APR_EGENERAL;
342 #endif /*ENETDOWN*/
343
344         default:
345             ap_log_error(APLOG_MARK, APLOG_ERR, status, ap_server_conf,
346                          "apr_socket_accept: (client socket)");
347             return APR_EGENERAL;
348     }
349     return status;
350 }
351
352 static void tell_workers_to_exit(void)
353 {
354     apr_size_t len;
355     int i = 0;
356     for (i = 0 ; i < ap_max_child_assigned; i++){
357         len = 4;
358         if (apr_socket_sendto(udp_sock, udp_sa, 0, "die!", &len) != APR_SUCCESS)
359             break;
360     }
361 }
362
363 static void set_signals(void)
364 {
365     struct sigaction sa;
366
367     sigemptyset(&sa.sa_mask);
368     sa.sa_flags = 0;
369
370     /* The first batch get handled by sig_coredump */
371     if (!one_process) {
372         sa.sa_handler = sig_coredump;
373
374         if (sigaction(SIGSEGV, &sa, NULL) < 0)
375             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
376         if (sigaction(SIGBUS, &sa, NULL) < 0)
377             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
378         if (sigaction(SIGABRT, &sa, NULL) < 0)
379             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
380         if (sigaction(SIGILL, &sa, NULL) < 0)
381             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
382         sa.sa_flags = 0;
383     }
384
385     /* These next two are handled by sig_term */
386     sa.sa_handler = sig_term;
387     if (sigaction(SIGTERM, &sa, NULL) < 0)
388             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
389     if (sigaction(SIGINT, &sa, NULL) < 0)
390         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
391
392     /* We ignore SIGPIPE */
393     sa.sa_handler = SIG_IGN;
394     if (sigaction(SIGPIPE, &sa, NULL) < 0)
395         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
396
397     /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
398      * processing one */
399     sigaddset(&sa.sa_mask, SIGHUP);
400     sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
401     sa.sa_handler = restart;
402     if (sigaction(SIGHUP, &sa, NULL) < 0)
403         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
404     if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
405             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
406 }
407
408 /*****************************************************************
409  * Here follows a long bunch of generic server bookkeeping stuff...
410  */
411
412 int ap_graceful_stop_signalled(void)
413 {
414     return is_graceful;
415 }
416
417 /* This is the thread that actually does all the work. */
418 static int32 worker_thread(void *dummy)
419 {
420     int worker_slot = (int)dummy;
421     apr_allocator_t *allocator;
422     apr_bucket_alloc_t *bucket_alloc;
423     apr_status_t rv = APR_EINIT;
424     int last_poll_idx = 0;
425     sigset_t sig_mask;
426     int requests_this_child = 0;
427     apr_pollset_t *pollset = NULL;
428     ap_listen_rec *lr = NULL;
429     ap_sb_handle_t *sbh = NULL;
430     int i;
431     /* each worker thread is in control of its own destiny...*/
432     int this_worker_should_exit = 0;
433     /* We have 2 pools that we create/use throughout the lifetime of this
434      * worker. The first and longest lived is the pworker pool. From
435      * this we create the ptrans pool, the lifetime of which is the same
436      * as each connection and is reset prior to each attempt to
437      * process a connection.
438      */
439     apr_pool_t *ptrans = NULL;
440     apr_pool_t *pworker = NULL;
441
442     mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
443                                   * child initializes
444                                   */
445
446     on_exit_thread(check_restart, (void*)worker_slot);
447
448     /* block the signals for this thread only if we're not running as a
449      * single process.
450      */
451     if (!one_process) {
452         sigfillset(&sig_mask);
453         sigprocmask(SIG_BLOCK, &sig_mask, NULL);
454     }
455
456     /* Each worker thread is fully in control of it's destinay and so
457      * to allow each thread to handle the lifetime of it's own resources
458      * we create and use a subcontext for every thread.
459      * The subcontext is a child of the pconf pool.
460      */
461     apr_allocator_create(&allocator);
462     apr_allocator_max_free_set(allocator, ap_max_mem_free);
463     apr_pool_create_ex(&pworker, pconf, NULL, allocator);
464     apr_allocator_owner_set(allocator, pworker);
465
466     apr_pool_create(&ptrans, pworker);
467     apr_pool_tag(ptrans, "transaction");
468
469     ap_create_sb_handle(&sbh, pworker, 0, worker_slot);
470     (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
471
472     /* We add an extra socket here as we add the udp_sock we use for signalling
473      * death. This gets added after the others.
474      */
475     apr_pollset_create(&pollset, num_listening_sockets + 1, pworker, 0);
476
477     for (lr = ap_listeners, i = num_listening_sockets; i--; lr = lr->next) {
478         apr_pollfd_t pfd = {0};
479
480         pfd.desc_type = APR_POLL_SOCKET;
481         pfd.desc.s = lr->sd;
482         pfd.reqevents = APR_POLLIN;
483         pfd.client_data = lr;
484
485         apr_pollset_add(pollset, &pfd);
486     }
487     {
488         apr_pollfd_t pfd = {0};
489
490         pfd.desc_type = APR_POLL_SOCKET;
491         pfd.desc.s = udp_sock;
492         pfd.reqevents = APR_POLLIN;
493
494         apr_pollset_add(pollset, &pfd);
495     }
496
497     bucket_alloc = apr_bucket_alloc_create(pworker);
498
499     mpm_state = AP_MPMQ_RUNNING;
500
501         while (!this_worker_should_exit) {
502         conn_rec *current_conn;
503         void *csd;
504
505         /* (Re)initialize this child to a pre-connection state. */
506         apr_pool_clear(ptrans);
507
508         if ((ap_max_requests_per_thread > 0
509              && requests_this_child++ >= ap_max_requests_per_thread))
510             clean_child_exit(0, worker_slot);
511
512         (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
513
514         apr_thread_mutex_lock(accept_mutex);
515
516         /* We always (presently) have at least 2 sockets we listen on, so
517          * we don't have the ability for a fast path for a single socket
518          * as some MPM's allow :(
519          */
520         for (;;) {
521             apr_int32_t numdesc = 0;
522             const apr_pollfd_t *pdesc = NULL;
523
524             rv = apr_pollset_poll(pollset, -1, &numdesc, &pdesc);
525             if (rv != APR_SUCCESS) {
526                 if (APR_STATUS_IS_EINTR(rv)) {
527                     if (one_process && shutdown_pending)
528                         return;
529                     continue;
530                 }
531                 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
532                              ap_server_conf, "apr_pollset_poll: (listen)");
533                 clean_child_exit(1, worker_slot);
534             }
535             /* We can always use pdesc[0], but sockets at position N
536              * could end up completely starved of attention in a very
537              * busy server. Therefore, we round-robin across the
538              * returned set of descriptors. While it is possible that
539              * the returned set of descriptors might flip around and
540              * continue to starve some sockets, we happen to know the
541              * internal pollset implementation retains ordering
542              * stability of the sockets. Thus, the round-robin should
543              * ensure that a socket will eventually be serviced.
544              */
545             if (last_poll_idx >= numdesc)
546                 last_poll_idx = 0;
547
548             /* Grab a listener record from the client_data of the poll
549              * descriptor, and advance our saved index to round-robin
550              * the next fetch.
551              *
552              * ### hmm... this descriptor might have POLLERR rather
553              * ### than POLLIN
554              */
555
556             lr = pdesc[last_poll_idx++].client_data;
557
558             /* The only socket we add without client_data is the first, the UDP socket
559              * we listen on for restart signals. If we've therefore gotten a hit on that
560              * listener lr will be NULL here and we know we've been told to die.
561              * Before we jump to the end of the while loop with this_worker_should_exit
562              * set to 1 (causing us to exit normally we hope) we release the accept_mutex
563              * as we want every thread to go through this same routine :)
564              * Bit of a hack, but compared to what I had before...
565              */
566             if (lr == NULL) {
567                 this_worker_should_exit = 1;
568                 apr_thread_mutex_unlock(accept_mutex);
569                 goto got_a_black_spot;
570             }
571             goto got_fd;
572         }
573 got_fd:
574         /* Run beos_accept to accept the connection and set things up to
575          * allow us to process it. We always release the accept_lock here,
576          * even if we failt o accept as otherwise we'll starve other workers
577          * which would be bad.
578          */
579         rv = beos_accept(&csd, lr, ptrans);
580         apr_thread_mutex_unlock(accept_mutex);
581
582         if (rv == APR_EGENERAL) {
583             /* resource shortage or should-not-occur occured */
584             clean_child_exit(1, worker_slot);
585         } else if (rv != APR_SUCCESS)
586             continue;
587
588         current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, worker_slot, sbh, bucket_alloc);
589         if (current_conn) {
590             ap_process_connection(current_conn, csd);
591             ap_lingering_close(current_conn);
592         }
593
594         if (ap_my_generation !=
595                  ap_scoreboard_image->global->running_generation) { /* restart? */
596             /* yeah, this could be non-graceful restart, in which case the
597              * parent will kill us soon enough, but why bother checking?
598              */
599             this_worker_should_exit = 1;
600         }
601 got_a_black_spot:
602     }
603
604     apr_pool_destroy(ptrans);
605     apr_pool_destroy(pworker);
606
607     clean_child_exit(0, worker_slot);
608 }
609
610 static int make_worker(int slot)
611 {
612     thread_id tid;
613
614     if (slot + 1 > ap_max_child_assigned)
615             ap_max_child_assigned = slot + 1;
616
617     (void) ap_update_child_status_from_indexes(0, slot, SERVER_STARTING, (request_rec*)NULL);
618
619     if (one_process) {
620         set_signals();
621         ap_scoreboard_image->parent[0].pid = getpid();
622         ap_scoreboard_image->servers[0][slot].tid = find_thread(NULL);
623         return 0;
624     }
625
626     tid = spawn_thread(worker_thread, "apache_worker", B_NORMAL_PRIORITY,
627                        (void *)slot);
628     if (tid < B_NO_ERROR) {
629         ap_log_error(APLOG_MARK, APLOG_ERR, errno, NULL,
630             "spawn_thread: Unable to start a new thread");
631         /* In case system resources are maxed out, we don't want
632          * Apache running away with the CPU trying to fork over and
633          * over and over again.
634          */
635         (void) ap_update_child_status_from_indexes(0, slot, SERVER_DEAD,
636                                                    (request_rec*)NULL);
637
638         sleep(10);
639         return -1;
640     }
641     resume_thread(tid);
642
643     ap_scoreboard_image->servers[0][slot].tid = tid;
644     return 0;
645 }
646
647 /* When a worker thread exits, this function is called. If we are not in
648  * a shutdown situation then we restart the worker in the slot that was
649  * just vacated.
650  */
651 static void check_restart(void *data)
652 {
653     if (!restart_pending && !shutdown_pending) {
654         int slot = (int)data;
655         make_worker(slot);
656         ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL,
657                      "spawning a new worker thread in slot %d", slot);
658     }
659 }
660
661 /* Start number_to_start children. This is used to start both the
662  * initial 'pool' of workers but also to replace existing workers who
663  * have reached the end of their time. It walks through the scoreboard to find
664  * an empty slot and starts the worker thread in that slot.
665  */
666 static void startup_threads(int number_to_start)
667 {
668     int i;
669
670     for (i = 0; number_to_start && i < ap_thread_limit; ++i) {
671         if (ap_scoreboard_image->servers[0][i].tid)
672             continue;
673
674         if (make_worker(i) < 0)
675                 break;
676
677         --number_to_start;
678     }
679 }
680
681
682 /*
683  * spawn_rate is the number of children that will be spawned on the
684  * next maintenance cycle if there aren't enough idle servers.  It is
685  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
686  * without the need to spawn.
687  */
688 static int spawn_rate = 1;
689 #ifndef MAX_SPAWN_RATE
690 #define MAX_SPAWN_RATE  (32)
691 #endif
692 static int hold_off_on_exponential_spawning;
693
694 static void perform_idle_server_maintenance(void)
695 {
696     int i;
697     int free_length;
698     int free_slots[MAX_SPAWN_RATE];
699     int last_non_dead  = -1;
700
701     /* initialize the free_list */
702     free_length = 0;
703
704     for (i = 0; i < ap_thread_limit; ++i) {
705         if (ap_scoreboard_image->servers[0][i].tid == 0) {
706             if (free_length < spawn_rate) {
707                 free_slots[free_length] = i;
708                 ++free_length;
709             }
710         }
711         else {
712             last_non_dead = i;
713         }
714
715         if (i >= ap_max_child_assigned && free_length >= spawn_rate) {
716                  break;
717         }
718     }
719     ap_max_child_assigned = last_non_dead + 1;
720
721     if (free_length > 0) {
722         for (i = 0; i < free_length; ++i) {
723                 make_worker(free_slots[i]);
724         }
725         /* the next time around we want to spawn twice as many if this
726          * wasn't good enough, but not if we've just done a graceful
727          */
728         if (hold_off_on_exponential_spawning) {
729             --hold_off_on_exponential_spawning;
730         } else if (spawn_rate < MAX_SPAWN_RATE) {
731             spawn_rate *= 2;
732         }
733     } else {
734         spawn_rate = 1;
735     }
736 }
737
738 static void server_main_loop(int remaining_threads_to_start)
739 {
740     int child_slot;
741     apr_exit_why_e exitwhy;
742     int status;
743     apr_proc_t pid;
744     int i;
745
746     while (!restart_pending && !shutdown_pending) {
747
748         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
749
750         if (pid.pid >= 0) {
751             if (ap_process_child_status(&pid, exitwhy, status) == APEXIT_CHILDFATAL) {
752                 shutdown_pending = 1;
753                 child_fatal = 1;
754                 return;
755             }
756             /* non-fatal death... note that it's gone in the scoreboard. */
757             child_slot = -1;
758             for (i = 0; i < ap_max_child_assigned; ++i) {
759                 if (ap_scoreboard_image->servers[0][i].tid == pid.pid) {
760                     child_slot = i;
761                     break;
762                 }
763             }
764             if (child_slot >= 0) {
765                 ap_scoreboard_image->servers[0][child_slot].tid = 0;
766                 (void) ap_update_child_status_from_indexes(0, child_slot,
767                                                            SERVER_DEAD,
768                                                            (request_rec*)NULL);
769
770                 if (remaining_threads_to_start
771                             && child_slot < ap_thread_limit) {
772                     /* we're still doing a 1-for-1 replacement of dead
773                      * children with new children
774                      */
775                     make_worker(child_slot);
776                     --remaining_threads_to_start;
777                         }
778 /* TODO
779 #if APR_HAS_OTHER_CHILD
780             }
781             else if (apr_proc_other_child_refresh(&pid, status) == 0) {
782 #endif
783 */
784             }
785             else if (is_graceful) {
786                 /* Great, we've probably just lost a slot in the
787                  * scoreboard.  Somehow we don't know about this
788                  * child.
789                  */
790                  ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf,
791                                           "long lost child came home! (pid %ld)", pid.pid);
792             }
793
794             /* Don't perform idle maintenance when a child dies,
795              * only do it when there's a timeout.  Remember only a
796              * finite number of children can die, and it's pretty
797              * pathological for a lot to die suddenly.
798              */
799              continue;
800          }
801              else if (remaining_threads_to_start) {
802              /* we hit a 1 second timeout in which none of the previous
803               * generation of children needed to be reaped... so assume
804               * they're all done, and pick up the slack if any is left.
805               */
806               startup_threads(remaining_threads_to_start);
807               remaining_threads_to_start = 0;
808               /* In any event we really shouldn't do the code below because
809                * few of the servers we just started are in the IDLE state
810                * yet, so we'd mistakenly create an extra server.
811                */
812               continue;
813          }
814          perform_idle_server_maintenance();
815     }
816 }
817
818 /* This is called to not only setup and run for the initial time, but also
819  * when we've asked for a restart. This means it must be able to handle both
820  * situations. It also means that when we exit here we should have tidied
821  * up after ourselves fully.
822  */
823 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
824 {
825     int remaining_threads_to_start, i,j;
826     apr_status_t rv;
827     ap_listen_rec *lr;
828     pconf = _pconf;
829     ap_server_conf = s;
830
831     /* Increase the available pool of fd's.  This code from
832      * Joe Kloss <joek@be.com>
833      */
834     if( FD_SETSIZE > 128 && (i = _kset_fd_limit_( 128 )) < 0 ){
835         ap_log_error(APLOG_MARK, APLOG_ERR, i, s,
836             "could not set FD_SETSIZE (_kset_fd_limit_ failed)");
837     }
838
839     /* BeOS R5 doesn't support pipes on select() calls, so we use a
840      * UDP socket as these are supported in both R5 and BONE.  If we only cared
841      * about BONE we'd use a pipe, but there it is.
842      * As we have UDP support in APR, now use the APR functions and check all the
843      * return values...
844      */
845     if (apr_sockaddr_info_get(&udp_sa, "127.0.0.1", APR_UNSPEC, 7772, 0, _pconf)
846         != APR_SUCCESS){
847         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
848             "couldn't create control socket information, shutting down");
849         return 1;
850     }
851     if (apr_socket_create(&udp_sock, udp_sa->family, SOCK_DGRAM, 0,
852                       _pconf) != APR_SUCCESS){
853         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
854             "couldn't create control socket, shutting down");
855         return 1;
856     }
857     if (apr_socket_bind(udp_sock, udp_sa) != APR_SUCCESS){
858         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
859             "couldn't bind UDP socket!");
860         return 1;
861     }
862
863     if ((num_listening_sockets = ap_setup_listeners(ap_server_conf)) < 1) {
864         ap_log_error(APLOG_MARK, APLOG_ALERT, 0, s,
865             "no listening sockets available, shutting down");
866         return 1;
867     }
868
869     ap_log_pid(pconf, ap_pid_fname);
870
871     /*
872      * Create our locks...
873      */
874
875     /* accept_mutex
876      * used to lock around select so we only have one thread
877      * in select at a time
878      */
879     rv = apr_thread_mutex_create(&accept_mutex, 0, pconf);
880     if (rv != APR_SUCCESS) {
881         /* tsch tsch, can't have more than one thread in the accept loop
882            at a time so we need to fall on our sword... */
883         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
884                      "Couldn't create accept lock");
885         return 1;
886     }
887
888     /*
889      * Startup/shutdown...
890      */
891
892     if (!is_graceful) {
893         /* setup the scoreboard shared memory */
894         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
895             return 1;
896         }
897
898         for (i = 0; i < HARD_SERVER_LIMIT; i++) {
899             ap_scoreboard_image->parent[i].pid = 0;
900             for (j = 0;j < HARD_THREAD_LIMIT; j++)
901                 ap_scoreboard_image->servers[i][j].tid = 0;
902         }
903     }
904
905     if (HARD_SERVER_LIMIT == 1)
906         ap_scoreboard_image->parent[0].pid = getpid();
907
908     set_signals();
909
910     apr_pool_create(&pmain, pconf);
911     ap_run_child_init(pmain, ap_server_conf);
912
913     /* Sanity checks to avoid thrashing... */
914     if (max_spare_threads < min_spare_threads )
915         max_spare_threads = min_spare_threads;
916
917     /* If we're doing a graceful_restart then we're going to see a lot
918      * of threads exiting immediately when we get into the main loop
919      * below (because we just sent them AP_SIG_GRACEFUL).  This happens
920      * pretty rapidly... and for each one that exits we'll start a new one
921      * until we reach at least threads_min_free.  But we may be permitted to
922      * start more than that, so we'll just keep track of how many we're
923      * supposed to start up without the 1 second penalty between each fork.
924      */
925     remaining_threads_to_start = ap_threads_to_start;
926     /* sanity check on the number to start... */
927     if (remaining_threads_to_start > ap_thread_limit) {
928             remaining_threads_to_start = ap_thread_limit;
929     }
930
931     /* If we're doing the single process thing or we're in a graceful_restart
932      * then we don't start threads here.
933      * if we're in one_process mode we don't want to start threads
934      * do we??
935      */
936     if (!is_graceful && !one_process) {
937             startup_threads(remaining_threads_to_start);
938             remaining_threads_to_start = 0;
939     } else {
940             /* give the system some time to recover before kicking into
941              * exponential mode */
942         hold_off_on_exponential_spawning = 10;
943     }
944
945     /*
946      * record that we've entered the world !
947      */
948     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
949                 "%s configured -- resuming normal operations",
950                 ap_get_server_description());
951
952     ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
953                 "Server built: %s", ap_get_server_built());
954
955     restart_pending = shutdown_pending = 0;
956
957     mpm_state = AP_MPMQ_RUNNING;
958
959     /* We sit in the server_main_loop() until we somehow manage to exit. When
960      * we do, we need to kill the workers we have, so we start by using the
961      * tell_workers_to_exit() function, but as it sometimes takes a short while
962      * to accomplish this we have a pause builtin to allow them the chance to
963      * gracefully exit.
964      */
965     if (!one_process) {
966         server_main_loop(remaining_threads_to_start);
967         tell_workers_to_exit();
968         snooze(1000000);
969     } else {
970         worker_thread((void*)0);
971     }
972     mpm_state = AP_MPMQ_STOPPING;
973
974     /* close the UDP socket we've been using... */
975     apr_socket_close(udp_sock);
976
977     if ((one_process || shutdown_pending) && !child_fatal) {
978         const char *pidfile = NULL;
979         pidfile = ap_server_root_relative (pconf, ap_pid_fname);
980         if ( pidfile != NULL && unlink(pidfile) == 0)
981             ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
982                          "removed PID file %s (pid=%ld)", pidfile,
983                          (long)getpid());
984     }
985
986     if (one_process) {
987         mpm_main_cleanup();
988         return 1;
989     }
990
991     /*
992      * If we get here we're shutting down...
993      */
994     if (shutdown_pending) {
995         /* Time to gracefully shut down:
996          * Kill child processes, tell them to call child_exit, etc...
997          */
998         if (beosd_killpg(getpgrp(), SIGTERM) < 0)
999             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
1000              "killpg SIGTERM");
1001
1002         /* use ap_reclaim_child_processes starting with SIGTERM */
1003         ap_reclaim_child_processes(1);
1004
1005         if (!child_fatal) {         /* already recorded */
1006             /* record the shutdown in the log */
1007             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1008                          "caught SIGTERM, shutting down");
1009         }
1010
1011         mpm_main_cleanup();
1012         return 1;
1013     }
1014
1015     /* we've been told to restart */
1016     signal(SIGHUP, SIG_IGN);
1017
1018     if (is_graceful) {
1019         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1020                     AP_SIG_GRACEFUL_STRING " received.  Doing graceful restart");
1021     } else {
1022         /* Kill 'em all.  Since the child acts the same on the parents SIGTERM
1023          * and a SIGHUP, we may as well use the same signal, because some user
1024          * pthreads are stealing signals from us left and right.
1025          */
1026
1027         ap_reclaim_child_processes(1);   /* Start with SIGTERM */
1028             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1029                     "SIGHUP received.  Attempting to restart");
1030     }
1031
1032     /* just before we go, tidy up the lock we created to prevent a
1033      * potential leak of semaphores...
1034      */
1035     apr_thread_mutex_destroy(accept_mutex);
1036
1037     mpm_main_cleanup();
1038     return 0;
1039 }
1040
1041 static int beos_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
1042 {
1043     static int restart_num = 0;
1044     int no_detach, debug, foreground;
1045     apr_status_t rv;
1046
1047     mpm_state = AP_MPMQ_STARTING;
1048
1049     debug = ap_exists_config_define("DEBUG");
1050
1051     if (debug) {
1052         foreground = one_process = 1;
1053         no_detach = 0;
1054     }
1055     else
1056     {
1057         one_process = ap_exists_config_define("ONE_PROCESS");
1058         no_detach = ap_exists_config_define("NO_DETACH");
1059         foreground = ap_exists_config_define("FOREGROUND");
1060     }
1061
1062     /* sigh, want this only the second time around */
1063     if (restart_num++ == 1) {
1064         is_graceful = 0;
1065
1066         if (!one_process && !foreground) {
1067             rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1068                                            : APR_PROC_DETACH_DAEMONIZE);
1069             if (rv != APR_SUCCESS) {
1070                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1071                              "apr_proc_detach failed");
1072                 return HTTP_INTERNAL_SERVER_ERROR;
1073             }
1074         }
1075
1076         server_pid = getpid();
1077     }
1078
1079     beosd_pre_config();
1080     ap_listen_pre_config();
1081     ap_threads_to_start = DEFAULT_START_THREADS;
1082     min_spare_threads = DEFAULT_MIN_FREE_THREADS;
1083     max_spare_threads = DEFAULT_MAX_FREE_THREADS;
1084     ap_thread_limit = HARD_THREAD_LIMIT;
1085     ap_pid_fname = DEFAULT_PIDLOG;
1086     ap_max_requests_per_thread = DEFAULT_MAX_REQUESTS_PER_THREAD;
1087 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
1088         ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
1089 #endif
1090
1091     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1092
1093     return OK;
1094 }
1095
1096 static int beos_check_config(apr_pool_t *pconf, apr_pool_t *plog,
1097                              apr_pool_t *ptemp, server_rec *s)
1098 {
1099     static int restart_num = 0;
1100     int startup = 0;
1101
1102     /* the reverse of pre_config, we want this only the first time around */
1103     if (restart_num++ == 0) {
1104         startup = 1;
1105     }
1106
1107     if (ap_thread_limit > HARD_THREAD_LIMIT) {
1108         if (startup) {
1109             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1110                          "WARNING: MaxClients of %d exceeds compile-time "
1111                          "limit of", ap_thread_limit);
1112             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1113                          " %d servers, decreasing to %d.",
1114                          HARD_THREAD_LIMIT, HARD_THREAD_LIMIT);
1115             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1116                          " To increase, please see the HARD_THREAD_LIMIT"
1117                          "define in");
1118             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1119                          " server/mpm/beos%s.", AP_MPM_HARD_LIMITS_FILE);
1120         } else {
1121             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1122                          "MaxClients of %d exceeds compile-time limit "
1123                          "of %d, decreasing to match",
1124                          ap_thread_limit, HARD_THREAD_LIMIT);
1125         }
1126         ap_thread_limit = HARD_THREAD_LIMIT;
1127     }
1128     else if (ap_thread_limit < 1) {
1129         if (startup) {
1130             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1131                          "WARNING: MaxClients of %d not allowed, "
1132                          "increasing to 1.", ap_thread_limit);
1133         } else {
1134             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1135                          "MaxClients of %d not allowed, increasing to 1",
1136                          ap_thread_limit);
1137         }
1138         ap_thread_limit = 1;
1139     }
1140
1141     /* ap_threads_to_start > ap_thread_limit checked in ap_mpm_run() */
1142     if (ap_threads_to_start < 0) {
1143         if (startup) {
1144             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1145                          "WARNING: StartThreads of %d not allowed, "
1146                          "increasing to 1.", ap_threads_to_start);
1147         } else {
1148             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1149                          "StartThreads of %d not allowed, increasing to 1",
1150                          ap_threads_to_start);
1151         }
1152         ap_threads_to_start = 1;
1153     }
1154
1155     if (min_spare_threads < 1) {
1156         if (startup) {
1157             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1158                          "WARNING: MinSpareThreads of %d not allowed, "
1159                          "increasing to 1", min_spare_threads);
1160             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1161                          " to avoid almost certain server failure.");
1162             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1163                          " Please read the documentation.");
1164         } else {
1165             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1166                          "MinSpareThreads of %d not allowed, increasing to 1",
1167                          min_spare_threads);
1168         }
1169         min_spare_threads = 1;
1170     }
1171
1172     /* max_spare_threads < min_spare_threads checked in ap_mpm_run() */
1173
1174     if (ap_max_requests_per_thread < 0) {
1175         if (startup) {
1176             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1177                          "WARNING: MaxRequestsPerThread of %d not allowed, "
1178                          "increasing to 0,", ap_max_requests_per_thread);
1179             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1180                          " but this may not be what you want.");
1181         } else {
1182             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1183                          "MaxRequestsPerThread of %d not allowed, "
1184                          "increasing to 0", ap_max_requests_per_thread);
1185         }
1186         ap_max_requests_per_thread = 0;
1187     }
1188
1189     return OK;
1190 }
1191
1192 static void beos_hooks(apr_pool_t *p)
1193 {
1194     one_process = 0;
1195
1196     ap_hook_pre_config(beos_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1197     ap_hook_check_config(beos_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1198 }
1199
1200 static const char *set_threads_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1201 {
1202     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1203     if (err != NULL) {
1204         return err;
1205     }
1206
1207     ap_threads_to_start = atoi(arg);
1208     return NULL;
1209 }
1210
1211 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1212 {
1213     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1214     if (err != NULL) {
1215         return err;
1216     }
1217
1218     min_spare_threads = atoi(arg);
1219     return NULL;
1220 }
1221
1222 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1223 {
1224     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1225     if (err != NULL) {
1226         return err;
1227     }
1228
1229     max_spare_threads = atoi(arg);
1230     return NULL;
1231 }
1232
1233 static const char *set_threads_limit (cmd_parms *cmd, void *dummy, const char *arg)
1234 {
1235     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1236     if (err != NULL) {
1237         return err;
1238     }
1239
1240     ap_thread_limit = atoi(arg);
1241     return NULL;
1242 }
1243
1244 static const char *set_max_requests_per_thread (cmd_parms *cmd, void *dummy, const char *arg)
1245 {
1246     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1247     if (err != NULL) {
1248         return err;
1249     }
1250
1251     ap_max_requests_per_thread = atoi(arg);
1252     return NULL;
1253 }
1254
1255 static const command_rec beos_cmds[] = {
1256 BEOS_DAEMON_COMMANDS,
1257 LISTEN_COMMANDS,
1258 AP_INIT_TAKE1( "StartThreads", set_threads_to_start, NULL, RSRC_CONF,
1259   "Number of threads to launch at server startup"),
1260 AP_INIT_TAKE1( "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1261   "Minimum number of idle children, to handle request spikes"),
1262 AP_INIT_TAKE1( "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1263   "Maximum number of idle children" ),
1264 AP_INIT_TAKE1( "MaxClients", set_threads_limit, NULL, RSRC_CONF,
1265   "Maximum number of children alive at the same time (max threads)" ),
1266 AP_INIT_TAKE1( "MaxRequestsPerThread", set_max_requests_per_thread, NULL, RSRC_CONF,
1267   "Maximum number of requests served by a thread" ),
1268 { NULL }
1269 };
1270
1271 module AP_MODULE_DECLARE_DATA mpm_beos_module = {
1272     MPM20_MODULE_STUFF,
1273     NULL,          /* hook to run before apache parses args */
1274     NULL,          /* create per-directory config structure */
1275     NULL,          /* merge per-directory config structures */
1276     NULL,          /* create per-server config structure */
1277     NULL,          /* merge per-server config structures */
1278     beos_cmds,     /* command apr_table_t */
1279     beos_hooks     /* register_hooks */
1280 };
1281