* make configure check for getloadavg()
[citadel.git] / citadel / threads.c
1 /*
2  * $Id$
3  *
4  * Citadel "system dependent" stuff.
5  * See COPYING for copyright information.
6  *
7  * Here's where we have the Citadel thread implimentation
8  *
9  */
10
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <sys/types.h>
15 #include <errno.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18 #include <fcntl.h>
19 #include <signal.h>
20
21 #if TIME_WITH_SYS_TIME
22 # include <sys/time.h>
23 # include <time.h>
24 #else
25 # if HAVE_SYS_TIME_H
26 #  include <sys/time.h>
27 # else
28 #  include <time.h>
29 # endif
30 #endif
31
32 #include <libcitadel.h>
33
34 #include "threads.h"
35 #include "ctdl_module.h"
36 #include "modules_init.h"
37 #include "housekeeping.h"
38 #include "config.h"
39 #include "citserver.h"
40 #include "sysdep_decls.h"
41 #include "context.h"
42
43 /*
44  * define this to use the new worker_thread method of handling connections
45  */
46 //#define NEW_WORKER
47
48 /*
49  * New thread interface.
50  * To create a thread you must call one of the create thread functions.
51  * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
52  * struct CtdlThreadNode *node = NULL;
53  * pass in &node
54  * If the thread is created *node will point to the thread control structure for the created thread.
55  * If the thread creation fails *node remains NULL
56  * Do not free the memory pointed to by *node, it doesn't belong to you.
57  * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
58  * remove the need for the calls to eCrashRegisterThread and friends
59  */
60
61 static int num_threads = 0;                     /* Current number of threads */
62 static int num_workers = 0;                     /* Current number of worker threads */
63 long statcount = 0;             /* are we doing a stats check? */
64 static long stats_done = 0;
65
66 CtdlThreadNode *CtdlThreadList = NULL;
67 CtdlThreadNode *CtdlThreadSchedList = NULL;
68
69 static CtdlThreadNode *GC_thread = NULL;
70 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
71 double CtdlThreadLoadAvg = 0;
72 double CtdlThreadWorkerAvg = 0;
73 citthread_key_t ThreadKey;
74
75 citthread_mutex_t Critters[MAX_SEMAPHORES];     /* Things needing locking */
76
77
78
79 void InitialiseSemaphores(void)
80 {
81         int i;
82
83         /* Set up a bunch of semaphores to be used for critical sections */
84         for (i=0; i<MAX_SEMAPHORES; ++i) {
85                 citthread_mutex_init(&Critters[i], NULL);
86         }
87 }
88
89
90
91
92 /*
93  * Obtain a semaphore lock to begin a critical section.
94  * but only if no one else has one
95  */
96 int try_critical_section(int which_one)
97 {
98         /* For all types of critical sections except those listed here,
99          * ensure nobody ever tries to do a critical section within a
100          * transaction; this could lead to deadlock.
101          */
102         if (    (which_one != S_FLOORCACHE)
103 #ifdef DEBUG_MEMORY_LEAKS
104                 && (which_one != S_DEBUGMEMLEAKS)
105 #endif
106                 && (which_one != S_RPLIST)
107         ) {
108                 cdb_check_handles();
109         }
110         return (citthread_mutex_trylock(&Critters[which_one]));
111 }
112
113
114 /*
115  * Obtain a semaphore lock to begin a critical section.
116  */
117 void begin_critical_section(int which_one)
118 {
119         /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
120
121         /* For all types of critical sections except those listed here,
122          * ensure nobody ever tries to do a critical section within a
123          * transaction; this could lead to deadlock.
124          */
125         if (    (which_one != S_FLOORCACHE)
126 #ifdef DEBUG_MEMORY_LEAKS
127                 && (which_one != S_DEBUGMEMLEAKS)
128 #endif
129                 && (which_one != S_RPLIST)
130         ) {
131                 cdb_check_handles();
132         }
133         citthread_mutex_lock(&Critters[which_one]);
134 }
135
136 /*
137  * Release a semaphore lock to end a critical section.
138  */
139 void end_critical_section(int which_one)
140 {
141         citthread_mutex_unlock(&Critters[which_one]);
142 }
143
144
145 /*
146  * A function to destroy the TSD
147  */
148 static void ctdl_thread_internal_dest_tsd(void *arg)
149 {
150         if (arg != NULL) {
151                 check_handles(arg);
152                 free(arg);
153         }
154 }
155
156
157 /*
158  * A function to initialise the thread TSD
159  */
160 void ctdl_thread_internal_init_tsd(void)
161 {
162         int ret;
163         
164         if ((ret = citthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
165                 CtdlLogPrintf(CTDL_EMERG, "citthread_key_create: %s\n", strerror(ret));
166                 exit(CTDLEXIT_DB);
167         }
168 }
169
170 /*
171  * Ensure that we have a key for thread-specific data. 
172  *
173  * This should be called immediately after startup by any thread 
174  * 
175  */
176 void CtdlThreadAllocTSD(void)
177 {
178         ThreadTSD *tsd;
179
180         if (citthread_getspecific(ThreadKey) != NULL)
181                 return;
182
183         tsd = malloc(sizeof(ThreadTSD));
184
185         tsd->tid = NULL;
186
187         memset(tsd->cursors, 0, sizeof tsd->cursors);
188         tsd->self = NULL;
189         
190         citthread_setspecific(ThreadKey, tsd);
191 }
192
193
194 void ctdl_thread_internal_free_tsd(void)
195 {
196         ctdl_thread_internal_dest_tsd(citthread_getspecific(ThreadKey));
197         citthread_setspecific(ThreadKey, NULL);
198 }
199
200
201 void ctdl_thread_internal_cleanup(void)
202 {
203         int i;
204         CtdlThreadNode *this_thread, *that_thread;
205         
206         for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
207         {
208                 free (CtdlThreadStates[i]);
209         }
210         
211         /* Clean up the scheduled thread list */
212         this_thread = CtdlThreadSchedList;
213         while (this_thread)
214         {
215                 that_thread = this_thread;
216                 this_thread = this_thread->next;
217                 citthread_mutex_destroy(&that_thread->ThreadMutex);
218                 citthread_cond_destroy(&that_thread->ThreadCond);
219                 citthread_mutex_destroy(&that_thread->SleepMutex);
220                 citthread_cond_destroy(&that_thread->SleepCond);
221                 citthread_attr_destroy(&that_thread->attr);
222                 free(that_thread);
223         }
224         ctdl_thread_internal_free_tsd();
225 }
226
227 void ctdl_thread_internal_init(void)
228 {
229         CtdlThreadNode *this_thread;
230         int ret = 0;
231         
232         CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
233         CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
234         CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
235         CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
236         CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
237         CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
238         CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
239         CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
240         CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
241         CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
242         
243         /* Get ourself a thread entry */
244         this_thread = malloc(sizeof(CtdlThreadNode));
245         if (this_thread == NULL) {
246                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
247                 return;
248         }
249         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
250         memset (this_thread, 0, sizeof(CtdlThreadNode));
251         
252         citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
253         citthread_cond_init (&(this_thread->ThreadCond), NULL);
254         citthread_mutex_init (&(this_thread->SleepMutex), NULL);
255         citthread_cond_init (&(this_thread->SleepCond), NULL);
256         
257         /* We are garbage collector so create us as running */
258         this_thread->state = CTDL_THREAD_RUNNING;
259         
260         if ((ret = citthread_attr_init(&this_thread->attr))) {
261                 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
262                 free(this_thread);
263                 return;
264         }
265
266         this_thread->name = "Garbage Collection Thread";
267         
268         this_thread->tid = citthread_self();
269         GC_thread = this_thread;
270         CT = this_thread;
271         
272         num_threads++;  // Increase the count of threads in the system.
273
274         this_thread->next = CtdlThreadList;
275         CtdlThreadList = this_thread;
276         if (this_thread->next)
277                 this_thread->next->prev = this_thread;
278         /* Set up start times */
279         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
280         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
281 }
282
283
284 /*
285  * A function to update a threads load averages
286  */
287  void ctdl_thread_internal_update_avgs(CtdlThreadNode *this_thread)
288  {
289         struct timeval now, result;
290         double last_duration;
291
292         gettimeofday(&now, NULL);
293         timersub(&now, &(this_thread->last_state_change), &result);
294         /* I don't think these mutex's are needed here */
295         citthread_mutex_lock(&this_thread->ThreadMutex);
296         // result now has a timeval for the time we spent in the last state since we last updated
297         last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
298         if (this_thread->state == CTDL_THREAD_SLEEPING)
299                 this_thread->avg_sleeping += last_duration;
300         if (this_thread->state == CTDL_THREAD_RUNNING)
301                 this_thread->avg_running += last_duration;
302         if (this_thread->state == CTDL_THREAD_BLOCKED)
303                 this_thread->avg_blocked += last_duration;
304         memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
305         citthread_mutex_unlock(&this_thread->ThreadMutex);
306 }
307
308 /*
309  * A function to chenge the state of a thread
310  */
311 void ctdl_thread_internal_change_state (CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
312 {
313         /*
314          * Wether we change state or not we need update the load values
315          */
316         ctdl_thread_internal_update_avgs(this_thread);
317         /* This mutex not needed here? */
318         citthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
319         if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
320                 this_thread->state = new_state;
321         if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
322                 this_thread->state = new_state;
323         if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
324                 this_thread->state = new_state;
325         citthread_mutex_unlock(&this_thread->ThreadMutex);
326 }
327
328
329 /*
330  * A function to tell all threads to exit
331  */
332 void CtdlThreadStopAll(void)
333 {
334         /* First run any registered shutdown hooks.  This probably doesn't belong here. */
335         PerformSessionHooks(EVT_SHUTDOWN);
336
337         //FIXME: The signalling of the condition should not be in the critical_section
338         // We need to build a list of threads we are going to signal and then signal them afterwards
339         
340         CtdlThreadNode *this_thread;
341         
342         begin_critical_section(S_THREAD_LIST);
343         this_thread = CtdlThreadList;
344         // Ask the GC thread to stop first so everything knows we are shutting down.
345         GC_thread->state = CTDL_THREAD_STOP_REQ;
346         while(this_thread)
347         {
348 #ifdef THREADS_USESIGNALS
349                 if (!citthread_equal(this_thread->tid, GC_thread->tid))
350                         citthread_kill(this_thread->tid, SIGHUP);
351 #endif
352                 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
353                 citthread_cond_signal(&this_thread->ThreadCond);
354                 citthread_cond_signal(&this_thread->SleepCond);
355                 this_thread->stop_ticker = time(NULL);
356                 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (0x%08lx).\n",
357                         this_thread->name, this_thread->tid);
358                 this_thread = this_thread->next;
359         }
360         end_critical_section(S_THREAD_LIST);
361 }
362
363
364 /*
365  * A function to wake up all sleeping threads
366  */
367 void CtdlThreadWakeAll(void)
368 {
369         CtdlThreadNode *this_thread;
370         
371         CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
372         
373         begin_critical_section(S_THREAD_LIST);
374         this_thread = CtdlThreadList;
375         while(this_thread)
376         {
377                 if (!this_thread->thread_func)
378                 {
379                         citthread_cond_signal(&this_thread->ThreadCond);
380                         citthread_cond_signal(&this_thread->SleepCond);
381                 }
382                 this_thread = this_thread->next;
383         }
384         end_critical_section(S_THREAD_LIST);
385 }
386
387
388 /*
389  * A function to return the number of threads running in the system
390  */
391 int CtdlThreadGetCount(void)
392 {
393         return  num_threads;
394 }
395
396 int CtdlThreadGetWorkers(void)
397 {
398         return  num_workers;
399 }
400
401 double CtdlThreadGetWorkerAvg(void)
402 {
403         double ret;
404         
405         begin_critical_section(S_THREAD_LIST);
406         ret =  CtdlThreadWorkerAvg;
407         end_critical_section(S_THREAD_LIST);
408         return ret;
409 }
410
411 double CtdlThreadGetLoadAvg(void)
412 {
413         double load_avg[3] = {0.0, 0.0, 0.0};
414
415         int ret = 0;
416         int smp_num_cpus;
417
418         /* Borrowed this straight from procps */
419         smp_num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
420         if(smp_num_cpus<1) smp_num_cpus=1; /* SPARC glibc is buggy */
421
422 #ifdef HAVE_GETLOADAVG
423         ret = getloadavg(load_avg, 3);
424 #endif
425         if (ret < 0)
426                 return 0;
427         return load_avg[0] / smp_num_cpus;
428 /*
429  * This old chunk of code return a value that indicated the load on citserver
430  * This value could easily reach 100 % even when citserver was doing very little and
431  * hence the machine has much more spare capacity.
432  * Because this value was used to determine if the machine was under heavy load conditions
433  * from other processes in the system then citserver could be strangled un-necesarily
434  * What we are actually trying to achieve is to strangle citserver if the machine is heavily loaded.
435  * So we have changed this.
436
437         begin_critical_section(S_THREAD_LIST);
438         ret =  CtdlThreadLoadAvg;
439         end_critical_section(S_THREAD_LIST);
440         return ret;
441 */
442 }
443
444
445
446
447 /*
448  * A function to rename a thread
449  * Returns a const char *
450  */
451 const char *CtdlThreadName(const char *name)
452 {
453         const char *old_name;
454         
455         if (!CT)
456         {
457                 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
458                 return NULL;
459         }
460         old_name = CT->name;
461         if (name)
462                 CT->name = name;
463         return (old_name);
464 }       
465
466
467 /*
468  * A function to force a thread to exit
469  */
470 void CtdlThreadCancel(CtdlThreadNode *thread)
471 {
472         CtdlThreadNode *this_thread;
473         
474         if (!thread)
475                 this_thread = CT;
476         else
477                 this_thread = thread;
478         if (!this_thread)
479         {
480                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
481                 CtdlThreadStopAll();
482                 return;
483         }
484         
485         if (!this_thread->thread_func)
486         {
487                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
488                 CtdlThreadStopAll();
489                 return;
490         }
491         
492         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
493         citthread_cancel(this_thread->tid);
494 }
495
496
497 /*
498  * A function for a thread to check if it has been asked to stop
499  */
500 int CtdlThreadCheckStop(void)
501 {
502         int state;
503         
504         if (!CT)
505         {
506                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
507                 CtdlThreadStopAll();
508                 return -1;
509         }
510         
511         state = CT->state;
512
513 #ifdef THREADS_USESIGNALS
514         if (CT->signal)
515         {
516                 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
517                 CT->signal = 0;
518         }
519 #endif
520         if(state == CTDL_THREAD_STOP_REQ)
521         {
522                 CT->state = CTDL_THREAD_STOPPING;
523                 return -1;
524         }
525         else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
526         {
527                 return -1;
528         }
529         return 0;
530 }
531
532
533 /*
534  * A function to ask a thread to exit
535  * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
536  */
537 void CtdlThreadStop(CtdlThreadNode *thread)
538 {
539         CtdlThreadNode *this_thread;
540         
541         if (!thread)
542                 this_thread = CT;
543         else
544                 this_thread = thread;
545         if (!this_thread)
546                 return;
547         if (!(this_thread->thread_func))
548                 return;         // Don't stop garbage collector
549 #ifdef THREADS_USESIGNALS
550         if (!citthread_equal(this_thread->tid, GC_thread->tid))
551                 citthread_kill(this_thread->tid, SIGHUP);
552 #endif
553         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
554         citthread_cond_signal(&this_thread->ThreadCond);
555         citthread_cond_signal(&this_thread->SleepCond);
556         this_thread->stop_ticker = time(NULL);
557 }
558
559 /*
560  * So we now have a sleep command that works with threads but it is in seconds
561  */
562 void CtdlThreadSleep(int secs)
563 {
564         struct timespec wake_time;
565         struct timeval time_now;
566         
567         
568         if (!CT)
569         {
570                 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
571                 return;
572         }
573         
574         memset (&wake_time, 0, sizeof(struct timespec));
575         gettimeofday(&time_now, NULL);
576         wake_time.tv_sec = time_now.tv_sec + secs;
577         wake_time.tv_nsec = time_now.tv_usec * 10;
578
579         ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
580         
581         citthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
582         citthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
583         citthread_mutex_unlock(&CT->ThreadMutex);
584         
585         ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
586 }
587
588
589 /*
590  * Routine to clean up our thread function on exit
591  */
592 static void ctdl_internal_thread_cleanup(void *arg)
593 {
594         /*
595          * In here we were called by the current thread because it is exiting
596          * NB. WE ARE THE CURRENT THREAD
597          */
598         CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (0x%08lx) exited.\n", CT->name, CT->tid);
599         
600         #ifdef HAVE_BACKTRACE
601         eCrash_UnregisterThread();
602         #endif
603         
604         citthread_mutex_lock(&CT->ThreadMutex);
605         CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
606         citthread_mutex_unlock(&CT->ThreadMutex);
607 }
608
609 /*
610  * A quick function to show the load averages
611  */
612 void ctdl_thread_internal_calc_loadavg(void)
613 {
614         CtdlThreadNode *that_thread;
615         double load_avg, worker_avg;
616         int workers = 0;
617
618         that_thread = CtdlThreadList;
619         load_avg = 0;
620         worker_avg = 0;
621         while(that_thread)
622         {
623                 /* Update load averages */
624                 ctdl_thread_internal_update_avgs(that_thread);
625                 citthread_mutex_lock(&that_thread->ThreadMutex);
626                 that_thread->load_avg = (that_thread->avg_sleeping + that_thread->avg_running) / (that_thread->avg_sleeping + that_thread->avg_running + that_thread->avg_blocked) * 100;
627                 that_thread->avg_sleeping /= 2;
628                 that_thread->avg_running /= 2;
629                 that_thread->avg_blocked /= 2;
630                 load_avg += that_thread->load_avg;
631                 if (that_thread->flags & CTDLTHREAD_WORKER)
632                 {
633                         worker_avg += that_thread->load_avg;
634                         workers++;
635                 }
636 #ifdef WITH_THREADLOG
637                 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
638                         that_thread->name,
639                         that_thread->tid,
640                         CtdlThreadStates[that_thread->state],
641                         that_thread->avg_sleeping,
642                         that_thread->avg_running,
643                         that_thread->avg_blocked,
644                         that_thread->load_avg);
645 #endif
646                 citthread_mutex_unlock(&that_thread->ThreadMutex);
647                 that_thread = that_thread->next;
648         }
649         CtdlThreadLoadAvg = load_avg/num_threads;
650         CtdlThreadWorkerAvg = worker_avg/workers;
651 #ifdef WITH_THREADLOG
652         CtdlLogPrintf(CTDL_INFO, "System load average %.2f, workers averag %.2f, threads %d, workers %d, sessions %d\n", CtdlThreadGetLoadAvg(), CtdlThreadWorkerAvg, num_threads, num_workers, num_sessions);
653 #endif
654 }
655
656
657 /*
658  * Garbage collection routine.
659  * Gets called by main() in a loop to clean up the thread list periodically.
660  */
661 void CtdlThreadGC (void)
662 {
663         CtdlThreadNode *this_thread, *that_thread;
664         int workers = 0, sys_workers;
665         int ret=0;
666         
667         begin_critical_section(S_THREAD_LIST);
668         
669         /* Handle exiting of garbage collector thread */
670         if(num_threads == 1)
671                 CtdlThreadList->state = CTDL_THREAD_EXITED;
672         
673 #ifdef WITH_THREADLOG
674         CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
675 #endif
676         /*
677          * Woke up to do garbage collection
678          */
679         this_thread = CtdlThreadList;
680         while(this_thread)
681         {
682                 that_thread = this_thread;
683                 this_thread = this_thread->next;
684                 
685                 if ((that_thread->state == CTDL_THREAD_STOP_REQ || that_thread->state == CTDL_THREAD_STOPPING)
686                         && (!citthread_equal(that_thread->tid, citthread_self())))
687                                 CtdlLogPrintf(CTDL_DEBUG, "Waiting for thread %s (0x%08lx) to exit.\n", that_thread->name, that_thread->tid);
688                 else
689                 {
690                         /**
691                          * Catch the situation where a worker was asked to stop but couldn't and we are not
692                          * shutting down.
693                          */
694                         that_thread->stop_ticker = 0;
695                 }
696                 
697                 if (that_thread->stop_ticker + 5 == time(NULL))
698                 {
699                         CtdlLogPrintf(CTDL_DEBUG, "Thread System: The thread \"%s\" (0x%08lx) failed to self terminate within 5 ticks. It would be cancelled now.\n", that_thread->name, that_thread->tid);
700                         if ((that_thread->flags & CTDLTHREAD_WORKER) == 0)
701                                 CtdlLogPrintf(CTDL_INFO, "Thread System: A non worker thread would have been canceled this may cause message loss.\n");
702 //                      that_thread->state = CTDL_THREAD_CANCELLED;
703                         that_thread->stop_ticker++;
704 //                      citthread_cancel(that_thread->tid);
705 //                      continue;
706                 }
707                 
708                 /* Do we need to clean up this thread? */
709                 if ((that_thread->state != CTDL_THREAD_EXITED) && (that_thread->state != CTDL_THREAD_CANCELLED))
710                 {
711                         if(that_thread->flags & CTDLTHREAD_WORKER)
712                                 workers++;      /* Sanity check on number of worker threads */
713                         continue;
714                 }
715                 
716                 if (citthread_equal(that_thread->tid, citthread_self()) && that_thread->thread_func)
717                 {       /* Sanity check */
718                         end_critical_section(S_THREAD_LIST);
719                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
720                         abort();
721                         return;
722                 }
723                 
724                 if (num_threads <= 0)
725                 {       /* Sanity check */
726                         end_critical_section(S_THREAD_LIST);
727                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
728                         abort();
729                         return;
730                 }
731
732                 if(that_thread->flags & CTDLTHREAD_WORKER)
733                         num_workers--;  /* This is a wroker thread so reduce the count. */
734                 num_threads--;
735                 /* If we are unlinking the list head then the next becomes the list head */
736                 if(that_thread->prev)
737                         that_thread->prev->next = that_thread->next;
738                 else
739                         CtdlThreadList = that_thread->next;
740                 if(that_thread->next)
741                         that_thread->next->prev = that_thread->prev;
742                 
743                 citthread_cond_signal(&that_thread->ThreadCond);
744                 citthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
745                 citthread_mutex_lock(&that_thread->ThreadMutex);        // Make sure it has done what its doing
746                 citthread_mutex_unlock(&that_thread->ThreadMutex);
747                 /*
748                  * Join on the thread to do clean up and prevent memory leaks
749                  * Also makes sure the thread has cleaned up after itself before we remove it from the list
750                  * We can join on the garbage collector thread the join should just return EDEADLCK
751                  */
752                 ret = citthread_join (that_thread->tid, NULL);
753                 if (ret == EDEADLK)
754                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection on own thread.\n");
755                 else if (ret == EINVAL)
756                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, that thread already joined on.\n");
757                 else if (ret == ESRCH)
758                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, no thread to join on.\n");
759                 else if (ret != 0)
760                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, citthread_join returned an unknown error(%d).\n", ret);
761                 /*
762                  * Now we own that thread entry
763                  */
764                 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (0x%08lx).\n",
765                         that_thread->name, that_thread->tid);
766                 citthread_mutex_destroy(&that_thread->ThreadMutex);
767                 citthread_cond_destroy(&that_thread->ThreadCond);
768                 citthread_mutex_destroy(&that_thread->SleepMutex);
769                 citthread_cond_destroy(&that_thread->SleepCond);
770                 citthread_attr_destroy(&that_thread->attr);
771                 free(that_thread);
772         }
773         sys_workers = num_workers;
774         end_critical_section(S_THREAD_LIST);
775         
776         /* Sanity check number of worker threads */
777         if (workers != sys_workers)
778         {
779                 CtdlLogPrintf(CTDL_EMERG,
780                         "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
781                         workers, sys_workers
782                         );
783                 abort();
784         }
785 }
786
787
788
789  
790 /*
791  * Runtime function for a Citadel Thread.
792  * This initialises the threads environment and then calls the user supplied thread function
793  * Note that this is the REAL thread function and wraps the users thread function.
794  */ 
795 static void *ctdl_internal_thread_func (void *arg)
796 {
797         CtdlThreadNode *this_thread;
798         void *ret = NULL;
799
800         /* lock and unlock the thread list.
801          * This causes this thread to wait until all its creation stuff has finished before it
802          * can continue its execution.
803          */
804         begin_critical_section(S_THREAD_LIST);
805         this_thread = (CtdlThreadNode *) arg;
806         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
807         
808         // Register the cleanup function to take care of when we exit.
809         citthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
810         // Get our thread data structure
811         CtdlThreadAllocTSD();
812         CT = this_thread;
813         this_thread->pid = getpid();
814         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
815         /* Only change to running state if we weren't asked to stop during the create cycle
816          * Other wise there is a window to allow this threads creation to continue to full grown and
817          * therby prevent a shutdown of the server.
818          */
819         if (!CtdlThreadCheckStop())
820         {
821                 citthread_mutex_lock(&this_thread->ThreadMutex);
822                 this_thread->state = CTDL_THREAD_RUNNING;
823                 citthread_mutex_unlock(&this_thread->ThreadMutex);
824         }
825         end_critical_section(S_THREAD_LIST);
826         
827         // Register for tracing
828         #ifdef HAVE_BACKTRACE
829         eCrash_RegisterThread(this_thread->name, 0);
830         #endif
831         
832         // Tell the world we are here
833         CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (0x%08lx).\n",
834                 this_thread->name, this_thread->tid);
835         
836         /*
837          * run the thread to do the work but only if we haven't been asked to stop
838          */
839         if (!CtdlThreadCheckStop())
840                 ret = (this_thread->thread_func)(this_thread->user_args);
841         
842         /*
843          * Our thread is exiting either because it wanted to end or because the server is stopping
844          * We need to clean up
845          */
846         citthread_cleanup_pop(1);       // Execute our cleanup routine and remove it
847         
848         return(ret);
849 }
850
851
852
853
854 /*
855  * Function to initialise an empty thread structure
856  */
857 CtdlThreadNode *ctdl_internal_init_thread_struct(CtdlThreadNode *this_thread, long flags)
858 {
859         int ret = 0;
860         
861         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
862         memset (this_thread, 0, sizeof(CtdlThreadNode));
863         
864         /* Create the mutex's early so we can use them */
865         citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
866         citthread_cond_init (&(this_thread->ThreadCond), NULL);
867         citthread_mutex_init (&(this_thread->SleepMutex), NULL);
868         citthread_cond_init (&(this_thread->SleepCond), NULL);
869         
870         this_thread->state = CTDL_THREAD_CREATE;
871         
872         if ((ret = citthread_attr_init(&this_thread->attr))) {
873                 citthread_mutex_unlock(&this_thread->ThreadMutex);
874                 citthread_mutex_destroy(&(this_thread->ThreadMutex));
875                 citthread_cond_destroy(&(this_thread->ThreadCond));
876                 citthread_mutex_destroy(&(this_thread->SleepMutex));
877                 citthread_cond_destroy(&(this_thread->SleepCond));
878                 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
879                 free(this_thread);
880                 return NULL;
881         }
882
883         /* Our per-thread stacks need to be bigger than the default size,
884          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
885          * crashes on 64-bit Linux.
886          */
887         if (flags & CTDLTHREAD_BIGSTACK)
888         {
889 #ifdef WITH_THREADLOG
890                 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
891 #endif
892                 if ((ret = citthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
893                         citthread_mutex_unlock(&this_thread->ThreadMutex);
894                         citthread_mutex_destroy(&(this_thread->ThreadMutex));
895                         citthread_cond_destroy(&(this_thread->ThreadCond));
896                         citthread_mutex_destroy(&(this_thread->SleepMutex));
897                         citthread_cond_destroy(&(this_thread->SleepCond));
898                         citthread_attr_destroy(&this_thread->attr);
899                         CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_setstacksize: %s\n",
900                                 strerror(ret));
901                         free(this_thread);
902                         return NULL;
903                 }
904         }
905
906         /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
907          * load average for the system. If we don't do this then we create a mass of threads at the same time 
908          * because the creation didn't affect the load average.
909          */
910         this_thread->avg_blocked = 2;
911         
912         return (this_thread);
913 }
914
915
916
917  
918 /*
919  * Internal function to create a thread.
920  */ 
921 CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
922 {
923         int ret = 0;
924         CtdlThreadNode *this_thread;
925
926         if (num_threads >= 32767)
927         {
928                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
929                 return NULL;
930         }
931                 
932         this_thread = malloc(sizeof(CtdlThreadNode));
933         if (this_thread == NULL) {
934                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
935                 return NULL;
936         }
937         
938         /* Initialise the thread structure */
939         if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
940         {
941                 free(this_thread);
942                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
943                 return NULL;
944         }
945         /*
946          * If we got here we are going to create the thread so we must initilise the structure
947          * first because most implimentations of threading can't create it in a stopped state
948          * and it might want to do things with its structure that aren't initialised otherwise.
949          */
950         if(name)
951         {
952                 this_thread->name = name;
953         }
954         else
955         {
956                 this_thread->name = "Un-named Thread";
957         }
958         
959         this_thread->flags = flags;
960         this_thread->thread_func = thread_func;
961         this_thread->user_args = args;
962         
963         begin_critical_section(S_THREAD_LIST);
964         /*
965          * We pass this_thread into the thread as its args so that it can find out information
966          * about itself and it has a bit of storage space for itself, not to mention that the REAL
967          * thread function needs to finish off the setup of the structure
968          */
969         if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
970         {
971                 end_critical_section(S_THREAD_LIST);
972                 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
973                         strerror(ret));
974                 citthread_mutex_unlock(&this_thread->ThreadMutex);
975                 citthread_mutex_destroy(&(this_thread->ThreadMutex));
976                 citthread_cond_destroy(&(this_thread->ThreadCond));
977                 citthread_mutex_destroy(&(this_thread->SleepMutex));
978                 citthread_cond_destroy(&(this_thread->SleepCond));
979                 citthread_attr_destroy(&this_thread->attr);
980                 free(this_thread);
981                 return NULL;
982         }
983         
984         num_threads++;  // Increase the count of threads in the system.
985         if(this_thread->flags & CTDLTHREAD_WORKER)
986                 num_workers++;
987
988         this_thread->next = CtdlThreadList;
989         CtdlThreadList = this_thread;
990         if (this_thread->next)
991                 this_thread->next->prev = this_thread;
992         ctdl_thread_internal_calc_loadavg();
993         
994         end_critical_section(S_THREAD_LIST);
995         
996         return this_thread;
997 }
998
999 /*
1000  * Wrapper function to create a thread
1001  * ensures the critical section and other protections are in place.
1002  * char *name = name to give to thread, if NULL, use generic name
1003  * int flags = flags to determine type of thread and standard facilities
1004  */
1005 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1006 {
1007         CtdlThreadNode *ret = NULL;
1008         
1009         ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1010         return ret;
1011 }
1012
1013
1014
1015 /*
1016  * Internal function to schedule a thread.
1017  * Must be called from within a S_THREAD_LIST critical section
1018  */ 
1019 CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
1020 {
1021         CtdlThreadNode *this_thread;
1022
1023         if (num_threads >= 32767)
1024         {
1025                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1026                 return NULL;
1027         }
1028                 
1029         this_thread = malloc(sizeof(CtdlThreadNode));
1030         if (this_thread == NULL) {
1031                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1032                 return NULL;
1033         }
1034         /* Initialise the thread structure */
1035         if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
1036         {
1037                 free(this_thread);
1038                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
1039                 return NULL;
1040         }
1041
1042         /*
1043          * If we got here we are going to create the thread so we must initilise the structure
1044          * first because most implimentations of threading can't create it in a stopped state
1045          * and it might want to do things with its structure that aren't initialised otherwise.
1046          */
1047         if(name)
1048         {
1049                 this_thread->name = name;
1050         }
1051         else
1052         {
1053                 this_thread->name = "Un-named Thread";
1054         }
1055         
1056         this_thread->flags = flags;
1057         this_thread->thread_func = thread_func;
1058         this_thread->user_args = args;
1059         
1060         /*
1061          * When to start this thread
1062          */
1063         this_thread->when = when;
1064
1065         begin_critical_section(S_SCHEDULE_LIST);
1066         this_thread->next = CtdlThreadSchedList;
1067         CtdlThreadSchedList = this_thread;
1068         if (this_thread->next)
1069                 this_thread->next->prev = this_thread;
1070         end_critical_section(S_SCHEDULE_LIST);
1071         
1072         return this_thread;
1073 }
1074
1075
1076
1077 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
1078 {
1079         int ret = 0;
1080         
1081         begin_critical_section(S_THREAD_LIST);
1082         /*
1083          * We pass this_thread into the thread as its args so that it can find out information
1084          * about itself and it has a bit of storage space for itself, not to mention that the REAL
1085          * thread function needs to finish off the setup of the structure
1086          */
1087         if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1088         {
1089                 end_critical_section(S_THREAD_LIST);
1090                 CtdlLogPrintf(CTDL_DEBUG, "Failed to start scheduled thread \"%s\": %s\n", this_thread->name, strerror(ret));
1091                 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1092                 citthread_cond_destroy(&(this_thread->ThreadCond));
1093                 citthread_mutex_destroy(&(this_thread->SleepMutex));
1094                 citthread_cond_destroy(&(this_thread->SleepCond));
1095                 citthread_attr_destroy(&this_thread->attr);
1096                 free(this_thread);
1097                 return NULL;
1098         }
1099         
1100         
1101         num_threads++;  // Increase the count of threads in the system.
1102         if(this_thread->flags & CTDLTHREAD_WORKER)
1103                 num_workers++;
1104
1105         this_thread->next = CtdlThreadList;
1106         CtdlThreadList = this_thread;
1107         if (this_thread->next)
1108                 this_thread->next->prev = this_thread;
1109         
1110         ctdl_thread_internal_calc_loadavg();
1111         end_critical_section(S_THREAD_LIST);
1112         
1113         
1114         return this_thread;
1115 }
1116
1117
1118
1119 void ctdl_thread_internal_check_scheduled(void)
1120 {
1121         CtdlThreadNode *this_thread, *that_thread;
1122         time_t now;
1123         
1124         /* Don't start scheduled threads if the system wants single user mode */
1125         if (CtdlWantSingleUser())
1126                 return;
1127         
1128         if (try_critical_section(S_SCHEDULE_LIST))
1129                 return; /* If this list is locked we wait till the next chance */
1130         
1131         now = time(NULL);
1132         
1133 #ifdef WITH_THREADLOG
1134         CtdlLogPrintf(CTDL_DEBUG, "Checking for scheduled threads to start.\n");
1135 #endif
1136
1137         this_thread = CtdlThreadSchedList;
1138         while(this_thread)
1139         {
1140                 that_thread = this_thread;
1141                 this_thread = this_thread->next;
1142                 
1143                 if (now > that_thread->when)
1144                 {
1145                         /* Unlink from schedule list */
1146                         if (that_thread->prev)
1147                                 that_thread->prev->next = that_thread->next;
1148                         else
1149                                 CtdlThreadSchedList = that_thread->next;
1150                         if (that_thread->next)
1151                                 that_thread->next->prev = that_thread->prev;
1152                                 
1153                         that_thread->next = that_thread->prev = NULL;
1154 #ifdef WITH_THREADLOG
1155                         CtdlLogPrintf(CTDL_DEBUG, "About to start scheduled thread \"%s\".\n", that_thread->name);
1156 #endif
1157                         if (CT->state > CTDL_THREAD_STOP_REQ)
1158                         {       /* Only start it if the system is not stopping */
1159                                 if (ctdl_thread_internal_start_scheduled (that_thread))
1160                                 {
1161 #ifdef WITH_THREADLOG
1162                                         CtdlLogPrintf(CTDL_INFO, "Thread system, Started a scheduled thread \"%s\" (0x%08lx).\n",
1163                                                 that_thread->name, that_thread->tid);
1164 #endif
1165                                 }
1166                         }
1167                 }
1168 #ifdef WITH_THREADLOG
1169                 else
1170                 {
1171                         CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" will start in %ld seconds.\n",
1172                                 that_thread->name, that_thread->when - time(NULL));
1173                 }
1174 #endif
1175         }
1176         end_critical_section(S_SCHEDULE_LIST);
1177 }
1178
1179
1180 /*
1181  * A warapper function for select so we can show a thread as blocked
1182  */
1183 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
1184 {
1185         int ret = 0;
1186         
1187         ctdl_thread_internal_change_state(CT, CTDL_THREAD_BLOCKED);
1188         if (!CtdlThreadCheckStop())
1189                 ret = select(n, readfds, writefds, exceptfds, timeout);
1190         /**
1191          * If the select returned <= 0 then it failed due to an error
1192          * or timeout so this thread could stop if asked to do so.
1193          * Anything else means it needs to continue unless the system is shutting down
1194          */
1195         if (ret > 0)
1196         {
1197                 /**
1198                  * The select says this thread needs to do something useful.
1199                  * This thread was in an idle state so it may have been asked to stop
1200                  * but if the system isn't shutting down this thread is no longer
1201                  * idle and select has given it a task to do so it must not stop
1202                  * In this condition we need to force it into the running state.
1203                  * CtdlThreadGC will clear its ticker for us.
1204                  *
1205                  * FIXME: there is still a small hole here. It is possible for the sequence of locking
1206                  * to allow the state to get changed to STOP_REQ just after this code if the other thread
1207                  * has decided to change the state before this lock, it there fore has to wait till the lock
1208                  * completes but it will continue to change the state. We need something a bit better here.
1209                  */
1210                 citthread_mutex_lock(&CT->ThreadMutex); /* To prevent race condition of a sleeping thread */
1211                 if (GC_thread->state > CTDL_THREAD_STOP_REQ && CT->state <= CTDL_THREAD_STOP_REQ)
1212                 {
1213                         CtdlLogPrintf(CTDL_DEBUG, "Thread %s (0x%08lx) refused stop request.\n", CT->name, CT->tid);
1214                         CT->state = CTDL_THREAD_RUNNING;
1215                 }
1216                 citthread_mutex_unlock(&CT->ThreadMutex);
1217         }
1218
1219         ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1220
1221         return ret;
1222 }
1223
1224
1225
1226 void *new_worker_thread(void *arg);
1227 extern void close_masters (void);
1228
1229
1230 void *simulation_worker (void*arg) {
1231         struct CitContext *this;
1232
1233         this = CreateNewContext();
1234         CtdlThreadSleep(1);
1235         this->kill_me = 1;
1236         this->state = CON_IDLE;
1237         dead_session_purge(1);
1238         begin_critical_section(S_SESSION_TABLE);
1239         stats_done++;
1240         end_critical_section(S_SESSION_TABLE);
1241         return NULL;
1242 }
1243
1244
1245 void *simulation_thread (void *arg)
1246 {
1247         long stats = statcount;
1248
1249         while(stats && !CtdlThreadCheckStop()) {
1250                 CtdlThreadCreate("Connection simulation worker", CTDLTHREAD_BIGSTACK, simulation_worker, NULL);
1251                 stats--;
1252         }
1253         CtdlThreadStopAll();
1254         return NULL;
1255 }
1256
1257 void go_threading(void)
1258 {
1259         int i;
1260         CtdlThreadNode *last_worker;
1261         struct timeval start, now, result;
1262         double last_duration;
1263
1264         /*
1265          * Initialise the thread system
1266          */
1267         ctdl_thread_internal_init();
1268
1269         /* Second call to module init functions now that threading is up */
1270         if (!statcount)
1271                 initialise_modules(1);
1272         else {
1273                 CtdlLogPrintf(CTDL_EMERG, "Running connection simulation stats\n");
1274                 gettimeofday(&start, NULL);
1275                 CtdlThreadCreate("Connection simulation master", CTDLTHREAD_BIGSTACK, simulation_thread, NULL);
1276         }
1277
1278
1279         /*
1280          * This thread is now used for garbage collection of other threads in the thread list
1281          */
1282         CtdlLogPrintf(CTDL_INFO, "Startup thread %d becoming garbage collector,\n", citthread_self());
1283
1284         /*
1285          * We do a lot of locking and unlocking of the thread list in here.
1286          * We do this so that we can repeatedly release time for other threads
1287          * that may be waiting on the thread list.
1288          * We are a low priority thread so we can afford to do this
1289          */
1290         
1291         while (CtdlThreadGetCount())
1292         {
1293                 if (CT->signal)
1294                         exit_signal = CT->signal;
1295                 if (exit_signal)
1296                 {
1297                         CtdlThreadStopAll();
1298                 }
1299                 check_sched_shutdown();
1300                 if (CT->state > CTDL_THREAD_STOP_REQ)
1301                 {
1302                         begin_critical_section(S_THREAD_LIST);
1303                         ctdl_thread_internal_calc_loadavg();
1304                         end_critical_section(S_THREAD_LIST);
1305                         
1306                         ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
1307                 }
1308                 
1309                 /* Reduce the size of the worker thread pool if necessary. */
1310                 if ((CtdlThreadGetWorkers() > config.c_min_workers + 1) && (CtdlThreadWorkerAvg < 20) && (CT->state > CTDL_THREAD_STOP_REQ))
1311                 {
1312                         /* Ask a worker thread to stop as we no longer need it */
1313                         begin_critical_section(S_THREAD_LIST);
1314                         last_worker = CtdlThreadList;
1315                         while (last_worker)
1316                         {
1317                                 citthread_mutex_lock(&last_worker->ThreadMutex);
1318                                 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1319                                 {
1320                                         citthread_mutex_unlock(&last_worker->ThreadMutex);
1321                                         break;
1322                                 }
1323                                 citthread_mutex_unlock(&last_worker->ThreadMutex);
1324                                 last_worker = last_worker->next;
1325                         }
1326                         end_critical_section(S_THREAD_LIST);
1327                         if (last_worker)
1328                         {
1329 #ifdef WITH_THREADLOG
1330                                 CtdlLogPrintf(CTDL_DEBUG, "Thread system, stopping excess worker thread \"%s\" (0x%08lx).\n",
1331                                         last_worker->name,
1332                                         last_worker->tid
1333                                         );
1334 #endif
1335                                 CtdlThreadStop(last_worker);
1336                         }
1337                 }
1338         
1339                 /*
1340                  * If all our workers are working hard, start some more to help out
1341                  * with things
1342                  */
1343                 /* FIXME: come up with a better way to dynamically alter the number of threads
1344                  * based on the system load
1345                  */
1346                 if (!statcount) {
1347                 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkerAvg() > 60)) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1348                 {
1349                         /* Only start new threads if we are not going to overload the machine */
1350                         /* Temporarily set to 10 should be enough to make sure we don't stranglew the server
1351                          * at least until we make this a config option */
1352                         if (CtdlThreadGetLoadAvg() < ((double)10.00)) {
1353                                 for (i=0; i<5 ; i++) {
1354                                         CtdlThreadCreate("Worker Thread",
1355                                                 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1356                                                 worker_thread,
1357                                                 NULL
1358                                                 );
1359                                 }
1360                         }
1361                         else
1362                                 CtdlLogPrintf (CTDL_WARNING, "Server strangled due to machine load average too high.\n");
1363                 }
1364                 }
1365
1366                 CtdlThreadGC();
1367
1368                 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1369                 {
1370                         CtdlThreadGC();
1371                 }
1372                 
1373 #ifdef THREADS_USESIGNALS
1374                 if (CtdlThreadGetCount() && CT->state > CTDL_THREAD_STOP_REQ)
1375 #else
1376                 if (CtdlThreadGetCount())
1377 #endif
1378                         CtdlThreadSleep(1);
1379         }
1380         /*
1381          * If the above loop exits we must be shutting down since we obviously have no threads
1382          */
1383         ctdl_thread_internal_cleanup();
1384
1385         if (statcount) {
1386                 gettimeofday(&now, NULL);
1387                 timersub(&now, &start, &result);
1388                 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1389                 CtdlLogPrintf(CTDL_EMERG, "Simulated %ld connections in %f seconds\n", stats_done, last_duration);
1390         }
1391 }
1392
1393
1394
1395