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