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