* rework imap tokenizer, we no longer copy the stuff around, we keep a reference...
[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                 if (!citthread_equal(this_thread->tid, GC_thread->tid))
349                         citthread_kill(this_thread->tid, SIGHUP);
350
351                 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
352                 citthread_cond_signal(&this_thread->ThreadCond);
353                 citthread_cond_signal(&this_thread->SleepCond);
354                 this_thread->stop_ticker = time(NULL);
355                 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (0x%08lx).\n",
356                         this_thread->name, this_thread->tid);
357                 this_thread = this_thread->next;
358         }
359         end_critical_section(S_THREAD_LIST);
360 }
361
362
363 /*
364  * A function to wake up all sleeping threads
365  */
366 void CtdlThreadWakeAll(void)
367 {
368         CtdlThreadNode *this_thread;
369         
370         CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
371         
372         begin_critical_section(S_THREAD_LIST);
373         this_thread = CtdlThreadList;
374         while(this_thread)
375         {
376                 if (!this_thread->thread_func)
377                 {
378                         citthread_cond_signal(&this_thread->ThreadCond);
379                         citthread_cond_signal(&this_thread->SleepCond);
380                 }
381                 this_thread = this_thread->next;
382         }
383         end_critical_section(S_THREAD_LIST);
384 }
385
386
387 /*
388  * A function to return the number of threads running in the system
389  */
390 int CtdlThreadGetCount(void)
391 {
392         return  num_threads;
393 }
394
395 int CtdlThreadGetWorkers(void)
396 {
397         return  num_workers;
398 }
399
400 double CtdlThreadGetWorkerAvg(void)
401 {
402         double ret;
403         
404         begin_critical_section(S_THREAD_LIST);
405         ret =  CtdlThreadWorkerAvg;
406         end_critical_section(S_THREAD_LIST);
407         return ret;
408 }
409
410 double CtdlThreadGetLoadAvg(void)
411 {
412         double load_avg[3] = {0.0, 0.0, 0.0};
413
414         int ret = 0;
415         int smp_num_cpus;
416
417         /* Borrowed this straight from procps */
418         smp_num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
419         if(smp_num_cpus<1) smp_num_cpus=1; /* SPARC glibc is buggy */
420
421 #ifdef HAVE_GETLOADAVG
422         ret = getloadavg(load_avg, 3);
423 #endif
424         if (ret < 0)
425                 return 0;
426         return load_avg[0] / smp_num_cpus;
427 /*
428  * This old chunk of code return a value that indicated the load on citserver
429  * This value could easily reach 100 % even when citserver was doing very little and
430  * hence the machine has much more spare capacity.
431  * Because this value was used to determine if the machine was under heavy load conditions
432  * from other processes in the system then citserver could be strangled un-necesarily
433  * What we are actually trying to achieve is to strangle citserver if the machine is heavily loaded.
434  * So we have changed this.
435
436         begin_critical_section(S_THREAD_LIST);
437         ret =  CtdlThreadLoadAvg;
438         end_critical_section(S_THREAD_LIST);
439         return ret;
440 */
441 }
442
443
444
445
446 /*
447  * A function to rename a thread
448  * Returns a const char *
449  */
450 const char *CtdlThreadName(const char *name)
451 {
452         const char *old_name;
453         
454         if (!CT)
455         {
456                 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
457                 return NULL;
458         }
459         old_name = CT->name;
460         if (name)
461                 CT->name = name;
462         return (old_name);
463 }       
464
465
466 /*
467  * A function to force a thread to exit
468  */
469 void CtdlThreadCancel(CtdlThreadNode *thread)
470 {
471         CtdlThreadNode *this_thread;
472         
473         if (!thread)
474                 this_thread = CT;
475         else
476                 this_thread = thread;
477         if (!this_thread)
478         {
479                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
480                 CtdlThreadStopAll();
481                 return;
482         }
483         
484         if (!this_thread->thread_func)
485         {
486                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
487                 CtdlThreadStopAll();
488                 return;
489         }
490         
491         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
492         citthread_cancel(this_thread->tid);
493 }
494
495
496 /*
497  * A function for a thread to check if it has been asked to stop
498  */
499 int CtdlThreadCheckStop(void)
500 {
501         int state;
502         
503         if (!CT)
504         {
505                 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
506                 CtdlThreadStopAll();
507                 return -1;
508         }
509         
510         state = CT->state;
511
512         if (CT->signal)
513         {
514                 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
515                 if (CT->signal == SIGHUP)
516                         CT->state = CTDL_THREAD_STOP_REQ;
517                 CT->signal = 0;
518         }
519         if(state == CTDL_THREAD_STOP_REQ)
520         {
521                 CT->state = CTDL_THREAD_STOPPING;
522                 return -1;
523         }
524         else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
525         {
526                 return -1;
527         }
528         return 0;
529 }
530
531
532 /*
533  * A function to ask a thread to exit
534  * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
535  */
536 void CtdlThreadStop(CtdlThreadNode *thread)
537 {
538         CtdlThreadNode *this_thread;
539         
540         if (!thread)
541                 this_thread = CT;
542         else
543                 this_thread = thread;
544         if (!this_thread)
545                 return;
546         if (!(this_thread->thread_func))
547                 return;         // Don't stop garbage collector
548
549         if (!citthread_equal(this_thread->tid, GC_thread->tid))
550                 citthread_kill(this_thread->tid, SIGHUP);
551
552         ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
553         citthread_cond_signal(&this_thread->ThreadCond);
554         citthread_cond_signal(&this_thread->SleepCond);
555         this_thread->stop_ticker = time(NULL);
556 }
557
558 /*
559  * So we now have a sleep command that works with threads but it is in seconds
560  */
561 void CtdlThreadSleep(int secs)
562 {
563         struct timespec wake_time;
564         struct timeval time_now;
565         
566         
567         if (!CT)
568         {
569                 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
570                 return;
571         }
572         
573         memset (&wake_time, 0, sizeof(struct timespec));
574         gettimeofday(&time_now, NULL);
575         wake_time.tv_sec = time_now.tv_sec + secs;
576         wake_time.tv_nsec = time_now.tv_usec * 10;
577
578         ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
579         
580         citthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
581         citthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
582         citthread_mutex_unlock(&CT->ThreadMutex);
583         
584         ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
585 }
586
587
588 /*
589  * Routine to clean up our thread function on exit
590  */
591 static void ctdl_internal_thread_cleanup(void *arg)
592 {
593         /*
594          * In here we were called by the current thread because it is exiting
595          * NB. WE ARE THE CURRENT THREAD
596          */
597         if (CT)
598         {
599                 const char *name = CT->name;
600                 const pid_t tid = CT->tid;
601
602                 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (0x%08lx) exited.\n", name, tid);
603         }
604         else 
605         {
606                 CtdlLogPrintf(CTDL_NOTICE, "some ((unknown ? ? ?) Thread exited.\n");
607         }
608         
609         #ifdef HAVE_BACKTRACE
610 ///     eCrash_UnregisterThread();
611         #endif
612         
613         citthread_mutex_lock(&CT->ThreadMutex);
614         CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
615         citthread_mutex_unlock(&CT->ThreadMutex);
616 }
617
618 /*
619  * A quick function to show the load averages
620  */
621 void ctdl_thread_internal_calc_loadavg(void)
622 {
623         CtdlThreadNode *that_thread;
624         double load_avg, worker_avg;
625         int workers = 0;
626
627         that_thread = CtdlThreadList;
628         load_avg = 0;
629         worker_avg = 0;
630         while(that_thread)
631         {
632                 /* Update load averages */
633                 ctdl_thread_internal_update_avgs(that_thread);
634                 citthread_mutex_lock(&that_thread->ThreadMutex);
635                 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;
636                 that_thread->avg_sleeping /= 2;
637                 that_thread->avg_running /= 2;
638                 that_thread->avg_blocked /= 2;
639                 load_avg += that_thread->load_avg;
640                 if (that_thread->flags & CTDLTHREAD_WORKER)
641                 {
642                         worker_avg += that_thread->load_avg;
643                         workers++;
644                 }
645 #ifdef WITH_THREADLOG
646                 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
647                         that_thread->name,
648                         that_thread->tid,
649                         CtdlThreadStates[that_thread->state],
650                         that_thread->avg_sleeping,
651                         that_thread->avg_running,
652                         that_thread->avg_blocked,
653                         that_thread->load_avg);
654 #endif
655                 citthread_mutex_unlock(&that_thread->ThreadMutex);
656                 that_thread = that_thread->next;
657         }
658         CtdlThreadLoadAvg = load_avg/num_threads;
659         CtdlThreadWorkerAvg = worker_avg/workers;
660 #ifdef WITH_THREADLOG
661         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);
662 #endif
663 }
664
665
666 /*
667  * Garbage collection routine.
668  * Gets called by main() in a loop to clean up the thread list periodically.
669  */
670 void CtdlThreadGC (void)
671 {
672         CtdlThreadNode *this_thread, *that_thread;
673         int workers = 0, sys_workers;
674         int ret=0;
675
676         begin_critical_section(S_THREAD_LIST);
677         
678         /* Handle exiting of garbage collector thread */
679         if(num_threads == 1)
680                 CtdlThreadList->state = CTDL_THREAD_EXITED;
681         
682 #ifdef WITH_THREADLOG
683         CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
684 #endif
685         /*
686          * Woke up to do garbage collection
687          */
688         this_thread = CtdlThreadList;
689         while(this_thread)
690         {
691                 that_thread = this_thread;
692                 this_thread = this_thread->next;
693                 
694                 if ((that_thread->state == CTDL_THREAD_STOP_REQ || that_thread->state == CTDL_THREAD_STOPPING)
695                         && (!citthread_equal(that_thread->tid, citthread_self())))
696                                 CtdlLogPrintf(CTDL_DEBUG, "Waiting for thread %s (0x%08lx) to exit.\n", that_thread->name, that_thread->tid);
697                 else
698                 {
699                         /**
700                          * Catch the situation where a worker was asked to stop but couldn't and we are not
701                          * shutting down.
702                          */
703                         that_thread->stop_ticker = 0;
704                 }
705                 
706                 if (that_thread->stop_ticker + 5 == time(NULL))
707                 {
708                         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);
709                         if ((that_thread->flags & CTDLTHREAD_WORKER) == 0)
710                                 CtdlLogPrintf(CTDL_INFO, "Thread System: A non worker thread would have been canceled this may cause message loss.\n");
711 //                      that_thread->state = CTDL_THREAD_CANCELLED;
712                         that_thread->stop_ticker++;
713 //                      citthread_cancel(that_thread->tid);
714 //                      continue;
715                 }
716                 
717                 /* Do we need to clean up this thread? */
718                 if ((that_thread->state != CTDL_THREAD_EXITED) && (that_thread->state != CTDL_THREAD_CANCELLED))
719                 {
720                         if(that_thread->flags & CTDLTHREAD_WORKER)
721                                 workers++;      /* Sanity check on number of worker threads */
722                         continue;
723                 }
724                 
725                 if (citthread_equal(that_thread->tid, citthread_self()) && that_thread->thread_func)
726                 {       /* Sanity check */
727                         end_critical_section(S_THREAD_LIST);
728                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
729                         abort();
730                         return;
731                 }
732                 
733                 if (num_threads <= 0)
734                 {       /* Sanity check */
735                         end_critical_section(S_THREAD_LIST);
736                         CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
737                         abort();
738                         return;
739                 }
740
741                 if(that_thread->flags & CTDLTHREAD_WORKER)
742                         num_workers--;  /* This is a wroker thread so reduce the count. */
743                 num_threads--;
744                 /* If we are unlinking the list head then the next becomes the list head */
745                 if(that_thread->prev)
746                         that_thread->prev->next = that_thread->next;
747                 else
748                         CtdlThreadList = that_thread->next;
749                 if(that_thread->next)
750                         that_thread->next->prev = that_thread->prev;
751                 
752                 citthread_cond_signal(&that_thread->ThreadCond);
753                 citthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
754                 citthread_mutex_lock(&that_thread->ThreadMutex);        // Make sure it has done what its doing
755                 citthread_mutex_unlock(&that_thread->ThreadMutex);
756                 /*
757                  * Join on the thread to do clean up and prevent memory leaks
758                  * Also makes sure the thread has cleaned up after itself before we remove it from the list
759                  * We can join on the garbage collector thread the join should just return EDEADLCK
760                  */
761                 ret = citthread_join (that_thread->tid, NULL);
762                 if (ret == EDEADLK)
763                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection on own thread.\n");
764                 else if (ret == EINVAL)
765                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, that thread already joined on.\n");
766                 else if (ret == ESRCH)
767                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, no thread to join on.\n");
768                 else if (ret != 0)
769                         CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, citthread_join returned an unknown error(%d).\n", ret);
770                 /*
771                  * Now we own that thread entry
772                  */
773                 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (0x%08lx).\n",
774                         that_thread->name, that_thread->tid);
775                 citthread_mutex_destroy(&that_thread->ThreadMutex);
776                 citthread_cond_destroy(&that_thread->ThreadCond);
777                 citthread_mutex_destroy(&that_thread->SleepMutex);
778                 citthread_cond_destroy(&that_thread->SleepCond);
779                 citthread_attr_destroy(&that_thread->attr);
780                 free(that_thread);
781         }
782         sys_workers = num_workers;
783         end_critical_section(S_THREAD_LIST);
784         
785         /* Sanity check number of worker threads */
786         if (workers != sys_workers)
787         {
788                 CtdlLogPrintf(CTDL_EMERG,
789                         "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
790                         workers, sys_workers
791                         );
792                 abort();
793         }
794 }
795
796
797
798  
799 /*
800  * Runtime function for a Citadel Thread.
801  * This initialises the threads environment and then calls the user supplied thread function
802  * Note that this is the REAL thread function and wraps the users thread function.
803  */ 
804 static void *ctdl_internal_thread_func (void *arg)
805 {
806         CtdlThreadNode *this_thread;
807         void *ret = NULL;
808
809         /* lock and unlock the thread list.
810          * This causes this thread to wait until all its creation stuff has finished before it
811          * can continue its execution.
812          */
813         begin_critical_section(S_THREAD_LIST);
814         this_thread = (CtdlThreadNode *) arg;
815         gettimeofday(&this_thread->start_time, NULL);           /* Time this thread started */
816         
817         // Register the cleanup function to take care of when we exit.
818         citthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
819         // Get our thread data structure
820         CtdlThreadAllocTSD();
821         CT = this_thread;
822         this_thread->pid = getpid();
823         memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval));     /* Changed state so mark it. */
824         /* Only change to running state if we weren't asked to stop during the create cycle
825          * Other wise there is a window to allow this threads creation to continue to full grown and
826          * therby prevent a shutdown of the server.
827          */
828         if (!CtdlThreadCheckStop())
829         {
830                 citthread_mutex_lock(&this_thread->ThreadMutex);
831                 this_thread->state = CTDL_THREAD_RUNNING;
832                 citthread_mutex_unlock(&this_thread->ThreadMutex);
833         }
834         end_critical_section(S_THREAD_LIST);
835         
836         // Register for tracing
837         #ifdef HAVE_BACKTRACE
838 ///     eCrash_RegisterThread(this_thread->name, 0);
839         #endif
840         
841         // Tell the world we are here
842         CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (0x%08lx).\n",
843                 this_thread->name, this_thread->tid);
844         
845         /*
846          * run the thread to do the work but only if we haven't been asked to stop
847          */
848         if (!CtdlThreadCheckStop())
849                 ret = (this_thread->thread_func)(this_thread->user_args);
850         
851         /*
852          * Our thread is exiting either because it wanted to end or because the server is stopping
853          * We need to clean up
854          */
855         citthread_cleanup_pop(1);       // Execute our cleanup routine and remove it
856         
857         return(ret);
858 }
859
860
861
862
863 /*
864  * Function to initialise an empty thread structure
865  */
866 CtdlThreadNode *ctdl_internal_init_thread_struct(CtdlThreadNode *this_thread, long flags)
867 {
868         int ret = 0;
869         
870         // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
871         memset (this_thread, 0, sizeof(CtdlThreadNode));
872         
873         /* Create the mutex's early so we can use them */
874         citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
875         citthread_cond_init (&(this_thread->ThreadCond), NULL);
876         citthread_mutex_init (&(this_thread->SleepMutex), NULL);
877         citthread_cond_init (&(this_thread->SleepCond), NULL);
878         
879         this_thread->state = CTDL_THREAD_CREATE;
880         
881         if ((ret = citthread_attr_init(&this_thread->attr))) {
882                 citthread_mutex_unlock(&this_thread->ThreadMutex);
883                 citthread_mutex_destroy(&(this_thread->ThreadMutex));
884                 citthread_cond_destroy(&(this_thread->ThreadCond));
885                 citthread_mutex_destroy(&(this_thread->SleepMutex));
886                 citthread_cond_destroy(&(this_thread->SleepCond));
887                 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
888                 free(this_thread);
889                 return NULL;
890         }
891
892         /* Our per-thread stacks need to be bigger than the default size,
893          * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
894          * crashes on 64-bit Linux.
895          */
896         if (flags & CTDLTHREAD_BIGSTACK)
897         {
898 #ifdef WITH_THREADLOG
899                 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
900 #endif
901                 if ((ret = citthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
902                         citthread_mutex_unlock(&this_thread->ThreadMutex);
903                         citthread_mutex_destroy(&(this_thread->ThreadMutex));
904                         citthread_cond_destroy(&(this_thread->ThreadCond));
905                         citthread_mutex_destroy(&(this_thread->SleepMutex));
906                         citthread_cond_destroy(&(this_thread->SleepCond));
907                         citthread_attr_destroy(&this_thread->attr);
908                         CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_setstacksize: %s\n",
909                                 strerror(ret));
910                         free(this_thread);
911                         return NULL;
912                 }
913         }
914
915         /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
916          * load average for the system. If we don't do this then we create a mass of threads at the same time 
917          * because the creation didn't affect the load average.
918          */
919         this_thread->avg_blocked = 2;
920         
921         return (this_thread);
922 }
923
924
925
926  
927 /*
928  * Internal function to create a thread.
929  */ 
930 CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
931 {
932         int ret = 0;
933         CtdlThreadNode *this_thread;
934
935         if (num_threads >= 32767)
936         {
937                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
938                 return NULL;
939         }
940                 
941         this_thread = malloc(sizeof(CtdlThreadNode));
942         if (this_thread == NULL) {
943                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
944                 return NULL;
945         }
946         
947         /* Initialise the thread structure */
948         if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
949         {
950                 free(this_thread);
951                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
952                 return NULL;
953         }
954         /*
955          * If we got here we are going to create the thread so we must initilise the structure
956          * first because most implimentations of threading can't create it in a stopped state
957          * and it might want to do things with its structure that aren't initialised otherwise.
958          */
959         if(name)
960         {
961                 this_thread->name = name;
962         }
963         else
964         {
965                 this_thread->name = "Un-named Thread";
966         }
967         
968         this_thread->flags = flags;
969         this_thread->thread_func = thread_func;
970         this_thread->user_args = args;
971         
972         begin_critical_section(S_THREAD_LIST);
973         /*
974          * We pass this_thread into the thread as its args so that it can find out information
975          * about itself and it has a bit of storage space for itself, not to mention that the REAL
976          * thread function needs to finish off the setup of the structure
977          */
978         if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
979         {
980                 end_critical_section(S_THREAD_LIST);
981                 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
982                         strerror(ret));
983                 citthread_mutex_unlock(&this_thread->ThreadMutex);
984                 citthread_mutex_destroy(&(this_thread->ThreadMutex));
985                 citthread_cond_destroy(&(this_thread->ThreadCond));
986                 citthread_mutex_destroy(&(this_thread->SleepMutex));
987                 citthread_cond_destroy(&(this_thread->SleepCond));
988                 citthread_attr_destroy(&this_thread->attr);
989                 free(this_thread);
990                 return NULL;
991         }
992         
993         num_threads++;  // Increase the count of threads in the system.
994         if(this_thread->flags & CTDLTHREAD_WORKER)
995                 num_workers++;
996
997         this_thread->next = CtdlThreadList;
998         CtdlThreadList = this_thread;
999         if (this_thread->next)
1000                 this_thread->next->prev = this_thread;
1001         ctdl_thread_internal_calc_loadavg();
1002         
1003         end_critical_section(S_THREAD_LIST);
1004         
1005         return this_thread;
1006 }
1007
1008 /*
1009  * Wrapper function to create a thread
1010  * ensures the critical section and other protections are in place.
1011  * char *name = name to give to thread, if NULL, use generic name
1012  * int flags = flags to determine type of thread and standard facilities
1013  */
1014 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1015 {
1016         CtdlThreadNode *ret = NULL;
1017         
1018         ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1019         return ret;
1020 }
1021
1022
1023
1024 /*
1025  * Internal function to schedule a thread.
1026  * Must be called from within a S_THREAD_LIST critical section
1027  */ 
1028 CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
1029 {
1030         CtdlThreadNode *this_thread;
1031
1032         if (num_threads >= 32767)
1033         {
1034                 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1035                 return NULL;
1036         }
1037                 
1038         this_thread = malloc(sizeof(CtdlThreadNode));
1039         if (this_thread == NULL) {
1040                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1041                 return NULL;
1042         }
1043         /* Initialise the thread structure */
1044         if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
1045         {
1046                 free(this_thread);
1047                 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
1048                 return NULL;
1049         }
1050
1051         /*
1052          * If we got here we are going to create the thread so we must initilise the structure
1053          * first because most implimentations of threading can't create it in a stopped state
1054          * and it might want to do things with its structure that aren't initialised otherwise.
1055          */
1056         if(name)
1057         {
1058                 this_thread->name = name;
1059         }
1060         else
1061         {
1062                 this_thread->name = "Un-named Thread";
1063         }
1064         
1065         this_thread->flags = flags;
1066         this_thread->thread_func = thread_func;
1067         this_thread->user_args = args;
1068         
1069         /*
1070          * When to start this thread
1071          */
1072         this_thread->when = when;
1073
1074         begin_critical_section(S_SCHEDULE_LIST);
1075         this_thread->next = CtdlThreadSchedList;
1076         CtdlThreadSchedList = this_thread;
1077         if (this_thread->next)
1078                 this_thread->next->prev = this_thread;
1079         end_critical_section(S_SCHEDULE_LIST);
1080         
1081         return this_thread;
1082 }
1083
1084
1085
1086 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
1087 {
1088         int ret = 0;
1089         
1090         begin_critical_section(S_THREAD_LIST);
1091         /*
1092          * We pass this_thread into the thread as its args so that it can find out information
1093          * about itself and it has a bit of storage space for itself, not to mention that the REAL
1094          * thread function needs to finish off the setup of the structure
1095          */
1096         if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1097         {
1098                 end_critical_section(S_THREAD_LIST);
1099                 CtdlLogPrintf(CTDL_DEBUG, "Failed to start scheduled thread \"%s\": %s\n", this_thread->name, strerror(ret));
1100                 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1101                 citthread_cond_destroy(&(this_thread->ThreadCond));
1102                 citthread_mutex_destroy(&(this_thread->SleepMutex));
1103                 citthread_cond_destroy(&(this_thread->SleepCond));
1104                 citthread_attr_destroy(&this_thread->attr);
1105                 free(this_thread);
1106                 return NULL;
1107         }
1108         
1109         
1110         num_threads++;  // Increase the count of threads in the system.
1111         if(this_thread->flags & CTDLTHREAD_WORKER)
1112                 num_workers++;
1113
1114         this_thread->next = CtdlThreadList;
1115         CtdlThreadList = this_thread;
1116         if (this_thread->next)
1117                 this_thread->next->prev = this_thread;
1118         
1119         ctdl_thread_internal_calc_loadavg();
1120         end_critical_section(S_THREAD_LIST);
1121         
1122         
1123         return this_thread;
1124 }
1125
1126
1127
1128 void ctdl_thread_internal_check_scheduled(void)
1129 {
1130         CtdlThreadNode *this_thread, *that_thread;
1131         time_t now;
1132         
1133         /* Don't start scheduled threads if the system wants single user mode */
1134         if (CtdlWantSingleUser())
1135                 return;
1136         
1137         if (try_critical_section(S_SCHEDULE_LIST))
1138                 return; /* If this list is locked we wait till the next chance */
1139         
1140         now = time(NULL);
1141         
1142 #ifdef WITH_THREADLOG
1143         CtdlLogPrintf(CTDL_DEBUG, "Checking for scheduled threads to start.\n");
1144 #endif
1145
1146         this_thread = CtdlThreadSchedList;
1147         while(this_thread)
1148         {
1149                 that_thread = this_thread;
1150                 this_thread = this_thread->next;
1151                 
1152                 if (now > that_thread->when)
1153                 {
1154                         /* Unlink from schedule list */
1155                         if (that_thread->prev)
1156                                 that_thread->prev->next = that_thread->next;
1157                         else
1158                                 CtdlThreadSchedList = that_thread->next;
1159                         if (that_thread->next)
1160                                 that_thread->next->prev = that_thread->prev;
1161                                 
1162                         that_thread->next = that_thread->prev = NULL;
1163 #ifdef WITH_THREADLOG
1164                         CtdlLogPrintf(CTDL_DEBUG, "About to start scheduled thread \"%s\".\n", that_thread->name);
1165 #endif
1166                         if (CT->state > CTDL_THREAD_STOP_REQ)
1167                         {       /* Only start it if the system is not stopping */
1168                                 if (ctdl_thread_internal_start_scheduled (that_thread))
1169                                 {
1170 #ifdef WITH_THREADLOG
1171                                         CtdlLogPrintf(CTDL_INFO, "Thread system, Started a scheduled thread \"%s\" (0x%08lx).\n",
1172                                                 that_thread->name, that_thread->tid);
1173 #endif
1174                                 }
1175                         }
1176                 }
1177 #ifdef WITH_THREADLOG
1178                 else
1179                 {
1180                         CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" will start in %ld seconds.\n",
1181                                 that_thread->name, that_thread->when - time(NULL));
1182                 }
1183 #endif
1184         }
1185         end_critical_section(S_SCHEDULE_LIST);
1186 }
1187
1188
1189 /*
1190  * A warapper function for select so we can show a thread as blocked
1191  */
1192 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
1193 {
1194         int ret = 0;
1195         
1196         ctdl_thread_internal_change_state(CT, CTDL_THREAD_BLOCKED);
1197         if (!CtdlThreadCheckStop())
1198                 ret = select(n, readfds, writefds, exceptfds, timeout);
1199         /**
1200          * If the select returned <= 0 then it failed due to an error
1201          * or timeout so this thread could stop if asked to do so.
1202          * Anything else means it needs to continue unless the system is shutting down
1203          */
1204         if (ret > 0)
1205         {
1206                 /**
1207                  * The select says this thread needs to do something useful.
1208                  * This thread was in an idle state so it may have been asked to stop
1209                  * but if the system isn't shutting down this thread is no longer
1210                  * idle and select has given it a task to do so it must not stop
1211                  * In this condition we need to force it into the running state.
1212                  * CtdlThreadGC will clear its ticker for us.
1213                  *
1214                  * FIXME: there is still a small hole here. It is possible for the sequence of locking
1215                  * to allow the state to get changed to STOP_REQ just after this code if the other thread
1216                  * has decided to change the state before this lock, it there fore has to wait till the lock
1217                  * completes but it will continue to change the state. We need something a bit better here.
1218                  */
1219                 citthread_mutex_lock(&CT->ThreadMutex); /* To prevent race condition of a sleeping thread */
1220                 if (GC_thread->state > CTDL_THREAD_STOP_REQ && CT->state <= CTDL_THREAD_STOP_REQ)
1221                 {
1222                         CtdlLogPrintf(CTDL_DEBUG, "Thread %s (0x%08lx) refused stop request.\n", CT->name, CT->tid);
1223                         CT->state = CTDL_THREAD_RUNNING;
1224                 }
1225                 citthread_mutex_unlock(&CT->ThreadMutex);
1226         }
1227
1228         ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1229
1230         return ret;
1231 }
1232
1233
1234
1235 void *new_worker_thread(void *arg);
1236 extern void close_masters (void);
1237
1238
1239 void *simulation_worker (void*arg) {
1240         struct CitContext *this;
1241
1242         this = CreateNewContext();
1243         CtdlThreadSleep(1);
1244         this->kill_me = 1;
1245         this->state = CON_IDLE;
1246         dead_session_purge(1);
1247         begin_critical_section(S_SESSION_TABLE);
1248         stats_done++;
1249         end_critical_section(S_SESSION_TABLE);
1250         return NULL;
1251 }
1252
1253
1254 void *simulation_thread (void *arg)
1255 {
1256         long stats = statcount;
1257
1258         while(stats && !CtdlThreadCheckStop()) {
1259                 CtdlThreadCreate("Connection simulation worker", CTDLTHREAD_BIGSTACK, simulation_worker, NULL);
1260                 stats--;
1261         }
1262         CtdlThreadStopAll();
1263         return NULL;
1264 }
1265
1266 void go_threading(void)
1267 {
1268         int i;
1269         CtdlThreadNode *last_worker;
1270         struct timeval start, now, result;
1271         double last_duration;
1272
1273         /*
1274          * Initialise the thread system
1275          */
1276         ctdl_thread_internal_init();
1277
1278         /* Second call to module init functions now that threading is up */
1279         if (!statcount) {
1280                 initialise_modules(1);
1281                 CtdlThreadCreate("select_on_master", CTDLTHREAD_BIGSTACK, select_on_master, NULL);
1282         }
1283         else {
1284                 CtdlLogPrintf(CTDL_EMERG, "Running connection simulation stats\n");
1285                 gettimeofday(&start, NULL);
1286                 CtdlThreadCreate("Connection simulation master", CTDLTHREAD_BIGSTACK, simulation_thread, NULL);
1287         }
1288
1289
1290         /*
1291          * This thread is now used for garbage collection of other threads in the thread list
1292          */
1293         CtdlLogPrintf(CTDL_INFO, "Startup thread %d becoming garbage collector,\n", citthread_self());
1294
1295         /*
1296          * We do a lot of locking and unlocking of the thread list in here.
1297          * We do this so that we can repeatedly release time for other threads
1298          * that may be waiting on the thread list.
1299          * We are a low priority thread so we can afford to do this
1300          */
1301         
1302         while (CtdlThreadGetCount())
1303         {
1304                 if (CT->signal)
1305                         exit_signal = CT->signal;
1306                 if (exit_signal)
1307                 {
1308                         CtdlThreadStopAll();
1309                 }
1310                 check_sched_shutdown();
1311                 if (CT->state > CTDL_THREAD_STOP_REQ)
1312                 {
1313                         begin_critical_section(S_THREAD_LIST);
1314                         ctdl_thread_internal_calc_loadavg();
1315                         end_critical_section(S_THREAD_LIST);
1316                         
1317                         ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
1318                 }
1319                 
1320                 /* Reduce the size of the worker thread pool if necessary. */
1321                 if ((CtdlThreadGetWorkers() > config.c_min_workers + 1) && (CtdlThreadWorkerAvg < 20) && (CT->state > CTDL_THREAD_STOP_REQ))
1322                 {
1323                         /* Ask a worker thread to stop as we no longer need it */
1324                         begin_critical_section(S_THREAD_LIST);
1325                         last_worker = CtdlThreadList;
1326                         while (last_worker)
1327                         {
1328                                 citthread_mutex_lock(&last_worker->ThreadMutex);
1329                                 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1330                                 {
1331                                         citthread_mutex_unlock(&last_worker->ThreadMutex);
1332                                         break;
1333                                 }
1334                                 citthread_mutex_unlock(&last_worker->ThreadMutex);
1335                                 last_worker = last_worker->next;
1336                         }
1337                         end_critical_section(S_THREAD_LIST);
1338                         if (last_worker)
1339                         {
1340 #ifdef WITH_THREADLOG
1341                                 CtdlLogPrintf(CTDL_DEBUG, "Thread system, stopping excess worker thread \"%s\" (0x%08lx).\n",
1342                                         last_worker->name,
1343                                         last_worker->tid
1344                                         );
1345 #endif
1346                                 CtdlThreadStop(last_worker);
1347                         }
1348                 }
1349         
1350                 /*
1351                  * If all our workers are working hard, start some more to help out
1352                  * with things
1353                  */
1354                 /* FIXME: come up with a better way to dynamically alter the number of threads
1355                  * based on the system load
1356                  */
1357                 if (!statcount) {
1358                 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkerAvg() > 60)) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1359                 {
1360                         /* Only start new threads if we are not going to overload the machine */
1361                         /* Temporarily set to 10 should be enough to make sure we don't stranglew the server
1362                          * at least until we make this a config option */
1363                         if (CtdlThreadGetLoadAvg() < ((double)10.00)) {
1364                                 for (i=0; i<5 ; i++) {
1365                                         CtdlThreadCreate("Worker Thread",
1366                                                 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1367                                                 worker_thread,
1368                                                 NULL
1369                                                 );
1370                                 }
1371                         }
1372                         else
1373                                 CtdlLogPrintf (CTDL_WARNING, "Server strangled due to machine load average too high.\n");
1374                 }
1375                 }
1376
1377                 CtdlThreadGC();
1378
1379                 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1380                 {
1381                         CtdlThreadGC();
1382                 }
1383                 
1384 #ifdef THREADS_USESIGNALS
1385                 if (CtdlThreadGetCount() && CT->state > CTDL_THREAD_STOP_REQ)
1386 #else
1387                 if (CtdlThreadGetCount())
1388 #endif
1389                         CtdlThreadSleep(1);
1390         }
1391         /*
1392          * If the above loop exits we must be shutting down since we obviously have no threads
1393          */
1394         ctdl_thread_internal_cleanup();
1395
1396         if (statcount) {
1397                 gettimeofday(&now, NULL);
1398                 timersub(&now, &start, &result);
1399                 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1400                 CtdlLogPrintf(CTDL_EMERG, "Simulated %ld connections in %f seconds\n", stats_done, last_duration);
1401         }
1402 }
1403
1404
1405
1406