import from branch_1_1:
[freeradius.git] / src / main / threads.c
1 /*
2  * threads.c    request threading support
3  *
4  * Version:     $Id$
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  *
20  * Copyright 2000,2006  The FreeRADIUS server project
21  * Copyright 2000  Alan DeKok <aland@ox.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include <freeradius-devel/radiusd.h>
28 #include <freeradius-devel/rad_assert.h>
29
30 /*
31  *      Other OS's have sem_init, OS X doesn't.
32  */
33 #ifdef HAVE_SEMAPHORE_H
34 #include <semaphore.h>
35 #endif
36
37 #ifdef DARWIN
38 #include <mach/task.h>
39 #include <mach/semaphore.h>
40
41 #undef sem_t
42 #define sem_t semaphore_t
43 #undef sem_init
44 #define sem_init(s,p,c) semaphore_create(mach_task_self(),s,SYNC_POLICY_FIFO,c)
45 #undef sem_wait
46 #define sem_wait(s) semaphore_wait(*s)
47 #undef sem_post
48 #define sem_post(s) semaphore_signal(*s)
49 #endif
50
51 #ifdef HAVE_SYS_WAIT_H
52 #include <sys/wait.h>
53 #endif
54
55 #ifdef HAVE_PTHREAD_H
56
57 #ifdef HAVE_OPENSSL_CRYPTO_H
58 #include <openssl/crypto.h>
59 #endif
60 #ifdef HAVE_OPENSSL_ERR_H
61 #include <openssl/err.h>
62 #endif
63
64 #define SEMAPHORE_LOCKED        (0)
65 #define SEMAPHORE_UNLOCKED      (1)
66
67 #define THREAD_RUNNING          (1)
68 #define THREAD_CANCELLED        (2)
69 #define THREAD_EXITED           (3)
70
71 #define NUM_FIFOS               RAD_LISTEN_MAX
72
73
74 /*
75  *  A data structure which contains the information about
76  *  the current thread.
77  *
78  *  pthread_id     pthread id
79  *  thread_num     server thread number, 1...number of threads
80  *  semaphore     used to block the thread until a request comes in
81  *  status        is the thread running or exited?
82  *  request_count the number of requests that this thread has handled
83  *  timestamp     when the thread started executing.
84  */
85 typedef struct THREAD_HANDLE {
86         struct THREAD_HANDLE *prev;
87         struct THREAD_HANDLE *next;
88         pthread_t            pthread_id;
89         int                  thread_num;
90         int                  status;
91         unsigned int         request_count;
92         time_t               timestamp;
93         REQUEST              *request;
94 } THREAD_HANDLE;
95
96 /*
97  *      For the request queue.
98  */
99 typedef struct request_queue_t {
100         REQUEST           *request;
101         RAD_REQUEST_FUNP  fun;
102 } request_queue_t;
103
104 typedef struct thread_fork_t {
105         pid_t           pid;
106         int             status;
107         int             exited;
108 } thread_fork_t;
109
110
111 /*
112  *      A data structure to manage the thread pool.  There's no real
113  *      need for a data structure, but it makes things conceptually
114  *      easier.
115  */
116 typedef struct THREAD_POOL {
117         THREAD_HANDLE *head;
118         THREAD_HANDLE *tail;
119
120         int total_threads;
121         int active_threads;     /* protected by queue_mutex */
122         int max_thread_num;
123         int start_threads;
124         int max_threads;
125         int min_spare_threads;
126         int max_spare_threads;
127         unsigned int max_requests_per_thread;
128         unsigned long request_count;
129         time_t time_last_spawned;
130         int cleanup_delay;
131         int spawn_flag;
132
133         pthread_mutex_t wait_mutex;
134         lrad_hash_table_t *waiters;
135
136         /*
137          *      All threads wait on this semaphore, for requests
138          *      to enter the queue.
139          */
140         sem_t           semaphore;
141
142         /*
143          *      To ensure only one thread at a time touches the queue.
144          */
145         pthread_mutex_t queue_mutex;
146
147         int             max_queue_size;
148         int             num_queued;
149         int             can_read_detail;
150         lrad_fifo_t     *fifo[NUM_FIFOS];
151 } THREAD_POOL;
152
153 static THREAD_POOL thread_pool;
154 static int pool_initialized = FALSE;
155
156
157 /*
158  *      A mapping of configuration file names to internal integers
159  */
160 static const CONF_PARSER thread_config[] = {
161         { "start_servers",           PW_TYPE_INTEGER, 0, &thread_pool.start_threads,           "5" },
162         { "max_servers",             PW_TYPE_INTEGER, 0, &thread_pool.max_threads,             "32" },
163         { "min_spare_servers",       PW_TYPE_INTEGER, 0, &thread_pool.min_spare_threads,       "3" },
164         { "max_spare_servers",       PW_TYPE_INTEGER, 0, &thread_pool.max_spare_threads,       "10" },
165         { "max_requests_per_server", PW_TYPE_INTEGER, 0, &thread_pool.max_requests_per_thread, "0" },
166         { "cleanup_delay",           PW_TYPE_INTEGER, 0, &thread_pool.cleanup_delay,           "5" },
167         { "max_queue_size",          PW_TYPE_INTEGER, 0, &thread_pool.max_queue_size,           "65536" },
168         { NULL, -1, 0, NULL, NULL }
169 };
170
171
172 #ifdef HAVE_OPENSSL_CRYPTO_H
173
174 /*
175  *      If we're linking against OpenSSL, then it is the
176  *      duty of the application, if it is multithreaded,
177  *      to provide OpenSSL with appropriate thread id
178  *      and mutex locking functions
179  *
180  *      Note: this only implements static callbacks.
181  *      OpenSSL does not use dynamic locking callbacks
182  *      right now, but may in the futiure, so we will have
183  *      to add them at some point.
184  */
185
186 static pthread_mutex_t *ssl_mutexes = NULL;
187
188 static unsigned long ssl_id_function(void)
189 {
190         return (unsigned long) pthread_self();
191 }
192
193 static void ssl_locking_function(int mode, int n, const char *file, int line)
194 {
195         file = file;            /* -Wunused */
196         line = line;            /* -Wunused */
197
198         if (mode & CRYPTO_LOCK) {
199                 pthread_mutex_lock(&(ssl_mutexes[n]));
200         } else {
201                 pthread_mutex_unlock(&(ssl_mutexes[n]));
202         }
203 }
204
205 static int setup_ssl_mutexes(void)
206 {
207         int i;
208
209         ssl_mutexes = rad_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
210         if (!ssl_mutexes) {
211                 radlog(L_ERR, "Error allocating memory for SSL mutexes!");
212                 return 0;
213         }
214
215         for (i = 0; i < CRYPTO_num_locks(); i++) {
216                 pthread_mutex_init(&(ssl_mutexes[i]), NULL);
217         }
218
219         CRYPTO_set_id_callback(ssl_id_function);
220         CRYPTO_set_locking_callback(ssl_locking_function);
221
222         return 1;
223 }
224 #endif
225
226
227 /*
228  *      We don't want to catch SIGCHLD for a host of reasons.
229  *
230  *      - exec_wait means that someone, somewhere, somewhen, will
231  *      call waitpid(), and catch the child.
232  *
233  *      - SIGCHLD is delivered to a random thread, not the one that
234  *      forked.
235  *
236  *      - if another thread catches the child, we have to coordinate
237  *      with the thread doing the waiting.
238  *
239  *      - if we don't waitpid() for non-wait children, they'll be zombies,
240  *      and will hang around forever.
241  *
242  */
243 static void reap_children(void)
244 {
245         pid_t pid;
246         int status;
247         thread_fork_t mytf, *tf;
248
249
250         pthread_mutex_lock(&thread_pool.wait_mutex);
251
252         do {
253                 pid = waitpid(0, &status, WNOHANG);
254                 if (pid <= 0) break;
255
256                 mytf.pid = pid;
257                 tf = lrad_hash_table_finddata(thread_pool.waiters, &mytf);
258                 if (!tf) continue;
259
260                 tf->status = status;
261                 tf->exited = 1;
262         } while (lrad_hash_table_num_elements(thread_pool.waiters) > 0);
263
264         pthread_mutex_unlock(&thread_pool.wait_mutex);
265 }
266
267 /*
268  *      Add a request to the list of waiting requests.
269  *      This function gets called ONLY from the main handler thread...
270  *
271  *      This function should never fail.
272  */
273 static int request_enqueue(REQUEST *request, RAD_REQUEST_FUNP fun)
274 {
275         int fifo;
276         request_queue_t *entry;
277
278         pthread_mutex_lock(&thread_pool.queue_mutex);
279
280         thread_pool.request_count++;
281
282         if (thread_pool.num_queued >= thread_pool.max_queue_size) {
283                 pthread_mutex_unlock(&thread_pool.queue_mutex);
284
285                 /*
286                  *      Mark the request as done.
287                  */
288                 radlog(L_ERR|L_CONS, "!!! ERROR !!! The server is blocked: discarding new request %d", request->number);
289                 request->child_state = REQUEST_DONE;
290                 return 0;
291         }
292
293         entry = rad_malloc(sizeof(*entry));
294         entry->request = request;
295         entry->fun = fun;
296
297         /*
298          *      Push the request onto the appropriate fifo for that
299          */
300         if (!lrad_fifo_push(thread_pool.fifo[request->priority],
301                             entry)) {
302                 pthread_mutex_unlock(&thread_pool.queue_mutex);
303                 radlog(L_ERR, "!!! ERROR !!! Failed inserting request %d into the queue", request->number);
304                 request->child_state = REQUEST_DONE;
305                 return 0;
306         }
307
308         /*
309          *      We've added an entry that didn't come from the detail
310          *      file.  Note that the child thread should signal the
311          *      main worker thread again when the queue becomes empty.
312          */
313         if (request->listener->type != RAD_LISTEN_DETAIL) {
314                 thread_pool.can_read_detail = FALSE;
315         }
316
317         thread_pool.num_queued++;
318
319         pthread_mutex_unlock(&thread_pool.queue_mutex);
320
321         /*
322          *      There's one more request in the queue.
323          *
324          *      Note that we're not touching the queue any more, so
325          *      the semaphore post is outside of the mutex.  This also
326          *      means that when the thread wakes up and tries to lock
327          *      the mutex, it will be unlocked, and there won't be
328          *      contention.
329          */
330         sem_post(&thread_pool.semaphore);
331
332         return 1;
333 }
334
335 /*
336  *      Remove a request from the queue.
337  */
338 static int request_dequeue(REQUEST **request, RAD_REQUEST_FUNP *fun)
339 {
340         RAD_LISTEN_TYPE i, start;
341         request_queue_t *entry;
342
343         reap_children();
344
345         pthread_mutex_lock(&thread_pool.queue_mutex);
346
347         /*
348          *      Clear old requests from all queues.
349          *
350          *      We only do one pass over the queue, in order to
351          *      amortize the work across the child threads.  Since we
352          *      do N checks for one request de-queued, the old
353          *      requests will be quickly cleared.
354          */
355         for (i = 0; i < RAD_LISTEN_MAX; i++) {
356                 entry = lrad_fifo_peek(thread_pool.fifo[i]);
357                 if (!entry ||
358                     (entry->request->master_state != REQUEST_STOP_PROCESSING)) {
359                         continue;
360 }
361                 /*
362                  *      This entry was marked to be stopped.  Acknowledge it.
363                  */
364                 entry = lrad_fifo_pop(thread_pool.fifo[i]);
365                 rad_assert(entry != NULL);
366                 entry->request->child_state = REQUEST_DONE;
367         }
368
369         start = 0;
370  retry:
371         /*
372          *      Pop results from the top of the queue
373          */
374         for (i = start; i < RAD_LISTEN_MAX; i++) {
375                 entry = lrad_fifo_pop(thread_pool.fifo[i]);
376                 if (entry) {
377                         start = i;
378                         break;
379                 }
380         }
381
382         if (!entry) {
383                 pthread_mutex_unlock(&thread_pool.queue_mutex);
384                 *request = NULL;
385                 *fun = NULL;
386                 return 0;
387         }
388
389         rad_assert(thread_pool.num_queued > 0);
390         thread_pool.num_queued--;
391         *request = entry->request;
392         *fun = entry->fun;
393         free(entry);
394
395         rad_assert(*request != NULL);
396         rad_assert((*request)->magic == REQUEST_MAGIC);
397         rad_assert(*fun != NULL);
398
399         /*
400          *      If the request has sat in the queue for too long,
401          *      kill it.
402          *
403          *      The main clean-up code can't delete the request from
404          *      the queue, and therefore won't clean it up until we
405          *      have acknowledged it as "done".
406          */
407         if ((*request)->master_state == REQUEST_STOP_PROCESSING) {
408                 (*request)->child_state = REQUEST_DONE;
409                 goto retry;
410         }
411
412         /*
413          *      The thread is currently processing a request.
414          */
415         thread_pool.active_threads++;
416
417         pthread_mutex_unlock(&thread_pool.queue_mutex);
418
419         return 1;
420 }
421
422
423 /*
424  *      The main thread handler for requests.
425  *
426  *      Wait on the semaphore until we have it, and process the request.
427  */
428 static void *request_handler_thread(void *arg)
429 {
430         RAD_REQUEST_FUNP  fun;
431         THREAD_HANDLE     *self = (THREAD_HANDLE *) arg;
432
433         /*
434          *      Loop forever, until told to exit.
435          */
436         do {
437                 int can_read_detail;
438
439                 /*
440                  *      Wait to be signalled.
441                  */
442                 DEBUG2("Thread %d waiting to be assigned a request",
443                        self->thread_num);
444         re_wait:
445                 if (sem_wait(&thread_pool.semaphore) != 0) {
446                         /*
447                          *      Interrupted system call.  Go back to
448                          *      waiting, but DON'T print out any more
449                          *      text.
450                          */
451                         if (errno == EINTR) {
452                                 DEBUG2("Re-wait %d", self->thread_num);
453                                 goto re_wait;
454                         }
455                         radlog(L_ERR, "Thread %d failed waiting for semaphore: %s: Exiting\n",
456                                self->thread_num, strerror(errno));
457                         break;
458                 }
459
460                 DEBUG2("Thread %d got semaphore", self->thread_num);
461
462                 /*
463                  *      Try to grab a request from the queue.
464                  *
465                  *      It may be empty, in which case we fail
466                  *      gracefully.
467                  */
468                 if (!request_dequeue(&self->request, &fun)) continue;
469
470                 self->request->child_pid = self->pthread_id;
471                 self->request_count++;
472
473                 DEBUG2("Thread %d handling request %d, (%d handled so far)",
474                        self->thread_num, self->request->number,
475                        self->request_count);
476
477                 radius_handle_request(self->request, fun);
478
479                 /*
480                  *      Update the active threads.
481                  */
482                 pthread_mutex_lock(&thread_pool.queue_mutex);
483                 rad_assert(thread_pool.active_threads > 0);
484                 thread_pool.active_threads--;
485
486                 /*
487                  *      If we're not currently allowed to read the
488                  *      detail file, AND there are no requests queued,
489                  *      THEN signal the main worker thread that
490                  *      there's at least one waiting thread (us) who
491                  *      can accept a packet from the detail file.
492                  */
493                 can_read_detail = FALSE;
494                 if (!thread_pool.can_read_detail &&
495                     (thread_pool.num_queued == 0)) {
496                         can_read_detail = TRUE;
497                 }
498
499                 pthread_mutex_unlock(&thread_pool.queue_mutex);
500
501                 /*
502                  *      Do this out of the lock to be nice to everyone.
503                  */
504                 if (can_read_detail) {
505                         radius_signal_self(RADIUS_SIGNAL_SELF_DETAIL);
506                 }
507
508         } while (self->status != THREAD_CANCELLED);
509
510         DEBUG2("Thread %d exiting...", self->thread_num);
511
512 #ifdef HAVE_OPENSSL_ERR_H
513         /*
514          *      If we linked with OpenSSL, the application
515          *      must remove the thread's error queue before
516          *      exiting to prevent memory leaks.
517          */
518         ERR_remove_state(0);
519 #endif
520
521         /*
522          *  Do this as the LAST thing before exiting.
523          */
524         self->status = THREAD_EXITED;
525
526         return NULL;
527 }
528
529 /*
530  *      Take a THREAD_HANDLE, delete it from the thread pool and
531  *      free its resources.
532  *
533  *      This function is called ONLY from the main server thread,
534  *      ONLY after the thread has exited.
535  */
536 static void delete_thread(THREAD_HANDLE *handle)
537 {
538         THREAD_HANDLE *prev;
539         THREAD_HANDLE *next;
540
541         rad_assert(handle->request == NULL);
542
543         DEBUG2("Deleting thread %d", handle->thread_num);
544
545         prev = handle->prev;
546         next = handle->next;
547         rad_assert(thread_pool.total_threads > 0);
548         thread_pool.total_threads--;
549
550         /*
551          *      Remove the handle from the list.
552          */
553         if (prev == NULL) {
554                 rad_assert(thread_pool.head == handle);
555                 thread_pool.head = next;
556         } else {
557                 prev->next = next;
558         }
559
560         if (next == NULL) {
561                 rad_assert(thread_pool.tail == handle);
562                 thread_pool.tail = prev;
563         } else {
564                 next->prev = prev;
565         }
566
567         /*
568          *      Free the handle, now that it's no longer referencable.
569          */
570         free(handle);
571 }
572
573
574 /*
575  *      Spawn a new thread, and place it in the thread pool.
576  *
577  *      The thread is started initially in the blocked state, waiting
578  *      for the semaphore.
579  */
580 static THREAD_HANDLE *spawn_thread(time_t now)
581 {
582         int rcode;
583         THREAD_HANDLE *handle;
584         pthread_attr_t attr;
585
586         /*
587          *      Ensure that we don't spawn too many threads.
588          */
589         if (thread_pool.total_threads >= thread_pool.max_threads) {
590                 DEBUG2("Thread spawn failed.  Maximum number of threads (%d) already running.", thread_pool.max_threads);
591                 return NULL;
592         }
593
594         /*
595          *      Allocate a new thread handle.
596          */
597         handle = (THREAD_HANDLE *) rad_malloc(sizeof(THREAD_HANDLE));
598         memset(handle, 0, sizeof(THREAD_HANDLE));
599         handle->prev = NULL;
600         handle->next = NULL;
601         handle->pthread_id = NO_SUCH_CHILD_PID;
602         handle->thread_num = thread_pool.max_thread_num++;
603         handle->request_count = 0;
604         handle->status = THREAD_RUNNING;
605         handle->timestamp = time(NULL);
606
607         /*
608          *      Initialize the thread's attributes to detached.
609          *
610          *      We could call pthread_detach() later, but if the thread
611          *      exits between the create & detach calls, it will need to
612          *      be joined, which will never happen.
613          */
614         pthread_attr_init(&attr);
615         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
616
617         /*
618          *      Create the thread detached, so that it cleans up it's
619          *      own memory when it exits.
620          *
621          *      Note that the function returns non-zero on error, NOT
622          *      -1.  The return code is the error, and errno isn't set.
623          */
624         rcode = pthread_create(&handle->pthread_id, &attr,
625                         request_handler_thread, handle);
626         if (rcode != 0) {
627                 radlog(L_ERR|L_CONS, "FATAL: Thread create failed: %s",
628                        strerror(rcode));
629                 exit(1);
630         }
631         pthread_attr_destroy(&attr);
632
633         /*
634          *      One more thread to go into the list.
635          */
636         thread_pool.total_threads++;
637         DEBUG2("Thread spawned new child %d. Total threads in pool: %d",
638                         handle->thread_num, thread_pool.total_threads);
639
640         /*
641          *      Add the thread handle to the tail of the thread pool list.
642          */
643         if (thread_pool.tail) {
644                 thread_pool.tail->next = handle;
645                 handle->prev = thread_pool.tail;
646                 thread_pool.tail = handle;
647         } else {
648                 rad_assert(thread_pool.head == NULL);
649                 thread_pool.head = thread_pool.tail = handle;
650         }
651
652         /*
653          *      Update the time we last spawned a thread.
654          */
655         thread_pool.time_last_spawned = now;
656
657         /*
658          *      And return the new handle to the caller.
659          */
660         return handle;
661 }
662
663 /*
664  *      Temporary function to prevent server from executing a SIGHUP
665  *      until all threads are finished handling requests.  This returns
666  *      the number of active threads to 'radiusd.c'.
667  */
668 int total_active_threads(void)
669 {
670         /*
671          *      We don't acquire the mutex, so this is just an estimate.
672          *      We can't return with the lock held, so there's no point
673          *      in getting the guaranteed correct value; by the time
674          *      the caller sees it, it can be wrong again.
675          */
676         return thread_pool.active_threads;
677 }
678
679
680 static uint32_t pid_hash(const void *data)
681 {
682         const thread_fork_t *tf = data;
683
684         return lrad_hash(&tf->pid, sizeof(tf->pid));
685 }
686
687 static int pid_cmp(const void *one, const void *two)
688 {
689         const thread_fork_t *a = one;
690         const thread_fork_t *b = two;
691
692         return (a->pid - b->pid);
693 }
694
695 /*
696  *      Allocate the thread pool, and seed it with an initial number
697  *      of threads.
698  *
699  *      FIXME: What to do on a SIGHUP???
700  */
701 int thread_pool_init(int spawn_flag)
702 {
703         int             i, rcode;
704         CONF_SECTION    *pool_cf;
705         time_t          now;
706
707         DEBUG("Initializing the thread pool...");
708         now = time(NULL);
709
710         /*
711          *      We're not spawning new threads, don't do
712          *      anything.
713          */
714         if (!spawn_flag) return 0;
715
716         /*
717          *      After a SIGHUP, we don't over-write the previous values.
718          */
719         if (!pool_initialized) {
720                 /*
721                  *      Initialize the thread pool to some reasonable values.
722                  */
723                 memset(&thread_pool, 0, sizeof(THREAD_POOL));
724                 thread_pool.head = NULL;
725                 thread_pool.tail = NULL;
726                 thread_pool.total_threads = 0;
727                 thread_pool.max_thread_num = 1;
728                 thread_pool.cleanup_delay = 5;
729                 thread_pool.spawn_flag = spawn_flag;
730
731                 if ((pthread_mutex_init(&thread_pool.wait_mutex,NULL) != 0)) {
732                         radlog(L_ERR, "FATAL: Failed to initialize wait mutex: %s",
733                                strerror(errno));
734                         exit(1);
735                 }
736
737                 /*
738                  *      Create the hash table of child PID's
739                  */
740                 thread_pool.waiters = lrad_hash_table_create(pid_hash,
741                                                              pid_cmp,
742                                                              free);
743                 if (!thread_pool.waiters) {
744                         radlog(L_ERR, "FATAL: Failed to set up wait hash");
745                         exit(1);
746                 }
747         }
748
749         pool_cf = cf_section_find("thread");
750         if (!pool_cf) {
751                 radlog(L_ERR, "FATAL: Attempting to start in multi-threaded mode with no thread configuration in radiusd.conf");
752                 exit(1);
753         }
754
755         if (cf_section_parse(pool_cf, NULL, thread_config) < 0) {
756                 exit(1);
757         }
758
759         /*
760          *      The pool has already been initialized.  Don't spawn
761          *      new threads, and don't forget about forked children,
762          */
763         if (pool_initialized) {
764                 return 0;
765         }
766
767         /*
768          *      Initialize the queue of requests.
769          */
770         memset(&thread_pool.semaphore, 0, sizeof(thread_pool.semaphore));
771         rcode = sem_init(&thread_pool.semaphore, 0, SEMAPHORE_LOCKED);
772         if (rcode != 0) {
773                 radlog(L_ERR|L_CONS, "FATAL: Failed to initialize semaphore: %s",
774                        strerror(errno));
775                 exit(1);
776         }
777
778         rcode = pthread_mutex_init(&thread_pool.queue_mutex,NULL);
779         if (rcode != 0) {
780                 radlog(L_ERR, "FATAL: Failed to initialize queue mutex: %s",
781                        strerror(errno));
782                 exit(1);
783         }
784
785         /*
786          *      Allocate multiple fifos.
787          */
788         for (i = 0; i < RAD_LISTEN_MAX; i++) {
789                 thread_pool.fifo[i] = lrad_fifo_create(65536, NULL);
790                 if (!thread_pool.fifo[i]) {
791                         radlog(L_ERR, "FATAL: Failed to set up request fifo");
792                         exit(1);
793                 }
794         }
795
796 #ifdef HAVE_OPENSSL_CRYPTO_H
797         /*
798          *      If we're linking with OpenSSL too, then we need
799          *      to set up the mutexes and enable the thread callbacks.
800          */
801         if (!setup_ssl_mutexes()) {
802                 radlog(L_ERR, "FATAL: Failed to set up SSL mutexes");
803                 exit(1);
804         }
805 #endif
806
807
808         /*
809          *      Create a number of waiting threads.
810          *
811          *      If we fail while creating them, do something intelligent.
812          */
813         for (i = 0; i < thread_pool.start_threads; i++) {
814                 if (spawn_thread(now) == NULL) {
815                         return -1;
816                 }
817         }
818
819         DEBUG2("Thread pool initialized");
820         pool_initialized = TRUE;
821         return 0;
822 }
823
824
825 /*
826  *      Assign a new request to a free thread.
827  *
828  *      If there isn't a free thread, then try to create a new one,
829  *      up to the configured limits.
830  */
831 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
832 {
833         /*
834          *      We've been told not to spawn threads, so don't.
835          */
836         if (!thread_pool.spawn_flag) {
837                 radius_handle_request(request, fun);
838
839                 /*
840                  *      Requests that care about child process exit
841                  *      codes have already either called
842                  *      rad_waitpid(), or they've given up.
843                  */
844                 wait(NULL);
845                 return 1;
846         }
847
848         /*
849          *      Add the new request to the queue.
850          */
851         if (!request_enqueue(request, fun)) return 0;
852
853         /*
854          *      If the thread pool is busy handling requests, then
855          *      try to spawn another one.  We don't acquire the mutex
856          *      before reading active_threads, so our thread count is
857          *      just an estimate.  It's fine to go ahead and spawn an
858          *      extra thread in that case.
859          *      NOTE: the log message may be in error since active_threads
860          *      is an estimate, but it's only in error about the thread
861          *      count, not about the fact that we can't create a new one.
862          */
863         if (thread_pool.active_threads == thread_pool.total_threads) {
864                 if (spawn_thread(request->timestamp) == NULL) {
865                         radlog(L_INFO,
866                                "The maximum number of threads (%d) are active, cannot spawn new thread to handle request",
867                                thread_pool.max_threads);
868                         return 1;
869                 }
870         }
871
872         return 1;
873 }
874
875 /*
876  *      Check the min_spare_threads and max_spare_threads.
877  *
878  *      If there are too many or too few threads waiting, then we
879  *      either create some more, or delete some.
880  */
881 int thread_pool_clean(time_t now)
882 {
883         int spare;
884         int i, total;
885         THREAD_HANDLE *handle, *next;
886         int active_threads;
887         static time_t last_cleaned = 0;
888
889         /*
890          *      Loop over the thread pool deleting exited threads.
891          */
892         for (handle = thread_pool.head; handle; handle = next) {
893                 next = handle->next;
894
895                 /*
896                  *      Maybe we've asked the thread to exit, and it
897                  *      has agreed.
898                  */
899                 if (handle->status == THREAD_EXITED) {
900                         delete_thread(handle);
901                 }
902         }
903
904         /*
905          *      We don't need a mutex lock here, as we're reading
906          *      active_threads, and not modifying it.  We want a close
907          *      approximation of the number of active threads, and this
908          *      is good enough.
909          */
910         active_threads = thread_pool.active_threads;
911         spare = thread_pool.total_threads - active_threads;
912         if (debug_flag) {
913                 static int old_total = -1;
914                 static int old_active = -1;
915
916                 if ((old_total != thread_pool.total_threads) ||
917                                 (old_active != active_threads)) {
918                         DEBUG2("Threads: total/active/spare threads = %d/%d/%d",
919                                         thread_pool.total_threads, active_threads, spare);
920                         old_total = thread_pool.total_threads;
921                         old_active = active_threads;
922                 }
923         }
924
925         /*
926          *      If there are too few spare threads, create some more.
927          */
928         if (spare < thread_pool.min_spare_threads) {
929                 total = thread_pool.min_spare_threads - spare;
930
931                 DEBUG2("Threads: Spawning %d spares", total);
932                 /*
933                  *      Create a number of spare threads.
934                  */
935                 for (i = 0; i < total; i++) {
936                         handle = spawn_thread(now);
937                         if (handle == NULL) {
938                                 return -1;
939                         }
940                 }
941
942                 /*
943                  *      And exit, as there can't be too many spare threads.
944                  */
945                 return 0;
946         }
947
948         /*
949          *      Only delete spare threads if we haven't already done
950          *      so this second.
951          */
952         if (now == last_cleaned) {
953                 return 0;
954         }
955         last_cleaned = now;
956
957         /*
958          *      Only delete the spare threads if sufficient time has
959          *      passed since we last created one.  This helps to minimize
960          *      the amount of create/delete cycles.
961          */
962         if ((now - thread_pool.time_last_spawned) < thread_pool.cleanup_delay) {
963                 return 0;
964         }
965
966         /*
967          *      If there are too many spare threads, delete one.
968          *
969          *      Note that we only delete ONE at a time, instead of
970          *      wiping out many.  This allows the excess servers to
971          *      be slowly reaped, just in case the load spike comes again.
972          */
973         if (spare > thread_pool.max_spare_threads) {
974
975                 spare -= thread_pool.max_spare_threads;
976
977                 DEBUG2("Threads: deleting 1 spare out of %d spares", spare);
978
979                 /*
980                  *      Walk through the thread pool, deleting the
981                  *      first idle thread we come across.
982                  */
983                 for (handle = thread_pool.head; (handle != NULL) && (spare > 0) ; handle = next) {
984                         next = handle->next;
985
986                         /*
987                          *      If the thread is not handling a
988                          *      request, but still live, then tell it
989                          *      to exit.
990                          *
991                          *      It will eventually wake up, and realize
992                          *      it's been told to commit suicide.
993                          */
994                         if ((handle->request == NULL) &&
995                             (handle->status == THREAD_RUNNING)) {
996                                 handle->status = THREAD_CANCELLED;
997                                 /*
998                                  *      Post an extra semaphore, as a
999                                  *      signal to wake up, and exit.
1000                                  */
1001                                 sem_post(&thread_pool.semaphore);
1002                                 spare--;
1003                                 break;
1004                         }
1005                 }
1006         }
1007
1008         /*
1009          *      If the thread has handled too many requests, then make it
1010          *      exit.
1011          */
1012         if (thread_pool.max_requests_per_thread > 0) {
1013                 for (handle = thread_pool.head; handle; handle = next) {
1014                         next = handle->next;
1015
1016                         /*
1017                          *      Not handling a request, but otherwise
1018                          *      live, we can kill it.
1019                          */
1020                         if ((handle->request == NULL) &&
1021                             (handle->status == THREAD_RUNNING) &&
1022                             (handle->request_count > thread_pool.max_requests_per_thread)) {
1023                                 handle->status = THREAD_CANCELLED;
1024                                 sem_post(&thread_pool.semaphore);
1025                         }
1026                 }
1027         }
1028
1029         /*
1030          *      Otherwise everything's kosher.  There are not too few,
1031          *      or too many spare threads.  Exit happily.
1032          */
1033         return 0;
1034 }
1035
1036
1037 /*
1038  *      Thread wrapper for fork().
1039  */
1040 pid_t rad_fork(void)
1041 {
1042         pid_t child_pid;
1043
1044         if (!pool_initialized) return fork();
1045
1046         reap_children();        /* be nice to non-wait thingies */
1047
1048         if (lrad_hash_table_num_elements(thread_pool.waiters) >= 1024) {
1049                 return -1;
1050         }
1051
1052         /*
1053          *      Fork & save the PID for later reaping.
1054          */
1055         child_pid = fork();
1056         if (child_pid > 0) {
1057                 int rcode;
1058                 thread_fork_t *tf;
1059
1060                 tf = rad_malloc(sizeof(*tf));
1061                 memset(tf, 0, sizeof(*tf));
1062
1063                 tf->pid = child_pid;
1064
1065                 pthread_mutex_lock(&thread_pool.wait_mutex);
1066                 rcode = lrad_hash_table_insert(thread_pool.waiters, tf);
1067                 pthread_mutex_unlock(&thread_pool.wait_mutex);
1068
1069                 if (!rcode) {
1070                         radlog(L_ERR, "Failed to store PID, creating what will be a zombie process %d",
1071                                (int) child_pid);
1072                 }
1073         }
1074
1075         /*
1076          *      Return whatever we were told.
1077          */
1078         return child_pid;
1079 }
1080
1081
1082 /*
1083  *      Wait 10 seconds at most for a child to exit, then give up.
1084  */
1085 pid_t rad_waitpid(pid_t pid, int *status)
1086 {
1087         int i;
1088         thread_fork_t mytf, *tf;
1089
1090         if (!pool_initialized) return waitpid(pid, status, 0);
1091
1092         if (pid <= 0) return -1;
1093
1094         mytf.pid = pid;
1095
1096         pthread_mutex_lock(&thread_pool.wait_mutex);
1097         tf = lrad_hash_table_finddata(thread_pool.waiters, &mytf);
1098         pthread_mutex_unlock(&thread_pool.wait_mutex);
1099
1100         if (!tf) return -1;
1101
1102         for (i = 0; i < 100; i++) {
1103                 reap_children();
1104
1105                 if (tf->exited) {
1106                         *status = tf->status;
1107
1108                         pthread_mutex_lock(&thread_pool.wait_mutex);
1109                         lrad_hash_table_delete(thread_pool.waiters, &mytf);
1110                         pthread_mutex_unlock(&thread_pool.wait_mutex);
1111                         return pid;
1112                 }
1113                 usleep(100000); /* sleep for 1/10 of a second */
1114         }
1115
1116         /*
1117          *      10 seconds have passed, give up on the child.
1118          */
1119         pthread_mutex_lock(&thread_pool.wait_mutex);
1120         lrad_hash_table_delete(thread_pool.waiters, &mytf);
1121         pthread_mutex_unlock(&thread_pool.wait_mutex);
1122
1123         return 0;
1124 }
1125
1126 #else /* HAVE_PTHREAD_H */
1127 /*
1128  *      "thread" code when we don't have threads.
1129  */
1130 int thread_pool_init(int spawn_flag)
1131 {
1132         return 0;
1133 }
1134
1135 /*
1136  *      call "radrespond".
1137  */
1138 int thread_pool_addrequest(REQUEST *request, RAD_REQUEST_FUNP fun)
1139 {
1140         radius_handle_request(request, fun);
1141         return 1;
1142 }
1143
1144 #endif /* HAVE_PTHREAD_H */