2 * $Id: sysdep.c 5882 2007-12-13 19:46:05Z davew $
4 * Citadel "system dependent" stuff.
5 * See copyright.txt for copyright information.
7 * Here's where we have the Citadel thread implimentation
12 #include <sys/socket.h>
16 #if TIME_WITH_SYS_TIME
17 # include <sys/time.h>
21 # include <sys/time.h>
28 #include "ctdl_module.h"
29 #include "modules_init.h"
30 #include "housekeeping.h"
32 #include "citserver.h"
33 #include "sysdep_decls.h"
36 * define this to use the new worker_thread method of handling connections
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;
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
53 static int num_threads = 0; /* Current number of threads */
54 static int num_workers = 0; /* Current number of worker threads */
56 CtdlThreadNode *CtdlThreadList = NULL;
57 CtdlThreadNode *CtdlThreadSchedList = NULL;
60 * Condition variable and Mutex for thread garbage collection
62 /*static pthread_mutex_t thread_gc_mutex = PTHREAD_MUTEX_INITIALIZER;
63 static pthread_cond_t thread_gc_cond = PTHREAD_COND_INITIALIZER;
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;
71 pthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
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;
80 void InitialiseSemaphores(void)
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);
94 * Obtain a semaphore lock to begin a critical section.
95 * but only if no one else has one
97 int try_critical_section(int which_one)
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.
103 if ( (which_one != S_FLOORCACHE)
104 #ifdef DEBUG_MEMORY_LEAKS
105 && (which_one != S_DEBUGMEMLEAKS)
107 && (which_one != S_RPLIST)
111 return (pthread_mutex_trylock(&Critters[which_one]));
116 * Obtain a semaphore lock to begin a critical section.
118 void begin_critical_section(int which_one)
120 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
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.
126 if ( (which_one != S_FLOORCACHE)
127 #ifdef DEBUG_MEMORY_LEAKS
128 && (which_one != S_DEBUGMEMLEAKS)
130 && (which_one != S_RPLIST)
134 pthread_mutex_lock(&Critters[which_one]);
138 * Release a semaphore lock to end a critical section.
140 void end_critical_section(int which_one)
142 pthread_mutex_unlock(&Critters[which_one]);
147 * A function to destroy the TSD
149 static void ctdl_thread_internal_dest_tsd(void *arg)
159 * A function to initialise the thread TSD
161 void ctdl_thread_internal_init_tsd(void)
165 if ((ret = pthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
166 lprintf(CTDL_EMERG, "pthread_key_create: %s\n",
173 * Ensure that we have a key for thread-specific data.
175 * This should be called immediately after startup by any thread
178 void CtdlThreadAllocTSD(void)
182 if (pthread_getspecific(ThreadKey) != NULL)
185 tsd = malloc(sizeof(ThreadTSD));
189 memset(tsd->cursors, 0, sizeof tsd->cursors);
192 pthread_setspecific(ThreadKey, tsd);
196 void ctdl_thread_internal_free_tsd(void)
198 ctdl_thread_internal_dest_tsd(pthread_getspecific(ThreadKey));
199 pthread_setspecific(ThreadKey, NULL);
203 void ctdl_thread_internal_cleanup(void)
206 CtdlThreadNode *this_thread, *that_thread;
208 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
210 free (CtdlThreadStates[i]);
213 /* Clean up the scheduled thread list */
214 this_thread = CtdlThreadSchedList;
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);
226 ctdl_thread_internal_free_tsd();
229 void ctdl_thread_internal_init(void)
231 CtdlThreadNode *this_thread;
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");
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");
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));
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);
260 /* We are garbage collector so create us as running */
261 this_thread->state = CTDL_THREAD_RUNNING;
263 if ((ret = pthread_attr_init(&this_thread->attr))) {
264 CtdlLogPrintf(CTDL_EMERG, "Thread system, pthread_attr_init: %s\n", strerror(ret));
269 this_thread->name = "Garbage Collection Thread";
271 this_thread->tid = GC_thread;
274 num_threads++; // Increase the count of threads in the system.
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. */
287 * A function to update a threads load averages
289 void ctdl_thread_internal_update_avgs(CtdlThreadNode *this_thread)
291 struct timeval now, result;
292 double last_duration;
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);
311 * A function to chenge the state of a thread
313 void ctdl_thread_internal_change_state (CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
316 * Wether we change state or not we need update the load values
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);
332 * A function to tell all threads to exit
334 void CtdlThreadStopAll(void)
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
339 CtdlThreadNode *this_thread;
341 begin_critical_section(S_THREAD_LIST);
342 this_thread = CtdlThreadList;
345 #ifdef THREADS_USESIGNALS
346 pthread_kill(this_thread->tid, SIGHUP);
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;
354 end_critical_section(S_THREAD_LIST);
359 * A function to wake up all sleeping threads
361 void CtdlThreadWakeAll(void)
363 CtdlThreadNode *this_thread;
365 CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
367 begin_critical_section(S_THREAD_LIST);
368 this_thread = CtdlThreadList;
371 if (!this_thread->thread_func)
373 pthread_cond_signal(&this_thread->ThreadCond);
374 pthread_cond_signal(&this_thread->SleepCond);
376 this_thread = this_thread->next;
378 end_critical_section(S_THREAD_LIST);
383 * A function to return the number of threads running in the system
385 int CtdlThreadGetCount(void)
390 int CtdlThreadGetWorkers(void)
395 double CtdlThreadGetWorkerAvg(void)
399 begin_critical_section(S_THREAD_LIST);
400 ret = CtdlThreadWorkerAvg;
401 end_critical_section(S_THREAD_LIST);
405 double CtdlThreadGetLoadAvg(void)
409 begin_critical_section(S_THREAD_LIST);
410 ret = CtdlThreadLoadAvg;
411 end_critical_section(S_THREAD_LIST);
419 * A function to rename a thread
420 * Returns a const char *
422 const char *CtdlThreadName(const char *name)
424 const char *old_name;
428 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
439 * A function to force a thread to exit
441 void CtdlThreadCancel(CtdlThreadNode *thread)
443 CtdlThreadNode *this_thread;
448 this_thread = thread;
451 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
456 if (!this_thread->thread_func)
458 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
463 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
464 pthread_cancel(this_thread->tid);
470 * A function for a thread to check if it has been asked to stop
472 int CtdlThreadCheckStop(void)
478 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
485 #ifdef THREADS_USERSIGNALS
487 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
489 if(state == CTDL_THREAD_STOP_REQ)
491 CT->state = CTDL_THREAD_STOPPING;
494 else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
503 * A function to ask a thread to exit
504 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
506 void CtdlThreadStop(CtdlThreadNode *thread)
508 CtdlThreadNode *this_thread;
513 this_thread = thread;
516 if (!(this_thread->thread_func))
517 return; // Don't stop garbage collector
518 #ifdef THREADS_USESIGNALS
519 pthread_kill(this_thread->tid, SIGHUP);
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);
527 * So we now have a sleep command that works with threads but it is in seconds
529 void CtdlThreadSleep(int secs)
531 struct timespec wake_time;
532 struct timeval time_now;
537 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
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;
546 ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
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);
552 ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
557 * Routine to clean up our thread function on exit
559 static void ctdl_internal_thread_cleanup(void *arg)
562 * In here we were called by the current thread because it is exiting
563 * NB. WE ARE THE CURRENT THREAD
565 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (%ld) exited.\n", CT->name, CT->tid);
567 #ifdef HAVE_BACKTRACE
568 eCrash_UnregisterThread();
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);
577 * A quick function to show the load averages
579 void ctdl_thread_internal_calc_loadavg(void)
581 CtdlThreadNode *that_thread;
582 double load_avg, worker_avg;
585 that_thread = CtdlThreadList;
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)
600 worker_avg += that_thread->load_avg;
603 #ifdef WITH_THREADLOG
604 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
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);
613 pthread_mutex_unlock(&that_thread->ThreadMutex);
614 that_thread = that_thread->next;
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);
625 * Garbage collection routine.
626 * Gets called by main() in a loop to clean up the thread list periodically.
628 void CtdlThreadGC (void)
630 CtdlThreadNode *this_thread, *that_thread;
631 int workers = 0, sys_workers;
634 begin_critical_section(S_THREAD_LIST);
636 /* Handle exiting of garbage collector thread */
638 CtdlThreadList->state = CTDL_THREAD_EXITED;
640 #ifdef WITH_THREADLOG
641 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
644 * Woke up to do garbage collection
646 this_thread = CtdlThreadList;
649 that_thread = this_thread;
650 this_thread = this_thread->next;
652 /* Do we need to clean up this thread? */
653 if (that_thread->state != CTDL_THREAD_EXITED)
655 if(that_thread->flags & CTDLTHREAD_WORKER)
656 workers++; /* Sanity check on number of worker threads */
660 if (pthread_equal(that_thread->tid, pthread_self()) && that_thread->thread_func)
662 end_critical_section(S_THREAD_LIST);
663 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
668 if (num_threads <= 0)
670 end_critical_section(S_THREAD_LIST);
671 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
676 if(that_thread->flags & CTDLTHREAD_WORKER)
677 num_workers--; /* This is a wroker thread so reduce the count. */
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;
683 CtdlThreadList = that_thread->next;
684 if(that_thread->next)
685 that_thread->next->prev = that_thread->prev;
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);
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
696 ret = pthread_join (that_thread->tid, NULL);
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");
704 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, pthread_join returned an unknown error.\n");
706 * Now we own that thread entry
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);
716 sys_workers = num_workers;
717 end_critical_section(S_THREAD_LIST);
719 /* Sanity check number of worker threads */
720 if (workers != sys_workers)
722 CtdlLogPrintf(CTDL_EMERG,
723 "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
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.
738 static void *ctdl_internal_thread_func (void *arg)
740 CtdlThreadNode *this_thread;
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.
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);
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();
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.
763 pthread_mutex_unlock(&this_thread->ThreadMutex);
765 if (!CtdlThreadCheckStop())
767 pthread_mutex_lock(&this_thread->ThreadMutex);
768 this_thread->state = CTDL_THREAD_RUNNING;
769 pthread_mutex_unlock(&this_thread->ThreadMutex);
771 end_critical_section(S_THREAD_LIST);
773 // Register for tracing
774 #ifdef HAVE_BACKTRACE
775 eCrash_RegisterThread(this_thread->name, 0);
778 // Tell the world we are here
779 CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (%ld). \n", this_thread->name, this_thread->tid);
784 * run the thread to do the work but only if we haven't been asked to stop
786 if (!CtdlThreadCheckStop())
787 ret = (this_thread->thread_func)(this_thread->user_args);
790 * Our thread is exiting either because it wanted to end or because the server is stopping
791 * We need to clean up
793 pthread_cleanup_pop(1); // Execute our cleanup routine and remove it
801 * Internal function to create a thread.
802 * Must be called from within a S_THREAD_LIST critical section
804 CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
807 CtdlThreadNode *this_thread;
809 if (num_threads >= 32767)
811 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
815 this_thread = malloc(sizeof(CtdlThreadNode));
816 if (this_thread == NULL) {
817 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
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));
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);
829 pthread_mutex_lock(&this_thread->ThreadMutex);
831 this_thread->state = CTDL_THREAD_CREATE;
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));
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.
848 if (flags & CTDLTHREAD_BIGSTACK)
850 #ifdef WITH_THREADLOG
851 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
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",
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.
874 this_thread->name = name;
878 this_thread->name = "Un-named Thread";
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.
888 this_thread->avg_blocked = 2;
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
895 if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
898 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
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);
910 num_threads++; // Increase the count of threads in the system.
911 if(this_thread->flags & CTDLTHREAD_WORKER)
914 this_thread->next = CtdlThreadList;
915 CtdlThreadList = this_thread;
916 if (this_thread->next)
917 this_thread->next->prev = this_thread;
919 pthread_mutex_unlock(&this_thread->ThreadMutex);
921 ctdl_thread_internal_calc_loadavg();
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
931 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
933 CtdlThreadNode *ret = NULL;
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);
944 * Internal function to schedule a thread.
945 * Must be called from within a S_THREAD_LIST critical section
947 CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
950 CtdlThreadNode *this_thread;
952 if (num_threads >= 32767)
954 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
958 this_thread = malloc(sizeof(CtdlThreadNode));
959 if (this_thread == NULL) {
960 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
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));
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);
972 this_thread->state = CTDL_THREAD_CREATE;
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));
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.
988 if (flags & CTDLTHREAD_BIGSTACK)
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",
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.
1011 this_thread->name = name;
1015 this_thread->name = "Un-named Thread";
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.
1025 this_thread->avg_blocked = 2;
1028 * When to start this thread
1030 this_thread->when = when;
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);
1044 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
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
1053 if ((ret = pthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1056 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
1062 num_threads++; // Increase the count of threads in the system.
1063 if(this_thread->flags & CTDLTHREAD_WORKER)
1066 this_thread->next = CtdlThreadList;
1067 CtdlThreadList = this_thread;
1068 if (this_thread->next)
1069 this_thread->next->prev = this_thread;
1076 void ctdl_thread_internal_check_scheduled(void)
1078 CtdlThreadNode *this_thread, *that_thread;
1081 if (try_critical_section(S_SCHEDULE_LIST))
1082 return; /* If this list is locked we wait till the next chance */
1086 #ifdef WITH_THREADLOG
1087 CtdlLogPrintf(CTDL_DEBUG, "Checking for scheduled threads to start.\n");
1090 this_thread = CtdlThreadSchedList;
1093 that_thread = this_thread;
1094 this_thread = this_thread->next;
1096 if (now > that_thread->when)
1098 /* Unlink from schedule list */
1099 if (that_thread->prev)
1100 that_thread->prev->next = that_thread->next;
1102 CtdlThreadSchedList = that_thread->next;
1103 if (that_thread->next)
1104 that_thread->next->prev = that_thread->prev;
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);
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)
1116 #ifdef WITH_THREADLOG
1117 CtdlLogPrintf(CTDL_DEBUG, "Failed to start scheduled thread \"%s\".\n", that_thread->name);
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);
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();
1135 end_critical_section(S_THREAD_LIST);
1139 #ifdef WITH_THREADLOG
1140 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" will start in %ld seconds.\n", that_thread->name, that_thread->when - time(NULL));
1144 end_critical_section(S_SCHEDULE_LIST);
1149 * A warapper function for select so we can show a thread as blocked
1151 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
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);
1163 void *new_worker_thread(void *arg);
1164 extern void close_masters (void);
1168 void go_threading(void)
1171 CtdlThreadNode *last_worker;
1174 * Initialise the thread system
1176 ctdl_thread_internal_init();
1178 /* Second call to module init functions now that threading is up */
1179 initialise_modules(1);
1182 * This thread is now used for garbage collection of other threads in the thread list
1184 CtdlLogPrintf(CTDL_INFO, "Startup thread %d becoming garbage collector,\n", pthread_self());
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
1193 while (CtdlThreadGetCount())
1196 exit_signal = CT->signal;
1199 CtdlThreadStopAll();
1202 check_sched_shutdown();
1203 if (CT->state > CTDL_THREAD_STOP_REQ)
1205 begin_critical_section(S_THREAD_LIST);
1206 ctdl_thread_internal_calc_loadavg();
1207 end_critical_section(S_THREAD_LIST);
1209 ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
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))
1215 /* Ask a worker thread to stop as we no longer need it */
1216 begin_critical_section(S_THREAD_LIST);
1217 last_worker = CtdlThreadList;
1220 pthread_mutex_lock(&last_worker->ThreadMutex);
1221 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1223 pthread_mutex_unlock(&last_worker->ThreadMutex);
1226 pthread_mutex_unlock(&last_worker->ThreadMutex);
1227 last_worker = last_worker->next;
1229 end_critical_section(S_THREAD_LIST);
1232 #ifdef WITH_THREADLOG
1233 CtdlLogPrintf(CTDL_DEBUG, "Thread system, stopping excess worker thread \"%s\" (%ld).\n",
1238 CtdlThreadStop(last_worker);
1243 * If all our workers are working hard, start some more to help out
1246 /* FIXME: come up with a better way to dynamically alter the number of threads
1247 * based on the system load
1250 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkers() <= num_sessions) ) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
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 */
1255 for (i=0; i<5 ; i++)
1258 CtdlThreadCreate("Worker Thread",
1259 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1264 CtdlThreadCreate("Worker Thread",
1265 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1269 #endif /* NEW_WORKER */
1275 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1280 if (CtdlThreadGetCount())
1284 * If the above loop exits we must be shutting down since we obviously have no threads
1286 ctdl_thread_internal_cleanup();
1293 * Starting a new implimentation of a worker thread.
1294 * This new implimentation will be faster and do more work per thread.
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.
1305 void select_on_master(void)
1308 struct ServiceFunctionHook *serviceptr;
1309 int ssock; /* Descriptor for client socket */
1314 struct CitContext *con;
1315 const char *old_name;
1319 old_name = CtdlThreadName("select_on_master");
1321 /* Initialize the fdset. */
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);
1334 tv.tv_sec = 1; /* wake up every 1 sec if no input */
1336 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1338 /* Select got an error or we are shutting down so get out */
1339 if (retval == 0 || CtdlThreadCheckStop()) {
1340 CtdlThreadName(old_name);
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);
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.
1354 if (fcntl(ssock, F_SETFL, 0) < 0) {
1355 CtdlLogPrintf(CTDL_EMERG,
1356 "citserver: Can't set socket to blocking: %s\n",
1360 /* New context will be created already
1361 * set up in the CON_EXECUTING state.
1363 con = CreateNewContext();
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;
1375 /* Set the SO_REUSEADDR socket option */
1377 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1379 become_session(con);
1381 serviceptr->h_greeting_function();
1382 become_session(NULL);
1383 con->state = CON_IDLE;
1389 CtdlThreadName(old_name);
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
1400 struct CitContext *select_on_client(void)
1406 const char *old_name;
1409 old_name = CtdlThreadName("select_on_client");
1411 /* Initialise the fdset */
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 */
1417 if (!CtdlThreadCheckStop())
1419 tv.tv_sec = config.c_sleeping; /* wake up every second if no input */
1421 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1423 else /* Shutting down? */
1425 CtdlThreadName(old_name);
1430 /* Now figure out who made this select() unblock.
1431 * First, check for an error or exit condition.
1434 if (errno == EBADF) {
1435 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
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");
1444 CtdlThreadName(old_name);
1447 else if(retval == 0)
1449 CtdlThreadName(old_name);
1450 CT->Context->kill_me = 1;
1455 CT->Context->state = CON_EXECUTING;
1456 CT->Context->input_waiting = 1;
1458 CtdlThreadName(old_name);
1459 return (CT->Context);
1465 * Do the worker threads work when needed
1467 int execute_session(struct CitContext *bind_me)
1471 become_session(bind_me);
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;
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;
1487 force_purge = CC->kill_me;
1490 become_session(NULL);
1491 bind_me->state = CON_IDLE;
1497 extern void dead_session_purge(int force);
1500 * A new worker_thread loop.
1503 void *new_worker_thread(void *arg)
1505 struct CitContext *bind_me;
1508 while (!CtdlThreadCheckStop()) {
1510 /* make doubly sure we're not holding any stale db handles
1511 * which might cause a deadlock.
1513 cdb_check_handles();
1515 bind_me = NULL; /* Which session shall we handle? */
1517 if (CT->Context == NULL)
1519 if (CtdlThreadCheckStop())
1523 bind_me = select_on_client();
1524 if (CtdlThreadCheckStop())
1528 force_purge = execute_session(bind_me);
1530 dead_session_purge(force_purge);
1531 if (CtdlThreadCheckStop())