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