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