4 * Citadel "system dependent" stuff.
5 * See COPYING for copyright information.
7 * Here's where we have the Citadel thread implimentation
14 #include <sys/types.h>
16 #include <sys/socket.h>
21 #if TIME_WITH_SYS_TIME
22 # include <sys/time.h>
26 # include <sys/time.h>
32 #include <libcitadel.h>
35 #include "ctdl_module.h"
36 #include "modules_init.h"
37 #include "housekeeping.h"
39 #include "citserver.h"
40 #include "sysdep_decls.h"
44 * define this to use the new worker_thread method of handling connections
49 * New thread interface.
50 * To create a thread you must call one of the create thread functions.
51 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
52 * struct CtdlThreadNode *node = NULL;
54 * If the thread is created *node will point to the thread control structure for the created thread.
55 * If the thread creation fails *node remains NULL
56 * Do not free the memory pointed to by *node, it doesn't belong to you.
57 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
58 * remove the need for the calls to eCrashRegisterThread and friends
61 static int num_threads = 0; /* Current number of threads */
62 static int num_workers = 0; /* Current number of worker threads */
64 CtdlThreadNode *CtdlThreadList = NULL;
65 CtdlThreadNode *CtdlThreadSchedList = NULL;
67 static CtdlThreadNode *GC_thread = NULL;
68 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
69 double CtdlThreadLoadAvg = 0;
70 double CtdlThreadWorkerAvg = 0;
71 citthread_key_t ThreadKey;
73 citthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
77 void InitialiseSemaphores(void)
81 /* Set up a bunch of semaphores to be used for critical sections */
82 for (i=0; i<MAX_SEMAPHORES; ++i) {
83 citthread_mutex_init(&Critters[i], NULL);
91 * Obtain a semaphore lock to begin a critical section.
92 * but only if no one else has one
94 int try_critical_section(int which_one)
96 /* For all types of critical sections except those listed here,
97 * ensure nobody ever tries to do a critical section within a
98 * transaction; this could lead to deadlock.
100 if ( (which_one != S_FLOORCACHE)
101 #ifdef DEBUG_MEMORY_LEAKS
102 && (which_one != S_DEBUGMEMLEAKS)
104 && (which_one != S_RPLIST)
108 return (citthread_mutex_trylock(&Critters[which_one]));
113 * Obtain a semaphore lock to begin a critical section.
115 void begin_critical_section(int which_one)
117 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
119 /* For all types of critical sections except those listed here,
120 * ensure nobody ever tries to do a critical section within a
121 * transaction; this could lead to deadlock.
123 if ( (which_one != S_FLOORCACHE)
124 #ifdef DEBUG_MEMORY_LEAKS
125 && (which_one != S_DEBUGMEMLEAKS)
127 && (which_one != S_RPLIST)
131 citthread_mutex_lock(&Critters[which_one]);
135 * Release a semaphore lock to end a critical section.
137 void end_critical_section(int which_one)
139 citthread_mutex_unlock(&Critters[which_one]);
144 * A function to destroy the TSD
146 static void ctdl_thread_internal_dest_tsd(void *arg)
156 * A function to initialise the thread TSD
158 void ctdl_thread_internal_init_tsd(void)
162 if ((ret = citthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
163 CtdlLogPrintf(CTDL_EMERG, "citthread_key_create: %s\n", strerror(ret));
169 * Ensure that we have a key for thread-specific data.
171 * This should be called immediately after startup by any thread
174 void CtdlThreadAllocTSD(void)
178 if (citthread_getspecific(ThreadKey) != NULL)
181 tsd = malloc(sizeof(ThreadTSD));
185 memset(tsd->cursors, 0, sizeof tsd->cursors);
188 citthread_setspecific(ThreadKey, tsd);
192 void ctdl_thread_internal_free_tsd(void)
194 ctdl_thread_internal_dest_tsd(citthread_getspecific(ThreadKey));
195 citthread_setspecific(ThreadKey, NULL);
199 void ctdl_thread_internal_cleanup(void)
202 CtdlThreadNode *this_thread, *that_thread;
204 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
206 free (CtdlThreadStates[i]);
209 /* Clean up the scheduled thread list */
210 this_thread = CtdlThreadSchedList;
213 that_thread = this_thread;
214 this_thread = this_thread->next;
215 citthread_mutex_destroy(&that_thread->ThreadMutex);
216 citthread_cond_destroy(&that_thread->ThreadCond);
217 citthread_mutex_destroy(&that_thread->SleepMutex);
218 citthread_cond_destroy(&that_thread->SleepCond);
219 citthread_attr_destroy(&that_thread->attr);
222 ctdl_thread_internal_free_tsd();
225 void ctdl_thread_internal_init(void)
227 CtdlThreadNode *this_thread;
230 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
231 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
232 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
233 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
234 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
235 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
236 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
237 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
238 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
239 CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
241 /* Get ourself a thread entry */
242 this_thread = malloc(sizeof(CtdlThreadNode));
243 if (this_thread == NULL) {
244 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
247 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
248 memset (this_thread, 0, sizeof(CtdlThreadNode));
250 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
251 citthread_cond_init (&(this_thread->ThreadCond), NULL);
252 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
253 citthread_cond_init (&(this_thread->SleepCond), NULL);
255 /* We are garbage collector so create us as running */
256 this_thread->state = CTDL_THREAD_RUNNING;
258 if ((ret = citthread_attr_init(&this_thread->attr))) {
259 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
264 this_thread->name = "Garbage Collection Thread";
266 this_thread->tid = citthread_self();
267 GC_thread = this_thread;
270 num_threads++; // Increase the count of threads in the system.
272 this_thread->next = CtdlThreadList;
273 CtdlThreadList = this_thread;
274 if (this_thread->next)
275 this_thread->next->prev = this_thread;
276 /* Set up start times */
277 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
278 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
283 * A function to update a threads load averages
285 void ctdl_thread_internal_update_avgs(CtdlThreadNode *this_thread)
287 struct timeval now, result;
288 double last_duration;
290 gettimeofday(&now, NULL);
291 timersub(&now, &(this_thread->last_state_change), &result);
292 /* I don't think these mutex's are needed here */
293 citthread_mutex_lock(&this_thread->ThreadMutex);
294 // result now has a timeval for the time we spent in the last state since we last updated
295 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
296 if (this_thread->state == CTDL_THREAD_SLEEPING)
297 this_thread->avg_sleeping += last_duration;
298 if (this_thread->state == CTDL_THREAD_RUNNING)
299 this_thread->avg_running += last_duration;
300 if (this_thread->state == CTDL_THREAD_BLOCKED)
301 this_thread->avg_blocked += last_duration;
302 memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
303 citthread_mutex_unlock(&this_thread->ThreadMutex);
307 * A function to chenge the state of a thread
309 void ctdl_thread_internal_change_state (CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
312 * Wether we change state or not we need update the load values
314 ctdl_thread_internal_update_avgs(this_thread);
315 /* This mutex not needed here? */
316 citthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
317 if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
318 this_thread->state = new_state;
319 if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
320 this_thread->state = new_state;
321 if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
322 this_thread->state = new_state;
323 citthread_mutex_unlock(&this_thread->ThreadMutex);
328 * A function to tell all threads to exit
330 void CtdlThreadStopAll(void)
332 /* First run any registered shutdown hooks. This probably doesn't belong here. */
333 PerformSessionHooks(EVT_SHUTDOWN);
335 //FIXME: The signalling of the condition should not be in the critical_section
336 // We need to build a list of threads we are going to signal and then signal them afterwards
338 CtdlThreadNode *this_thread;
340 begin_critical_section(S_THREAD_LIST);
341 this_thread = CtdlThreadList;
342 // Ask the GC thread to stop first so everything knows we are shutting down.
343 GC_thread->state = CTDL_THREAD_STOP_REQ;
346 #ifdef THREADS_USESIGNALS
347 if (!citthread_equal(this_thread->tid, GC_thread->tid))
348 citthread_kill(this_thread->tid, SIGHUP);
350 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
351 citthread_cond_signal(&this_thread->ThreadCond);
352 citthread_cond_signal(&this_thread->SleepCond);
353 this_thread->stop_ticker = time(NULL);
354 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (0x%08lx).\n",
355 this_thread->name, this_thread->tid);
356 this_thread = this_thread->next;
358 end_critical_section(S_THREAD_LIST);
363 * A function to wake up all sleeping threads
365 void CtdlThreadWakeAll(void)
367 CtdlThreadNode *this_thread;
369 CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
371 begin_critical_section(S_THREAD_LIST);
372 this_thread = CtdlThreadList;
375 if (!this_thread->thread_func)
377 citthread_cond_signal(&this_thread->ThreadCond);
378 citthread_cond_signal(&this_thread->SleepCond);
380 this_thread = this_thread->next;
382 end_critical_section(S_THREAD_LIST);
387 * A function to return the number of threads running in the system
389 int CtdlThreadGetCount(void)
394 int CtdlThreadGetWorkers(void)
399 double CtdlThreadGetWorkerAvg(void)
403 begin_critical_section(S_THREAD_LIST);
404 ret = CtdlThreadWorkerAvg;
405 end_critical_section(S_THREAD_LIST);
409 double CtdlThreadGetLoadAvg(void)
416 /* Borrowed this straight from procps */
417 smp_num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
418 if(smp_num_cpus<1) smp_num_cpus=1; /* SPARC glibc is buggy */
420 ret = getloadavg(load_avg, 3);
423 return load_avg[0] / smp_num_cpus;
425 * This old chunk of code return a value that indicated the load on citserver
426 * This value could easily reach 100 % even when citserver was doing very little and
427 * hence the machine has much more spare capacity.
428 * Because this value was used to determine if the machine was under heavy load conditions
429 * from other processes in the system then citserver could be strangled un-necesarily
430 * What we are actually trying to achieve is to strangle citserver if the machine is heavily loaded.
431 * So we have changed this.
433 begin_critical_section(S_THREAD_LIST);
434 ret = CtdlThreadLoadAvg;
435 end_critical_section(S_THREAD_LIST);
444 * A function to rename a thread
445 * Returns a const char *
447 const char *CtdlThreadName(const char *name)
449 const char *old_name;
453 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
464 * A function to force a thread to exit
466 void CtdlThreadCancel(CtdlThreadNode *thread)
468 CtdlThreadNode *this_thread;
473 this_thread = thread;
476 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
481 if (!this_thread->thread_func)
483 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
488 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
489 citthread_cancel(this_thread->tid);
494 * A function for a thread to check if it has been asked to stop
496 int CtdlThreadCheckStop(void)
502 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
509 #ifdef THREADS_USESIGNALS
512 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
516 if(state == CTDL_THREAD_STOP_REQ)
518 CT->state = CTDL_THREAD_STOPPING;
521 else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
530 * A function to ask a thread to exit
531 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
533 void CtdlThreadStop(CtdlThreadNode *thread)
535 CtdlThreadNode *this_thread;
540 this_thread = thread;
543 if (!(this_thread->thread_func))
544 return; // Don't stop garbage collector
545 #ifdef THREADS_USESIGNALS
546 if (!citthread_equal(this_thread->tid, GC_thread->tid))
547 citthread_kill(this_thread->tid, SIGHUP);
549 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
550 citthread_cond_signal(&this_thread->ThreadCond);
551 citthread_cond_signal(&this_thread->SleepCond);
552 this_thread->stop_ticker = time(NULL);
556 * So we now have a sleep command that works with threads but it is in seconds
558 void CtdlThreadSleep(int secs)
560 struct timespec wake_time;
561 struct timeval time_now;
566 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
570 memset (&wake_time, 0, sizeof(struct timespec));
571 gettimeofday(&time_now, NULL);
572 wake_time.tv_sec = time_now.tv_sec + secs;
573 wake_time.tv_nsec = time_now.tv_usec * 10;
575 ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
577 citthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
578 citthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
579 citthread_mutex_unlock(&CT->ThreadMutex);
581 ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
586 * Routine to clean up our thread function on exit
588 static void ctdl_internal_thread_cleanup(void *arg)
591 * In here we were called by the current thread because it is exiting
592 * NB. WE ARE THE CURRENT THREAD
594 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (0x%08lx) exited.\n", CT->name, CT->tid);
596 #ifdef HAVE_BACKTRACE
597 eCrash_UnregisterThread();
600 citthread_mutex_lock(&CT->ThreadMutex);
601 CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
602 citthread_mutex_unlock(&CT->ThreadMutex);
606 * A quick function to show the load averages
608 void ctdl_thread_internal_calc_loadavg(void)
610 CtdlThreadNode *that_thread;
611 double load_avg, worker_avg;
614 that_thread = CtdlThreadList;
619 /* Update load averages */
620 ctdl_thread_internal_update_avgs(that_thread);
621 citthread_mutex_lock(&that_thread->ThreadMutex);
622 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;
623 that_thread->avg_sleeping /= 2;
624 that_thread->avg_running /= 2;
625 that_thread->avg_blocked /= 2;
626 load_avg += that_thread->load_avg;
627 if (that_thread->flags & CTDLTHREAD_WORKER)
629 worker_avg += that_thread->load_avg;
632 #ifdef WITH_THREADLOG
633 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
636 CtdlThreadStates[that_thread->state],
637 that_thread->avg_sleeping,
638 that_thread->avg_running,
639 that_thread->avg_blocked,
640 that_thread->load_avg);
642 citthread_mutex_unlock(&that_thread->ThreadMutex);
643 that_thread = that_thread->next;
645 CtdlThreadLoadAvg = load_avg/num_threads;
646 CtdlThreadWorkerAvg = worker_avg/workers;
647 #ifdef WITH_THREADLOG
648 CtdlLogPrintf(CTDL_INFO, "System load average %.2f, workers averag %.2f, threads %d, workers %d, sessions %d\n", CtdlThreadGetLoadAvg(), CtdlThreadWorkerAvg, num_threads, num_workers, num_sessions);
654 * Garbage collection routine.
655 * Gets called by main() in a loop to clean up the thread list periodically.
657 void CtdlThreadGC (void)
659 CtdlThreadNode *this_thread, *that_thread;
660 int workers = 0, sys_workers;
663 begin_critical_section(S_THREAD_LIST);
665 /* Handle exiting of garbage collector thread */
667 CtdlThreadList->state = CTDL_THREAD_EXITED;
669 #ifdef WITH_THREADLOG
670 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
673 * Woke up to do garbage collection
675 this_thread = CtdlThreadList;
678 that_thread = this_thread;
679 this_thread = this_thread->next;
681 if ((that_thread->state == CTDL_THREAD_STOP_REQ || that_thread->state == CTDL_THREAD_STOPPING)
682 && (!citthread_equal(that_thread->tid, citthread_self())))
683 CtdlLogPrintf(CTDL_DEBUG, "Waiting for thread %s (0x%08lx) to exit.\n", that_thread->name, that_thread->tid);
687 * Catch the situation where a worker was asked to stop but couldn't and we are not
690 that_thread->stop_ticker = 0;
693 if (that_thread->stop_ticker + 5 == time(NULL))
695 CtdlLogPrintf(CTDL_DEBUG, "Thread System: The thread \"%s\" (0x%08lx) failed to self terminate within 5 ticks. It would be cancelled now.\n", that_thread->name, that_thread->tid);
696 if ((that_thread->flags & CTDLTHREAD_WORKER) == 0)
697 CtdlLogPrintf(CTDL_INFO, "Thread System: A non worker thread would have been canceled this may cause message loss.\n");
698 // that_thread->state = CTDL_THREAD_CANCELLED;
699 that_thread->stop_ticker++;
700 // citthread_cancel(that_thread->tid);
704 /* Do we need to clean up this thread? */
705 if ((that_thread->state != CTDL_THREAD_EXITED) && (that_thread->state != CTDL_THREAD_CANCELLED))
707 if(that_thread->flags & CTDLTHREAD_WORKER)
708 workers++; /* Sanity check on number of worker threads */
712 if (citthread_equal(that_thread->tid, citthread_self()) && that_thread->thread_func)
714 end_critical_section(S_THREAD_LIST);
715 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
720 if (num_threads <= 0)
722 end_critical_section(S_THREAD_LIST);
723 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
728 if(that_thread->flags & CTDLTHREAD_WORKER)
729 num_workers--; /* This is a wroker thread so reduce the count. */
731 /* If we are unlinking the list head then the next becomes the list head */
732 if(that_thread->prev)
733 that_thread->prev->next = that_thread->next;
735 CtdlThreadList = that_thread->next;
736 if(that_thread->next)
737 that_thread->next->prev = that_thread->prev;
739 citthread_cond_signal(&that_thread->ThreadCond);
740 citthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
741 citthread_mutex_lock(&that_thread->ThreadMutex); // Make sure it has done what its doing
742 citthread_mutex_unlock(&that_thread->ThreadMutex);
744 * Join on the thread to do clean up and prevent memory leaks
745 * Also makes sure the thread has cleaned up after itself before we remove it from the list
746 * We can join on the garbage collector thread the join should just return EDEADLCK
748 ret = citthread_join (that_thread->tid, NULL);
750 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection on own thread.\n");
751 else if (ret == EINVAL)
752 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, that thread already joined on.\n");
753 else if (ret == ESRCH)
754 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, no thread to join on.\n");
756 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, citthread_join returned an unknown error(%d).\n", ret);
758 * Now we own that thread entry
760 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (0x%08lx).\n",
761 that_thread->name, that_thread->tid);
762 citthread_mutex_destroy(&that_thread->ThreadMutex);
763 citthread_cond_destroy(&that_thread->ThreadCond);
764 citthread_mutex_destroy(&that_thread->SleepMutex);
765 citthread_cond_destroy(&that_thread->SleepCond);
766 citthread_attr_destroy(&that_thread->attr);
769 sys_workers = num_workers;
770 end_critical_section(S_THREAD_LIST);
772 /* Sanity check number of worker threads */
773 if (workers != sys_workers)
775 CtdlLogPrintf(CTDL_EMERG,
776 "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
787 * Runtime function for a Citadel Thread.
788 * This initialises the threads environment and then calls the user supplied thread function
789 * Note that this is the REAL thread function and wraps the users thread function.
791 static void *ctdl_internal_thread_func (void *arg)
793 CtdlThreadNode *this_thread;
796 /* lock and unlock the thread list.
797 * This causes this thread to wait until all its creation stuff has finished before it
798 * can continue its execution.
800 begin_critical_section(S_THREAD_LIST);
801 this_thread = (CtdlThreadNode *) arg;
802 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
803 // citthread_mutex_lock(&this_thread->ThreadMutex);
805 // Register the cleanup function to take care of when we exit.
806 citthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
807 // Get our thread data structure
808 CtdlThreadAllocTSD();
810 this_thread->pid = getpid();
811 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
812 /* Only change to running state if we weren't asked to stop during the create cycle
813 * Other wise there is a window to allow this threads creation to continue to full grown and
814 * therby prevent a shutdown of the server.
816 // citthread_mutex_unlock(&this_thread->ThreadMutex);
818 if (!CtdlThreadCheckStop())
820 citthread_mutex_lock(&this_thread->ThreadMutex);
821 this_thread->state = CTDL_THREAD_RUNNING;
822 citthread_mutex_unlock(&this_thread->ThreadMutex);
824 end_critical_section(S_THREAD_LIST);
826 // Register for tracing
827 #ifdef HAVE_BACKTRACE
828 eCrash_RegisterThread(this_thread->name, 0);
831 // Tell the world we are here
832 CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (0x%08lx).\n",
833 this_thread->name, this_thread->tid);
836 * run the thread to do the work but only if we haven't been asked to stop
838 if (!CtdlThreadCheckStop())
839 ret = (this_thread->thread_func)(this_thread->user_args);
842 * Our thread is exiting either because it wanted to end or because the server is stopping
843 * We need to clean up
845 citthread_cleanup_pop(1); // Execute our cleanup routine and remove it
854 * Function to initialise an empty thread structure
856 CtdlThreadNode *ctdl_internal_init_thread_struct(CtdlThreadNode *this_thread, long flags)
860 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
861 memset (this_thread, 0, sizeof(CtdlThreadNode));
863 /* Create the mutex's early so we can use them */
864 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
865 citthread_cond_init (&(this_thread->ThreadCond), NULL);
866 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
867 citthread_cond_init (&(this_thread->SleepCond), NULL);
869 this_thread->state = CTDL_THREAD_CREATE;
871 if ((ret = citthread_attr_init(&this_thread->attr))) {
872 citthread_mutex_unlock(&this_thread->ThreadMutex);
873 citthread_mutex_destroy(&(this_thread->ThreadMutex));
874 citthread_cond_destroy(&(this_thread->ThreadCond));
875 citthread_mutex_destroy(&(this_thread->SleepMutex));
876 citthread_cond_destroy(&(this_thread->SleepCond));
877 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
882 /* Our per-thread stacks need to be bigger than the default size,
883 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
884 * crashes on 64-bit Linux.
886 if (flags & CTDLTHREAD_BIGSTACK)
888 #ifdef WITH_THREADLOG
889 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
891 if ((ret = citthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
892 citthread_mutex_unlock(&this_thread->ThreadMutex);
893 citthread_mutex_destroy(&(this_thread->ThreadMutex));
894 citthread_cond_destroy(&(this_thread->ThreadCond));
895 citthread_mutex_destroy(&(this_thread->SleepMutex));
896 citthread_cond_destroy(&(this_thread->SleepCond));
897 citthread_attr_destroy(&this_thread->attr);
898 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_setstacksize: %s\n",
905 /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
906 * load average for the system. If we don't do this then we create a mass of threads at the same time
907 * because the creation didn't affect the load average.
909 this_thread->avg_blocked = 2;
911 return (this_thread);
918 * Internal function to create a thread.
920 CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
923 CtdlThreadNode *this_thread;
925 if (num_threads >= 32767)
927 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
931 this_thread = malloc(sizeof(CtdlThreadNode));
932 if (this_thread == NULL) {
933 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
937 /* Initialise the thread structure */
938 if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
941 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
945 * If we got here we are going to create the thread so we must initilise the structure
946 * first because most implimentations of threading can't create it in a stopped state
947 * and it might want to do things with its structure that aren't initialised otherwise.
951 this_thread->name = name;
955 this_thread->name = "Un-named Thread";
958 this_thread->flags = flags;
959 this_thread->thread_func = thread_func;
960 this_thread->user_args = args;
962 // citthread_mutex_lock(&this_thread->ThreadMutex);
964 begin_critical_section(S_THREAD_LIST);
966 * We pass this_thread into the thread as its args so that it can find out information
967 * about itself and it has a bit of storage space for itself, not to mention that the REAL
968 * thread function needs to finish off the setup of the structure
970 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
972 end_critical_section(S_THREAD_LIST);
973 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
975 citthread_mutex_unlock(&this_thread->ThreadMutex);
976 citthread_mutex_destroy(&(this_thread->ThreadMutex));
977 citthread_cond_destroy(&(this_thread->ThreadCond));
978 citthread_mutex_destroy(&(this_thread->SleepMutex));
979 citthread_cond_destroy(&(this_thread->SleepCond));
980 citthread_attr_destroy(&this_thread->attr);
985 num_threads++; // Increase the count of threads in the system.
986 if(this_thread->flags & CTDLTHREAD_WORKER)
989 this_thread->next = CtdlThreadList;
990 CtdlThreadList = this_thread;
991 if (this_thread->next)
992 this_thread->next->prev = this_thread;
993 ctdl_thread_internal_calc_loadavg();
995 // citthread_mutex_unlock(&this_thread->ThreadMutex);
996 end_critical_section(S_THREAD_LIST);
1002 * Wrapper function to create a thread
1003 * ensures the critical section and other protections are in place.
1004 * char *name = name to give to thread, if NULL, use generic name
1005 * int flags = flags to determine type of thread and standard facilities
1007 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1009 CtdlThreadNode *ret = NULL;
1011 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1018 * Internal function to schedule a thread.
1019 * Must be called from within a S_THREAD_LIST critical section
1021 CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
1023 CtdlThreadNode *this_thread;
1025 if (num_threads >= 32767)
1027 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1031 this_thread = malloc(sizeof(CtdlThreadNode));
1032 if (this_thread == NULL) {
1033 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1036 /* Initialise the thread structure */
1037 if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
1040 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
1045 * If we got here we are going to create the thread so we must initilise the structure
1046 * first because most implimentations of threading can't create it in a stopped state
1047 * and it might want to do things with its structure that aren't initialised otherwise.
1051 this_thread->name = name;
1055 this_thread->name = "Un-named Thread";
1058 this_thread->flags = flags;
1059 this_thread->thread_func = thread_func;
1060 this_thread->user_args = args;
1063 * When to start this thread
1065 this_thread->when = when;
1067 begin_critical_section(S_SCHEDULE_LIST);
1068 this_thread->next = CtdlThreadSchedList;
1069 CtdlThreadSchedList = this_thread;
1070 if (this_thread->next)
1071 this_thread->next->prev = this_thread;
1072 end_critical_section(S_SCHEDULE_LIST);
1079 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
1083 // citthread_mutex_lock(&that_thread->ThreadMutex);
1084 begin_critical_section(S_THREAD_LIST);
1086 * We pass this_thread into the thread as its args so that it can find out information
1087 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1088 * thread function needs to finish off the setup of the structure
1090 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1092 end_critical_section(S_THREAD_LIST);
1093 CtdlLogPrintf(CTDL_DEBUG, "Failed to start scheduled thread \"%s\": %s\n", this_thread->name, strerror(ret));
1094 // citthread_mutex_unlock(&this_thread->ThreadMutex);
1095 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1096 citthread_cond_destroy(&(this_thread->ThreadCond));
1097 citthread_mutex_destroy(&(this_thread->SleepMutex));
1098 citthread_cond_destroy(&(this_thread->SleepCond));
1099 citthread_attr_destroy(&this_thread->attr);
1105 num_threads++; // Increase the count of threads in the system.
1106 if(this_thread->flags & CTDLTHREAD_WORKER)
1109 this_thread->next = CtdlThreadList;
1110 CtdlThreadList = this_thread;
1111 if (this_thread->next)
1112 this_thread->next->prev = this_thread;
1113 // citthread_mutex_unlock(&that_thread->ThreadMutex);
1115 ctdl_thread_internal_calc_loadavg();
1116 end_critical_section(S_THREAD_LIST);
1124 void ctdl_thread_internal_check_scheduled(void)
1126 CtdlThreadNode *this_thread, *that_thread;
1129 /* Don't start scheduled threads if the system wants single user mode */
1130 if (CtdlWantSingleUser())
1133 if (try_critical_section(S_SCHEDULE_LIST))
1134 return; /* If this list is locked we wait till the next chance */
1138 #ifdef WITH_THREADLOG
1139 CtdlLogPrintf(CTDL_DEBUG, "Checking for scheduled threads to start.\n");
1142 this_thread = CtdlThreadSchedList;
1145 that_thread = this_thread;
1146 this_thread = this_thread->next;
1148 if (now > that_thread->when)
1150 /* Unlink from schedule list */
1151 if (that_thread->prev)
1152 that_thread->prev->next = that_thread->next;
1154 CtdlThreadSchedList = that_thread->next;
1155 if (that_thread->next)
1156 that_thread->next->prev = that_thread->prev;
1158 that_thread->next = that_thread->prev = NULL;
1159 #ifdef WITH_THREADLOG
1160 CtdlLogPrintf(CTDL_DEBUG, "About to start scheduled thread \"%s\".\n", that_thread->name);
1162 if (CT->state > CTDL_THREAD_STOP_REQ)
1163 { /* Only start it if the system is not stopping */
1164 if (ctdl_thread_internal_start_scheduled (that_thread))
1166 #ifdef WITH_THREADLOG
1167 CtdlLogPrintf(CTDL_INFO, "Thread system, Started a scheduled thread \"%s\" (0x%08lx).\n",
1168 that_thread->name, that_thread->tid);
1173 #ifdef WITH_THREADLOG
1176 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" will start in %ld seconds.\n",
1177 that_thread->name, that_thread->when - time(NULL));
1181 end_critical_section(S_SCHEDULE_LIST);
1186 * A warapper function for select so we can show a thread as blocked
1188 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
1192 ctdl_thread_internal_change_state(CT, CTDL_THREAD_BLOCKED);
1193 if (!CtdlThreadCheckStop())
1194 ret = select(n, readfds, writefds, exceptfds, timeout);
1196 * If the select returned <= 0 then it failed due to an error
1197 * or timeout so this thread could stop if asked to do so.
1198 * Anything else means it needs to continue unless the system is shutting down
1203 * The select says this thread needs to do something useful.
1204 * This thread was in an idle state so it may have been asked to stop
1205 * but if the system isn't shutting down this thread is no longer
1206 * idle and select has given it a task to do so it must not stop
1207 * In this condition we need to force it into the running state.
1208 * CtdlThreadGC will clear its ticker for us.
1210 * FIXME: there is still a small hole here. It is possible for the sequence of locking
1211 * to allow the state to get changed to STOP_REQ just after this code if the other thread
1212 * has decided to change the state before this lock, it there fore has to wait till the lock
1213 * completes but it will continue to change the state. We need something a bit better here.
1215 citthread_mutex_lock(&CT->ThreadMutex); /* To prevent race condition of a sleeping thread */
1216 if (GC_thread->state > CTDL_THREAD_STOP_REQ && CT->state <= CTDL_THREAD_STOP_REQ)
1218 CtdlLogPrintf(CTDL_DEBUG, "Thread %s (0x%08lx) refused stop request.\n", CT->name, CT->tid);
1219 CT->state = CTDL_THREAD_RUNNING;
1221 citthread_mutex_unlock(&CT->ThreadMutex);
1224 ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1231 void *new_worker_thread(void *arg);
1232 extern void close_masters (void);
1236 void go_threading(void)
1239 CtdlThreadNode *last_worker;
1242 * Initialise the thread system
1244 ctdl_thread_internal_init();
1246 /* Second call to module init functions now that threading is up */
1247 initialise_modules(1);
1250 * This thread is now used for garbage collection of other threads in the thread list
1252 CtdlLogPrintf(CTDL_INFO, "Startup thread %d becoming garbage collector,\n", citthread_self());
1255 * We do a lot of locking and unlocking of the thread list in here.
1256 * We do this so that we can repeatedly release time for other threads
1257 * that may be waiting on the thread list.
1258 * We are a low priority thread so we can afford to do this
1261 while (CtdlThreadGetCount())
1264 exit_signal = CT->signal;
1267 CtdlThreadStopAll();
1270 check_sched_shutdown();
1271 if (CT->state > CTDL_THREAD_STOP_REQ)
1273 begin_critical_section(S_THREAD_LIST);
1274 ctdl_thread_internal_calc_loadavg();
1275 end_critical_section(S_THREAD_LIST);
1277 ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
1280 /* Reduce the size of the worker thread pool if necessary. */
1281 if ((CtdlThreadGetWorkers() > config.c_min_workers + 1) && (CtdlThreadWorkerAvg < 20) && (CT->state > CTDL_THREAD_STOP_REQ))
1283 /* Ask a worker thread to stop as we no longer need it */
1284 begin_critical_section(S_THREAD_LIST);
1285 last_worker = CtdlThreadList;
1288 citthread_mutex_lock(&last_worker->ThreadMutex);
1289 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1291 citthread_mutex_unlock(&last_worker->ThreadMutex);
1294 citthread_mutex_unlock(&last_worker->ThreadMutex);
1295 last_worker = last_worker->next;
1297 end_critical_section(S_THREAD_LIST);
1300 #ifdef WITH_THREADLOG
1301 CtdlLogPrintf(CTDL_DEBUG, "Thread system, stopping excess worker thread \"%s\" (0x%08lx).\n",
1306 CtdlThreadStop(last_worker);
1311 * If all our workers are working hard, start some more to help out
1314 /* FIXME: come up with a better way to dynamically alter the number of threads
1315 * based on the system load
1318 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkers() <= num_sessions) ) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1320 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkerAvg() > 60)) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1321 #endif /* NEW_WORKER */
1323 /* Only start new threads if we are not going to overload the machine */
1324 if (CtdlThreadGetLoadAvg() < ((double)1.00)) {
1325 for (i=0; i<5 ; i++) {
1327 CtdlThreadCreate("Worker Thread (new)",
1328 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1333 CtdlThreadCreate("Worker Thread",
1334 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1338 #endif /* NEW_WORKER */
1342 CtdlLogPrintf (CTDL_WARNING, "Server strangled due to machine load average too high.\n");
1347 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1352 #ifdef THREADS_USESIGNALS
1353 if (CtdlThreadGetCount() && CT->state > CTDL_THREAD_STOP_REQ)
1355 if (CtdlThreadGetCount())
1360 * If the above loop exits we must be shutting down since we obviously have no threads
1362 ctdl_thread_internal_cleanup();
1369 * Starting a new implimentation of a worker thread.
1370 * This new implimentation will be faster and do more work per thread.
1374 * Select on master socket.
1375 * First worker thread in here acquires the lock and builds an FDSET of master sockets.
1376 * then it goes into a loop selecting on the master sockets timing out every few milliseconds.
1377 * If it times out it rebiulds its list and loops.
1378 * If the select succeeds it creates a new context and returns.
1379 * During this time the other workers are selecting on existing contexts or sleeping.
1381 void select_on_master(void)
1384 struct ServiceFunctionHook *serviceptr;
1385 int ssock; /* Descriptor for client socket */
1390 struct CitContext *con;
1391 const char *old_name;
1395 old_name = CtdlThreadName("select_on_master");
1397 /* Initialize the fdset. */
1401 /* First, add the various master sockets to the fdset. */
1402 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1403 m = serviceptr->msock;
1404 FD_SET(m, &readfds);
1410 tv.tv_sec = 1; /* wake up every 1 sec if no input */
1412 retval = CtdlThreadSelect(highest + 1, &readfds, NULL, NULL, &tv);
1414 /* Select got an error or we are shutting down so get out */
1415 if (retval == 0 || CtdlThreadCheckStop()) {
1416 CtdlThreadName(old_name);
1420 /* Select says something happened on one of our master sockets so now we handle it */
1421 for (serviceptr = ServiceHookTable; serviceptr != NULL; serviceptr = serviceptr->next ) {
1422 if (FD_ISSET(serviceptr->msock, &readfds)) {
1423 ssock = accept(serviceptr->msock, NULL, 0);
1425 CtdlLogPrintf(CTDL_DEBUG, "New client socket %d\n", ssock);
1426 /* The master socket is non-blocking but the client
1427 * sockets need to be blocking, otherwise certain
1428 * operations barf on FreeBSD. Not a fatal error.
1430 if (fcntl(ssock, F_SETFL, 0) < 0) {
1431 CtdlLogPrintf(CTDL_EMERG,
1432 "citserver: Can't set socket to blocking: %s\n",
1436 /* New context will be created already
1437 * set up in the CON_EXECUTING state.
1439 con = CreateNewContext();
1442 /* Assign our new socket number to it. */
1443 con->client_socket = ssock;
1444 con->h_command_function = serviceptr->h_command_function;
1445 con->h_async_function = serviceptr->h_async_function;
1446 con->ServiceName = serviceptr->ServiceName;
1447 /* Determine whether it's a local socket */
1448 if (serviceptr->sockpath != NULL)
1449 con->is_local_socket = 1;
1451 /* Set the SO_REUSEADDR socket option */
1453 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
1455 become_session(con);
1457 serviceptr->h_greeting_function();
1458 become_session(NULL);
1459 con->state = CON_IDLE;
1465 CtdlThreadName(old_name);
1469 * Select on client socket.
1470 * First worker thread in here acquires the lock and builds an FDSET of client sockets.
1471 * then it selects on the client sockets timing out after 1 second.
1472 * If it times out the thread goes off to check on housekeeping etc.
1473 * If the select succeeds the thread goes off to handle the client request.
1474 * If the list of client connections is empty the threads all sleep for one second
1476 struct CitContext *select_on_client(void)
1482 const char *old_name;
1485 old_name = CtdlThreadName("select_on_client");
1487 /* Initialise the fdset */
1489 FD_SET(CT->Context->client_socket, &readfds);
1490 highest = CT->Context->client_socket;
1491 /* Now we can select on any connections that are waiting */
1493 if (!CtdlThreadCheckStop())
1495 tv.tv_sec = config.c_sleeping; /* wake up every second if no input */
1497 retval = select(highest + 1, &readfds, NULL, NULL, &tv);
1499 else /* Shutting down? */
1501 CtdlThreadName(old_name);
1506 /* Now figure out who made this select() unblock.
1507 * First, check for an error or exit condition.
1510 if (errno == EBADF) {
1511 CtdlLogPrintf(CTDL_NOTICE, "select() failed: (%s)\n",
1514 if (errno != EINTR) {
1515 CtdlLogPrintf(CTDL_EMERG, "Exiting (%s)\n", strerror(errno));
1516 CtdlThreadStopAll();
1517 } else if (!CtdlThreadCheckStop()) {
1518 CtdlLogPrintf(CTDL_DEBUG, "Un handled select failure.\n");
1520 CtdlThreadName(old_name);
1523 else if(retval == 0)
1525 CtdlThreadName(old_name);
1526 CT->Context->kill_me = 1;
1531 CT->Context->state = CON_EXECUTING;
1532 CT->Context->input_waiting = 1;
1534 CtdlThreadName(old_name);
1535 return (CT->Context);
1541 * Do the worker threads work when needed
1543 int execute_session(struct CitContext *bind_me)
1547 become_session(bind_me);
1549 /* If the client has sent a command, execute it. */
1550 if (CC->input_waiting) {
1551 CC->h_command_function();
1552 CC->input_waiting = 0;
1555 /* If there are asynchronous messages waiting and the
1556 * client supports it, do those now */
1557 if ((CC->is_async) && (CC->async_waiting)
1558 && (CC->h_async_function != NULL)) {
1559 CC->h_async_function();
1560 CC->async_waiting = 0;
1563 force_purge = CC->kill_me;
1566 become_session(NULL);
1567 bind_me->state = CON_IDLE;
1575 * A new worker_thread loop.
1578 void *new_worker_thread(void *arg)
1580 struct CitContext *bind_me;
1583 while (!CtdlThreadCheckStop()) {
1585 /* make doubly sure we're not holding any stale db handles
1586 * which might cause a deadlock.
1588 cdb_check_handles();
1590 bind_me = NULL; /* Which session shall we handle? */
1592 if (CT->Context == NULL)
1594 if (CtdlThreadCheckStop())
1598 bind_me = select_on_client();
1599 if (CtdlThreadCheckStop())
1603 force_purge = execute_session(bind_me);
1605 dead_session_purge(force_purge);
1606 if (CtdlThreadCheckStop())