Main Page | Modules | Namespace List | Alphabetical List | Data Structures | Directories | File List | Data Fields | Globals | Related Pages | Examples

beos.c

Go to the documentation of this file.
00001 /* Copyright 2000-2005 The Apache Software Foundation or its licensors, as
00002  * applicable.
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 /* The new BeOS MPM!
00018  *
00019  * This one basically is a single process multi threaded model, but 
00020  * I couldn't be bothered adding the spmt_ to the front of the name!
00021  * Anyway, this is still under development so it isn't yet the default
00022  * choice.
00023  */
00024  
00025 #define CORE_PRIVATE 
00026  
00027 #include <kernel/OS.h>
00028 #include <unistd.h>
00029 #include <sys/socket.h>
00030 #include <signal.h>
00031 
00032 #include "apr_strings.h"
00033 #include "apr_portable.h"
00034 #include "httpd.h" 
00035 #include "http_main.h" 
00036 #include "http_log.h" 
00037 #include "http_config.h"        /* for read_config */ 
00038 #include "http_core.h"          /* for get_remote_host */ 
00039 #include "http_connection.h"
00040 #include "ap_mpm.h"
00041 #include "beosd.h"
00042 #include "ap_listen.h"
00043 #include "scoreboard.h" 
00044 #include "mpm_common.h"
00045 #include "mpm.h"
00046 #include "mpm_default.h"
00047 #include "apr_thread_mutex.h"
00048 #include "apr_poll.h"
00049 
00050 extern int _kset_fd_limit_(int num);
00051 
00052 /* Limit on the total --- clients will be locked out if more servers than
00053  * this are needed.  It is intended solely to keep the server from crashing
00054  * when things get out of hand.
00055  *
00056  * We keep a hard maximum number of servers, for two reasons:
00057  * 1) in case something goes seriously wrong, we want to stop the server starting
00058  *    threads ad infinitum and crashing the server (remember that BeOS has a 192
00059  *    thread per team limit).
00060  * 2) it keeps the size of the scoreboard file small
00061  *    enough that we can read the whole thing without worrying too much about
00062  *    the overhead.
00063  */
00064 
00065 /* we only ever have 1 main process running... */ 
00066 #define HARD_SERVER_LIMIT 1
00067 
00068 /* Limit on the threads per process.  Clients will be locked out if more than
00069  * this  * HARD_SERVER_LIMIT are needed.
00070  *
00071  * We keep this for one reason it keeps the size of the scoreboard file small
00072  * enough that we can read the whole thing without worrying too much about
00073  * the overhead.
00074  */
00075 #ifdef NO_THREADS
00076 #define HARD_THREAD_LIMIT 1
00077 #endif
00078 #ifndef HARD_THREAD_LIMIT
00079 #define HARD_THREAD_LIMIT 50 
00080 #endif
00081 
00082 /*
00083  * Actual definitions of config globals
00084  */
00085 
00086 static int ap_threads_to_start=0;
00087 static int ap_max_requests_per_thread = 0;
00088 static int min_spare_threads=0;
00089 static int max_spare_threads=0;
00090 static int ap_thread_limit=0;
00091 static int num_listening_sockets = 0;
00092 static apr_socket_t ** listening_sockets;
00093 apr_thread_mutex_t *accept_mutex = NULL;
00094 
00095 static apr_pool_t *pconf;               /* Pool for config stuff */
00096 static apr_pool_t *pchild;              /* Pool for httpd child stuff */
00097 
00098 static int server_pid; 
00099 static int mpm_state = AP_MPMQ_STARTING;
00100 
00101 /* Keep track of the number of worker threads currently active */
00102 static int worker_thread_count;
00103 apr_thread_mutex_t *worker_thread_count_mutex;
00104 
00105 /* The structure used to pass unique initialization info to each thread */
00106 typedef struct {
00107     int slot;
00108     apr_pool_t *tpool;
00109 } proc_info;
00110 
00111 static void check_restart(void *data);
00112 
00113 /*
00114  * The max child slot ever assigned, preserved across restarts.  Necessary
00115  * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts.  We use 
00116  * this value to optimize routines that have to scan the entire scoreboard.
00117  */
00118 int ap_max_child_assigned = -1;
00119 int ap_max_threads_limit = -1;
00120 
00121 static apr_socket_t *udp_sock;
00122 static apr_sockaddr_t *udp_sa;
00123 
00124 /* shared http_main globals... */
00125 
00126 server_rec *ap_server_conf;
00127 
00128 /* one_process */
00129 static int one_process = 0;
00130 
00131 #ifdef DEBUG_SIGSTOP
00132 int raise_sigstop_flags;
00133 #endif
00134 
00135 /* a clean exit from a child with proper cleanup 
00136    static void clean_child_exit(int code) __attribute__ ((noreturn)); */
00137 static void clean_child_exit(int code)
00138 {
00139     if (pchild)
00140         apr_pool_destroy(pchild);
00141     exit(code);
00142 }
00143 
00144 /* handle all varieties of core dumping signals */
00145 static void sig_coredump(int sig)
00146 {
00147     chdir(ap_coredump_dir);
00148     signal(sig, SIG_DFL);
00149     kill(server_pid, sig);
00150     /* At this point we've got sig blocked, because we're still inside
00151      * the signal handler.  When we leave the signal handler it will
00152      * be unblocked, and we'll take the signal... and coredump or whatever
00153      * is appropriate for this particular Unix.  In addition the parent
00154      * will see the real signal we received -- whereas if we called
00155      * abort() here, the parent would only see SIGABRT.
00156      */
00157 }
00158 
00159 /*****************************************************************
00160  * Connection structures and accounting...
00161  */
00162 
00163 /* volatile just in case */
00164 static int volatile shutdown_pending;
00165 static int volatile restart_pending;
00166 static int volatile is_graceful;
00167 static int volatile child_fatal;
00168 ap_generation_t volatile ap_my_generation = 0;
00169 
00170 /*
00171  * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
00172  * functions to initiate shutdown or restart without relying on signals. 
00173  * Previously this was initiated in sig_term() and restart() signal handlers, 
00174  * but we want to be able to start a shutdown/restart from other sources --
00175  * e.g. on Win32, from the service manager. Now the service manager can
00176  * call ap_start_shutdown() or ap_start_restart() as appropiate.  Note that
00177  * these functions can also be called by the child processes, since global
00178  * variables are no longer used to pass on the required action to the parent.
00179  *
00180  * These should only be called from the parent process itself, since the
00181  * parent process will use the shutdown_pending and restart_pending variables
00182  * to determine whether to shutdown or restart. The child process should
00183  * call signal_parent() directly to tell the parent to die -- this will
00184  * cause neither of those variable to be set, which the parent will
00185  * assume means something serious is wrong (which it will be, for the
00186  * child to force an exit) and so do an exit anyway.
00187  */
00188 
00189 static void ap_start_shutdown(void)
00190 {
00191     mpm_state = AP_MPMQ_STOPPING;
00192  
00193     if (shutdown_pending == 1) {
00194         /* Um, is this _probably_ not an error, if the user has
00195          * tried to do a shutdown twice quickly, so we won't
00196          * worry about reporting it.
00197          */
00198         return;
00199     }
00200     shutdown_pending = 1;
00201 }
00202 
00203 /* do a graceful restart if graceful == 1 */
00204 static void ap_start_restart(int graceful)
00205 {
00206     mpm_state = AP_MPMQ_STOPPING;
00207 
00208     if (restart_pending == 1) {
00209         /* Probably not an error - don't bother reporting it */
00210         return;
00211     }
00212     restart_pending = 1;
00213     is_graceful = graceful;
00214 }
00215 
00216 static void sig_term(int sig)
00217 {
00218     ap_start_shutdown();
00219 }
00220 
00221 static void restart(int sig)
00222 {
00223     ap_start_restart(sig == AP_SIG_GRACEFUL);
00224 }
00225 
00226 static void tell_workers_to_exit(void)
00227 {
00228     apr_size_t len;
00229     int i = 0;
00230 
00231     mpm_state = AP_MPMQ_STOPPING;
00232 
00233     for (i = 0 ; i < ap_max_child_assigned; i++){
00234         len = 4;
00235         if (apr_sendto(udp_sock, udp_sa, 0, "die!", &len) != APR_SUCCESS)
00236             break;
00237     }   
00238 }
00239 
00240 static void set_signals(void)
00241 {
00242     struct sigaction sa;
00243 
00244     sigemptyset(&sa.sa_mask);
00245     sa.sa_flags = 0;
00246 
00247     if (!one_process) {
00248         sa.sa_handler = sig_coredump;
00249 
00250         if (sigaction(SIGSEGV, &sa, NULL) < 0)
00251             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
00252         if (sigaction(SIGBUS, &sa, NULL) < 0)
00253             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
00254         if (sigaction(SIGABRT, &sa, NULL) < 0)
00255             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
00256         if (sigaction(SIGILL, &sa, NULL) < 0)
00257             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
00258         sa.sa_flags = 0;
00259     }
00260     sa.sa_handler = sig_term;
00261     if (sigaction(SIGTERM, &sa, NULL) < 0)
00262             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
00263     if (sigaction(SIGINT, &sa, NULL) < 0)
00264         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
00265     
00266     sa.sa_handler = SIG_IGN;
00267     if (sigaction(SIGPIPE, &sa, NULL) < 0)
00268         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
00269 
00270     /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy 
00271      * processing one */
00272     sigaddset(&sa.sa_mask, SIGHUP);
00273     sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
00274     sa.sa_handler = restart;
00275     if (sigaction(SIGHUP, &sa, NULL) < 0)
00276         ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
00277     if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
00278             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
00279 }
00280 
00281 /*****************************************************************
00282  * Here follows a long bunch of generic server bookkeeping stuff...
00283  */
00284 
00285 int ap_graceful_stop_signalled(void)
00286 {
00287     /* XXX - Does this really work? - Manoj */
00288     return is_graceful;
00289 }
00290 
00291 /*****************************************************************
00292  * Child process main loop.
00293  */
00294 
00295 static void process_socket(apr_pool_t *p, apr_socket_t *sock,
00296                            int my_child_num, apr_bucket_alloc_t *bucket_alloc)
00297 {
00298     conn_rec *current_conn;
00299     long conn_id = my_child_num;
00300     int csd;
00301     ap_sb_handle_t *sbh;
00302 
00303     (void)apr_os_sock_get(&csd, sock);
00304     
00305     if (csd >= FD_SETSIZE) {
00306         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
00307                      "filedescriptor (%u) larger than FD_SETSIZE (%u) "
00308                      "found, you probably need to rebuild Apache with a "
00309                      "larger FD_SETSIZE", csd, FD_SETSIZE);
00310         apr_socket_close(sock);
00311         return;
00312     }
00313 
00314     ap_create_sb_handle(&sbh, p, 0, my_child_num);
00315     current_conn = ap_run_create_connection(p, ap_server_conf,
00316                                             sock, conn_id, sbh,
00317                                             bucket_alloc);
00318 
00319     if (current_conn) {
00320         ap_process_connection(current_conn, sock);
00321         ap_lingering_close(current_conn);
00322     }
00323 }
00324 
00325 static int32 worker_thread(void * dummy)
00326 {
00327     proc_info * ti = dummy;
00328     int child_slot = ti->slot;
00329     apr_pool_t *tpool = ti->tpool;
00330     apr_allocator_t *allocator;
00331     apr_socket_t *csd = NULL;
00332     apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
00333     apr_bucket_alloc_t *bucket_alloc;
00334     apr_socket_t *sd = NULL;
00335     apr_status_t rv = APR_EINIT;
00336     int srv , n;
00337     int curr_pollfd = 0, last_pollfd = 0;
00338     sigset_t sig_mask;
00339     int requests_this_child = ap_max_requests_per_thread;
00340     apr_pollfd_t *pollset;
00341     /* each worker thread is in control of its own destiny...*/
00342     int this_worker_should_exit = 0; 
00343     free(ti);
00344 
00345     mpm_state = AP_MPMQ_STARTING;
00346 
00347     on_exit_thread(check_restart, (void*)child_slot);
00348           
00349     /* block the signals for this thread */
00350     sigfillset(&sig_mask);
00351     sigprocmask(SIG_BLOCK, &sig_mask, NULL);
00352 
00353     apr_allocator_create(&allocator);
00354     apr_allocator_max_free_set(allocator, ap_max_mem_free);
00355     apr_pool_create_ex(&ptrans, tpool, NULL, allocator);
00356     apr_allocator_owner_set(allocator, ptrans);
00357 
00358     apr_pool_tag(ptrans, "transaction");
00359 
00360     bucket_alloc = apr_bucket_alloc_create_ex(allocator);
00361 
00362     apr_thread_mutex_lock(worker_thread_count_mutex);
00363     worker_thread_count++;
00364     apr_thread_mutex_unlock(worker_thread_count_mutex);
00365 
00366     (void) ap_update_child_status_from_indexes(0, child_slot, SERVER_STARTING,
00367                                                (request_rec*)NULL);
00368                                   
00369     apr_poll_setup(&pollset, num_listening_sockets + 1, tpool);
00370     for(n=0 ; n <= num_listening_sockets ; n++)
00371         apr_poll_socket_add(pollset, listening_sockets[n], APR_POLLIN);
00372 
00373     mpm_state = AP_MPMQ_RUNNING;
00374 
00375     while (1) {
00376         /* If we're here, then chances are (unless we're the first thread created) 
00377          * we're going to be held up in the accept mutex, so doing this here
00378          * shouldn't hurt performance.
00379          */
00380 
00381         this_worker_should_exit |= (ap_max_requests_per_thread != 0) && (requests_this_child <= 0);
00382         
00383         if (this_worker_should_exit) break;
00384 
00385         (void) ap_update_child_status_from_indexes(0, child_slot, SERVER_READY,
00386                                                    (request_rec*)NULL);
00387 
00388         apr_thread_mutex_lock(accept_mutex);
00389 
00390         while (!this_worker_should_exit) {
00391             apr_int16_t event;
00392             apr_status_t ret;
00393 
00394             ret = apr_poll(pollset, num_listening_sockets + 1, &srv, -1);
00395 
00396             if (ret != APR_SUCCESS) {
00397                 if (APR_STATUS_IS_EINTR(ret)) {
00398                     continue;
00399                 }
00400                 /* poll() will only return errors in catastrophic
00401                  * circumstances. Let's try exiting gracefully, for now. */
00402                 ap_log_error(APLOG_MARK, APLOG_ERR, ret, (const server_rec *)
00403                              ap_server_conf, "apr_poll: (listen)");
00404                 this_worker_should_exit = 1;
00405             } else {
00406                 /* if we've bailed in apr_poll what's the point of trying to use the data? */
00407                 apr_poll_revents_get(&event, listening_sockets[0], pollset);
00408 
00409                 if (event & APR_POLLIN){
00410                     apr_sockaddr_t *rec_sa;
00411                     apr_size_t len = 5;
00412                     char *tmpbuf = apr_palloc(ptrans, sizeof(char) * 5);
00413                     apr_sockaddr_info_get(&rec_sa, "127.0.0.1", APR_UNSPEC, 7772, 0, ptrans);
00414                     
00415                     if ((ret = apr_recvfrom(rec_sa, listening_sockets[0], 0, tmpbuf, &len))
00416                         != APR_SUCCESS){
00417                         ap_log_error(APLOG_MARK, APLOG_ERR, ret, NULL, 
00418                             "error getting data from UDP!!");
00419                     }else {
00420                         /* add checking??? */              
00421                     }
00422                     this_worker_should_exit = 1;
00423                 }
00424             }
00425           
00426             if (this_worker_should_exit) break;
00427 
00428             if (num_listening_sockets == 1) {
00429                 sd = ap_listeners->sd;
00430                 goto got_fd;
00431             }
00432             else {
00433                 /* find a listener */
00434                 curr_pollfd = last_pollfd;
00435                 do {
00436                     curr_pollfd++;
00437 
00438                     if (curr_pollfd > num_listening_sockets)
00439                         curr_pollfd = 1;
00440                     
00441                     /* Get the revent... */
00442                     apr_poll_revents_get(&event, listening_sockets[curr_pollfd], pollset);
00443                     
00444                     if (event & APR_POLLIN) {
00445                         last_pollfd = curr_pollfd;
00446                         sd = listening_sockets[curr_pollfd];
00447                         goto got_fd;
00448                     }
00449                 } while (curr_pollfd != last_pollfd);
00450             }
00451         }
00452     got_fd:
00453 
00454         if (!this_worker_should_exit) {
00455             rv = apr_accept(&csd, sd, ptrans);
00456 
00457             apr_thread_mutex_unlock(accept_mutex);
00458             if (rv != APR_SUCCESS) {
00459                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
00460                   "apr_accept");
00461             } else {
00462                 process_socket(ptrans, csd, child_slot, bucket_alloc);
00463                 requests_this_child--;
00464             }
00465         }
00466         else {
00467             apr_thread_mutex_unlock(accept_mutex);
00468             break;
00469         }
00470         apr_pool_clear(ptrans);
00471     }
00472 
00473     ap_update_child_status_from_indexes(0, child_slot, SERVER_DEAD, (request_rec*)NULL);
00474 
00475     apr_bucket_alloc_destroy(bucket_alloc);
00476 
00477     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL,
00478                  "worker_thread %ld exiting", find_thread(NULL));
00479     
00480     apr_thread_mutex_lock(worker_thread_count_mutex);
00481     worker_thread_count--;
00482     apr_thread_mutex_unlock(worker_thread_count_mutex);
00483 
00484     return (0);
00485 }
00486 
00487 static int make_worker(int slot)
00488 {
00489     thread_id tid;
00490     proc_info *my_info = (proc_info *)malloc(sizeof(proc_info)); /* freed by thread... */
00491 
00492     if (my_info == NULL) {
00493         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
00494             "malloc: out of memory");
00495         clean_child_exit(APEXIT_CHILDFATAL);
00496     }
00497     
00498     my_info->slot = slot;
00499     apr_pool_create(&my_info->tpool, pchild);
00500     
00501     if (slot + 1 > ap_max_child_assigned)
00502             ap_max_child_assigned = slot + 1;
00503 
00504     if (one_process) {
00505         set_signals();
00506         ap_scoreboard_image->parent[0].pid = getpid();
00507         return 0;
00508     }
00509 
00510     (void) ap_update_child_status_from_indexes(0, slot, SERVER_STARTING, (request_rec*)NULL);
00511     tid = spawn_thread(worker_thread, "apache_worker", B_NORMAL_PRIORITY,
00512         my_info);
00513     if (tid < B_NO_ERROR) {
00514         ap_log_error(APLOG_MARK, APLOG_ERR, errno, NULL, 
00515             "spawn_thread: Unable to start a new thread");
00516         /* In case system resources are maxxed out, we don't want
00517          * Apache running away with the CPU trying to fork over and
00518          * over and over again. 
00519          */
00520         (void) ap_update_child_status_from_indexes(0, slot, SERVER_DEAD, 
00521                                                    (request_rec*)NULL);
00522         
00523         sleep(10);
00524         free(my_info);
00525         
00526         return -1;
00527     }
00528     resume_thread(tid);
00529 
00530     ap_scoreboard_image->servers[0][slot].tid = tid;
00531     return 0;
00532 }
00533 
00534 static void check_restart(void *data)
00535 {
00536     if (!restart_pending && !shutdown_pending) {
00537         int slot = (int)data;
00538         make_worker(slot);
00539         ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, 
00540             "spawning a new worker thread in slot %d", slot);
00541     }
00542 }
00543 
00544 /* start up a bunch of children */
00545 static void startup_threads(int number_to_start)
00546 {
00547     int i;
00548 
00549     for (i = 0; number_to_start && i < ap_thread_limit; ++i) {
00550         if (ap_scoreboard_image->servers[0][i].tid) {
00551             continue;
00552         }
00553         if (make_worker(i) < 0) {
00554             break;
00555         }
00556         --number_to_start;
00557     }
00558 }
00559 
00560 
00561 /*
00562  * spawn_rate is the number of children that will be spawned on the
00563  * next maintenance cycle if there aren't enough idle servers.  It is
00564  * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
00565  * without the need to spawn.
00566  */
00567 static int spawn_rate = 1;
00568 #ifndef MAX_SPAWN_RATE
00569 #define MAX_SPAWN_RATE  (32)
00570 #endif
00571 static int hold_off_on_exponential_spawning;
00572 
00573 static void perform_idle_server_maintenance(void)
00574 {
00575     int i;
00576     int free_length;
00577     int free_slots[MAX_SPAWN_RATE];
00578     int last_non_dead  = -1;
00579 
00580     /* initialize the free_list */
00581     free_length = 0;
00582 
00583     for (i = 0; i < ap_thread_limit; ++i) {
00584         if (ap_scoreboard_image->servers[0][i].tid == 0) {
00585             if (free_length < spawn_rate) {
00586                 free_slots[free_length] = i;
00587                 ++free_length;
00588             }
00589         }
00590         else {
00591             last_non_dead = i;
00592         }
00593 
00594         if (i >= ap_max_child_assigned && free_length >= spawn_rate) {
00595                  break;
00596             }
00597     }
00598     ap_max_child_assigned = last_non_dead + 1;
00599 
00600     if (free_length > 0) {
00601         for (i = 0; i < free_length; ++i) {
00602                 make_worker(free_slots[i]);
00603             }
00604             /* the next time around we want to spawn twice as many if this
00605              * wasn't good enough, but not if we've just done a graceful
00606              */
00607             if (hold_off_on_exponential_spawning) {
00608                 --hold_off_on_exponential_spawning;
00609             } else if (spawn_rate < MAX_SPAWN_RATE) {
00610                 spawn_rate *= 2;
00611             }
00612     } else {
00613         spawn_rate = 1;
00614     }
00615 }
00616 
00617 static void server_main_loop(int remaining_threads_to_start)
00618 {
00619     int child_slot;
00620     apr_exit_why_e exitwhy;
00621     int status;
00622     apr_proc_t pid;
00623     int i;
00624 
00625     while (!restart_pending && !shutdown_pending) {
00626 
00627         ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
00628          
00629         if (pid.pid >= 0) {
00630             if (ap_process_child_status(&pid, exitwhy, status) == APEXIT_CHILDFATAL) {
00631                 shutdown_pending = 1;
00632                 child_fatal = 1;
00633                 return;
00634             }
00635             /* non-fatal death... note that it's gone in the scoreboard. */
00636             child_slot = -1;
00637             for (i = 0; i < ap_max_child_assigned; ++i) {
00638                 if (ap_scoreboard_image->servers[0][i].tid == pid.pid) {
00639                     child_slot = i;
00640                     break;
00641                 }
00642             }
00643             if (child_slot >= 0) {
00644                 ap_scoreboard_image->servers[0][child_slot].tid = 0;
00645                 (void) ap_update_child_status_from_indexes(0, child_slot, 
00646                                                            SERVER_DEAD, 
00647                                                            (request_rec*)NULL);
00648                 
00649                 if (remaining_threads_to_start
00650                             && child_slot < ap_thread_limit) {
00651                     /* we're still doing a 1-for-1 replacement of dead
00652                      * children with new children
00653                      */
00654                     make_worker(child_slot);
00655                     --remaining_threads_to_start;
00656                         }
00657 #if APR_HAS_OTHER_CHILD
00658             }
00659             else if (apr_proc_other_child_read(&pid, status) == 0) {
00660                 /* handled */
00661 #endif
00662             }
00663             else if (is_graceful) {
00664                 /* Great, we've probably just lost a slot in the
00665                  * scoreboard.  Somehow we don't know about this
00666                  * child.
00667                  */
00668                  ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf,
00669                                           "long lost child came home! (pid %ld)", pid.pid);
00670             }
00671             
00672             /* Don't perform idle maintenance when a child dies,
00673              * only do it when there's a timeout.  Remember only a
00674              * finite number of children can die, and it's pretty
00675              * pathological for a lot to die suddenly.
00676              */
00677              continue;
00678          }
00679              else if (remaining_threads_to_start) {
00680              /* we hit a 1 second timeout in which none of the previous
00681               * generation of children needed to be reaped... so assume
00682               * they're all done, and pick up the slack if any is left.
00683               */
00684               startup_threads(remaining_threads_to_start);
00685               remaining_threads_to_start = 0;
00686               /* In any event we really shouldn't do the code below because
00687                * few of the servers we just started are in the IDLE state
00688                * yet, so we'd mistakenly create an extra server.
00689                */
00690               continue;
00691          }
00692          perform_idle_server_maintenance();
00693     }
00694 }
00695 
00696 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
00697 {
00698     switch(query_code){
00699         case AP_MPMQ_MAX_DAEMON_USED:
00700             *result = ap_max_child_assigned;
00701             return APR_SUCCESS;
00702         case AP_MPMQ_IS_THREADED:
00703             *result = AP_MPMQ_DYNAMIC;
00704             return APR_SUCCESS;
00705         case AP_MPMQ_IS_FORKED:
00706             *result = AP_MPMQ_NOT_SUPPORTED;
00707             return APR_SUCCESS;
00708         case AP_MPMQ_HARD_LIMIT_DAEMONS:
00709             *result = HARD_SERVER_LIMIT;
00710             return APR_SUCCESS;
00711         case AP_MPMQ_HARD_LIMIT_THREADS:
00712             *result = HARD_THREAD_LIMIT;
00713             return APR_SUCCESS;
00714         case AP_MPMQ_MAX_THREADS:
00715             *result = HARD_THREAD_LIMIT;
00716             return APR_SUCCESS;
00717         case AP_MPMQ_MIN_SPARE_DAEMONS:
00718             *result = 0;
00719             return APR_SUCCESS;
00720         case AP_MPMQ_MIN_SPARE_THREADS:    
00721             *result = max_spare_threads;
00722             return APR_SUCCESS;
00723         case AP_MPMQ_MAX_SPARE_DAEMONS:
00724             *result = 0;
00725             return APR_SUCCESS;
00726         case AP_MPMQ_MAX_SPARE_THREADS:
00727             *result = min_spare_threads;
00728             return APR_SUCCESS;
00729         case AP_MPMQ_MAX_REQUESTS_DAEMON:
00730             *result = ap_max_requests_per_thread;
00731             return APR_SUCCESS;
00732         case AP_MPMQ_MAX_DAEMONS:
00733             *result = HARD_SERVER_LIMIT;
00734             return APR_SUCCESS;
00735         case AP_MPMQ_MPM_STATE:
00736             *result = mpm_state;
00737             return APR_SUCCESS;
00738     }
00739     return APR_ENOTIMPL;
00740 }
00741 
00742 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
00743 {
00744     int remaining_threads_to_start, i,j;
00745     apr_status_t rv;
00746     ap_listen_rec *lr;    
00747     pconf = _pconf;
00748     ap_server_conf = s;
00749 
00750     /* Increase the available pool of fd's.  This code from
00751      * Joe Kloss <joek@be.com>
00752      */
00753     if( FD_SETSIZE > 128 && (i = _kset_fd_limit_( 128 )) < 0 ){
00754         ap_log_error(APLOG_MARK, APLOG_ERR, i, s,
00755             "could not set FD_SETSIZE (_kset_fd_limit_ failed)");
00756     }
00757 
00758     /* BeOS R5 doesn't support pipes on select() calls, so we use a 
00759        UDP socket as these are supported in both R5 and BONE.  If we only cared
00760        about BONE we'd use a pipe, but there it is.
00761        As we have UDP support in APR, now use the APR functions and check all the
00762        return values...
00763       */
00764     if (apr_sockaddr_info_get(&udp_sa, "127.0.0.1", APR_UNSPEC, 7772, 0, _pconf)
00765         != APR_SUCCESS){
00766         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
00767             "couldn't create control socket information, shutting down");
00768         return 1;
00769     }
00770     if (apr_socket_create(&udp_sock, udp_sa->family, SOCK_DGRAM,
00771                       _pconf) != APR_SUCCESS){
00772         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
00773             "couldn't create control socket, shutting down");
00774         return 1;
00775     }
00776     if (apr_bind(udp_sock, udp_sa) != APR_SUCCESS){
00777         ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
00778             "couldn't bind UDP socket!");
00779         return 1;
00780     }
00781  
00782     if ((num_listening_sockets = ap_setup_listeners(ap_server_conf)) < 1) {
00783         ap_log_error(APLOG_MARK, APLOG_ALERT, 0, s,
00784             "no listening sockets available, shutting down");
00785         return 1;
00786     }
00787 
00788     ap_log_pid(pconf, ap_pid_fname);
00789 
00790     /*
00791      * Create our locks... 
00792      */
00793     
00794     /* accept_mutex
00795      * used to lock around select so we only have one thread
00796      * in select at a time
00797      */
00798     rv = apr_thread_mutex_create(&accept_mutex, 0, pconf);
00799     if (rv != APR_SUCCESS) {
00800         /* tsch tsch, can't have more than one thread in the accept loop
00801            at a time so we need to fall on our sword... */
00802         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
00803                      "Couldn't create accept lock");
00804         return 1;
00805     }
00806 
00807     /* worker_thread_count_mutex
00808      * locks the worker_thread_count so we have ana ccurate count...
00809      */
00810     rv = apr_thread_mutex_create(&worker_thread_count_mutex, 0, pconf);
00811     if (rv != APR_SUCCESS) {
00812         ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
00813                      "Couldn't create worker thread count lock");
00814         return 1;
00815     }
00816 
00817     /*
00818      * Startup/shutdown... 
00819      */
00820     
00821     if (!is_graceful) {
00822         /* setup the scoreboard shared memory */
00823         if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
00824             return 1;
00825         }
00826 
00827         for (i = 0; i < HARD_SERVER_LIMIT; i++) {
00828             ap_scoreboard_image->parent[i].pid = 0;
00829             for (j = 0;j < HARD_THREAD_LIMIT; j++)
00830                 ap_scoreboard_image->servers[i][j].tid = 0;
00831         }
00832     }
00833 
00834     if (HARD_SERVER_LIMIT == 1)
00835         ap_scoreboard_image->parent[0].pid = getpid();
00836 
00837     set_signals();
00838 
00839     /* Sanity checks to avoid thrashing... */
00840     if (max_spare_threads < min_spare_threads )
00841         max_spare_threads = min_spare_threads;
00842 
00843     /* If we're doing a graceful_restart then we're going to see a lot
00844      * of threads exiting immediately when we get into the main loop
00845      * below (because we just sent them AP_SIG_GRACEFUL).  This happens 
00846      * pretty rapidly... and for each one that exits we'll start a new one 
00847      * until we reach at least threads_min_free.  But we may be permitted to
00848      * start more than that, so we'll just keep track of how many we're
00849      * supposed to start up without the 1 second penalty between each fork.
00850      */
00851     remaining_threads_to_start = ap_threads_to_start;
00852     /* sanity check on the number to start... */
00853     if (remaining_threads_to_start > ap_thread_limit) {
00854             remaining_threads_to_start = ap_thread_limit;
00855     }
00856 
00857     /* setup the child pool to use for the workers.  Each worker creates
00858      * a seperate pool of its own to use.
00859      */
00860     apr_pool_create(&pchild, pconf);
00861 
00862     /* Now that we have the child pool (pchild) we can allocate
00863      * the listenfds and creat the pollset...
00864      */
00865     listening_sockets = apr_palloc(pchild,
00866        sizeof(*listening_sockets) * (num_listening_sockets + 1));
00867 
00868     listening_sockets[0] = udp_sock;
00869     for (lr = ap_listeners, i = 1; i <= num_listening_sockets; lr = lr->next, ++i)
00870             listening_sockets[i]=lr->sd;
00871 
00872     /* we assume all goes OK...hmm might want to check that! */
00873     /* if we're in one_process mode we don't want to start threads
00874      * do we??
00875      */
00876     if (!is_graceful && !one_process) {
00877             startup_threads(remaining_threads_to_start);
00878             remaining_threads_to_start = 0;
00879     }
00880     else {
00881             /* give the system some time to recover before kicking into
00882              * exponential mode */
00883         hold_off_on_exponential_spawning = 10;
00884     }
00885 
00886     /*
00887      * record that we've entered the world !
00888      */
00889     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
00890                 "%s configured -- resuming normal operations",
00891                 ap_get_server_version());
00892 
00893     ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
00894                 "Server built: %s", ap_get_server_built());
00895 
00896     restart_pending = shutdown_pending = 0;
00897 
00898     /*
00899      * main_loop until it's all over
00900      */
00901     if (!one_process) {
00902         server_main_loop(remaining_threads_to_start);
00903     
00904         tell_workers_to_exit(); /* if we get here we're exiting... */
00905         sleep(1); /* give them a brief chance to exit */
00906     } else {
00907         proc_info *my_info = (proc_info *)malloc(sizeof(proc_info));
00908         my_info->slot = 0;
00909         apr_pool_create(&my_info->tpool, pchild);
00910         worker_thread(my_info);
00911     }
00912         
00913     /* close the UDP socket we've been using... */
00914     apr_socket_close(listening_sockets[0]);
00915 
00916     if ((one_process || shutdown_pending) && !child_fatal) {
00917         const char *pidfile = NULL;
00918         pidfile = ap_server_root_relative (pconf, ap_pid_fname);
00919         if ( pidfile != NULL && unlink(pidfile) == 0)
00920             ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
00921                          "removed PID file %s (pid=%ld)", pidfile, 
00922                          (long)getpid());
00923     }
00924 
00925     if (one_process) {
00926         return 1;
00927     }
00928         
00929     /*
00930      * If we get here we're shutting down...
00931      */
00932     if (shutdown_pending) {
00933         /* Time to gracefully shut down:
00934          * Kill child processes, tell them to call child_exit, etc...
00935          */
00936         if (beosd_killpg(getpgrp(), SIGTERM) < 0)
00937             ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
00938              "killpg SIGTERM");
00939       
00940         /* use ap_reclaim_child_processes starting with SIGTERM */
00941         ap_reclaim_child_processes(1);
00942 
00943         if (!child_fatal) {         /* already recorded */
00944             /* record the shutdown in the log */
00945             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
00946                          "caught SIGTERM, shutting down");
00947         }
00948     
00949         return 1;
00950     }
00951 
00952     /* we've been told to restart */
00953     signal(SIGHUP, SIG_IGN);
00954 
00955     if (is_graceful) {
00956         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
00957                     AP_SIG_GRACEFUL_STRING " received.  Doing graceful restart");
00958     }
00959     else {
00960         /* Kill 'em all.  Since the child acts the same on the parents SIGTERM 
00961          * and a SIGHUP, we may as well use the same signal, because some user
00962          * pthreads are stealing signals from us left and right.
00963          */
00964             
00965         ap_reclaim_child_processes(1);          /* Start with SIGTERM */
00966             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
00967                     "SIGHUP received.  Attempting to restart");
00968     }
00969     
00970     /* just before we go, tidy up the locks we've created to prevent a 
00971      * potential leak of semaphores... */
00972     apr_thread_mutex_destroy(worker_thread_count_mutex);
00973     apr_thread_mutex_destroy(accept_mutex);
00974     
00975     return 0;
00976 }
00977 
00978 static int beos_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
00979 {
00980     static int restart_num = 0;
00981     int no_detach, debug, foreground;
00982     apr_status_t rv;
00983 
00984     mpm_state = AP_MPMQ_STARTING;
00985 
00986     debug = ap_exists_config_define("DEBUG");
00987 
00988     if (debug) {
00989         foreground = one_process = 1;
00990         no_detach = 0;
00991     }
00992     else
00993     {
00994         one_process = ap_exists_config_define("ONE_PROCESS");
00995         no_detach = ap_exists_config_define("NO_DETACH");
00996         foreground = ap_exists_config_define("FOREGROUND");
00997     }
00998 
00999     /* sigh, want this only the second time around */
01000     if (restart_num++ == 1) {
01001         is_graceful = 0;
01002         
01003         if (!one_process && !foreground) {
01004             rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
01005                                            : APR_PROC_DETACH_DAEMONIZE);
01006             if (rv != APR_SUCCESS) {
01007                 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
01008                              "apr_proc_detach failed");
01009                 return HTTP_INTERNAL_SERVER_ERROR;
01010             }                  
01011         }
01012 
01013         server_pid = getpid();
01014     }
01015 
01016     beosd_pre_config();
01017     ap_listen_pre_config();
01018     ap_threads_to_start = DEFAULT_START_THREADS;
01019     min_spare_threads = DEFAULT_MIN_FREE_THREADS;
01020     max_spare_threads = DEFAULT_MAX_FREE_THREADS;
01021     ap_thread_limit = HARD_THREAD_LIMIT;
01022     ap_pid_fname = DEFAULT_PIDLOG;
01023     ap_max_requests_per_thread = DEFAULT_MAX_REQUESTS_PER_THREAD;
01024 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
01025         ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
01026 #endif
01027 
01028     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
01029 
01030     return OK;
01031 }
01032 
01033 static void beos_hooks(apr_pool_t *p)
01034 {
01035     one_process = 0;
01036     
01037     ap_hook_pre_config(beos_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST); 
01038 }
01039 
01040 static const char *set_threads_to_start(cmd_parms *cmd, void *dummy, const char *arg) 
01041 {
01042     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
01043     if (err != NULL) {
01044         return err;
01045     }
01046 
01047     ap_threads_to_start = atoi(arg);
01048     if (ap_threads_to_start < 0) {
01049         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
01050                      "StartThreads set to a value less than 0, reset to 1");
01051         ap_threads_to_start = 1;
01052     }
01053     return NULL;
01054 }
01055 
01056 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
01057 {
01058     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
01059     if (err != NULL) {
01060         return err;
01061     }
01062 
01063     min_spare_threads = atoi(arg);
01064     if (min_spare_threads <= 0) {
01065        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
01066                     "WARNING: detected MinSpareThreads set to non-positive.");
01067        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
01068                     "Resetting to 1 to avoid almost certain Apache failure.");
01069        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
01070                     "Please read the documentation.");
01071        min_spare_threads = 1;
01072     }
01073        
01074     return NULL;
01075 }
01076 
01077 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
01078 {
01079     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
01080     if (err != NULL) {
01081         return err;
01082     }
01083 
01084     max_spare_threads = atoi(arg);
01085     return NULL;
01086 }
01087 
01088 static const char *set_threads_limit (cmd_parms *cmd, void *dummy, const char *arg) 
01089 {
01090     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
01091     if (err != NULL) {
01092         return err;
01093     }
01094 
01095     ap_thread_limit = atoi(arg);
01096     if (ap_thread_limit > HARD_THREAD_LIMIT) {
01097        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
01098                     "WARNING: MaxClients of %d exceeds compile time limit "
01099                     "of %d servers,", ap_thread_limit, HARD_THREAD_LIMIT);
01100        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
01101                     " lowering MaxClients to %d.  To increase, please "
01102                     "see the", HARD_THREAD_LIMIT);
01103        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
01104                     " HARD_THREAD_LIMIT define in server/mpm/beos/mpm_default.h.");
01105        ap_thread_limit = HARD_THREAD_LIMIT;
01106     } 
01107     else if (ap_thread_limit < 1) {
01108         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
01109                      "WARNING: Require MaxClients > 0, setting to %d", HARD_THREAD_LIMIT);
01110         ap_thread_limit = HARD_THREAD_LIMIT;
01111     }
01112     return NULL;
01113 }
01114 
01115 static const char *set_max_requests_per_thread (cmd_parms *cmd, void *dummy, const char *arg)
01116 {
01117     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
01118     if (err != NULL) {
01119         return err;
01120     }
01121 
01122     ap_max_requests_per_thread = atoi(arg);
01123     if (ap_max_requests_per_thread < 0) {
01124         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
01125                      "WARNING: MaxRequestsPerThread was set below 0"
01126                      "reset to 0, but this may not be what you want.");
01127         ap_max_requests_per_thread = 0;
01128     }
01129 
01130     return NULL;
01131 }
01132 
01133 static const command_rec beos_cmds[] = {
01134 BEOS_DAEMON_COMMANDS,
01135 LISTEN_COMMANDS,
01136 AP_INIT_TAKE1( "StartThreads", set_threads_to_start, NULL, RSRC_CONF,
01137   "Number of threads to launch at server startup"),
01138 AP_INIT_TAKE1( "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
01139   "Minimum number of idle children, to handle request spikes"),
01140 AP_INIT_TAKE1( "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
01141   "Maximum number of idle children" ),
01142 AP_INIT_TAKE1( "MaxClients", set_threads_limit, NULL, RSRC_CONF, 
01143   "Maximum number of children alive at the same time (max threads)" ),
01144 AP_INIT_TAKE1( "MaxRequestsPerThread", set_max_requests_per_thread, NULL, RSRC_CONF,
01145   "Maximum number of requests served by a thread" ),
01146 { NULL }
01147 };
01148 
01149 module AP_MODULE_DECLARE_DATA mpm_beos_module = {
01150     MPM20_MODULE_STUFF,
01151     NULL,                       /* hook to run before apache parses args */
01152     NULL,                       /* create per-directory config structure */
01153     NULL,                       /* merge per-directory config structures */
01154     NULL,                       /* create per-server config structure */
01155     NULL,                       /* merge per-server config structures */
01156     beos_cmds,          /* command apr_table_t */
01157     beos_hooks          /* register_hooks */
01158 };
01159