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