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