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