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