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 */
63 long statcount = 0; /* are we doing a stats check? */
64 static long stats_done = 0;
66 CtdlThreadNode *CtdlThreadList = NULL;
67 CtdlThreadNode *CtdlThreadSchedList = NULL;
69 static CtdlThreadNode *GC_thread = NULL;
70 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
71 double CtdlThreadLoadAvg = 0;
72 double CtdlThreadWorkerAvg = 0;
73 citthread_key_t ThreadKey;
75 citthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
79 void InitialiseSemaphores(void)
83 /* Set up a bunch of semaphores to be used for critical sections */
84 for (i=0; i<MAX_SEMAPHORES; ++i) {
85 citthread_mutex_init(&Critters[i], NULL);
93 * Obtain a semaphore lock to begin a critical section.
94 * but only if no one else has one
96 int try_critical_section(int which_one)
98 /* For all types of critical sections except those listed here,
99 * ensure nobody ever tries to do a critical section within a
100 * transaction; this could lead to deadlock.
102 if ( (which_one != S_FLOORCACHE)
103 #ifdef DEBUG_MEMORY_LEAKS
104 && (which_one != S_DEBUGMEMLEAKS)
106 && (which_one != S_RPLIST)
110 return (citthread_mutex_trylock(&Critters[which_one]));
115 * Obtain a semaphore lock to begin a critical section.
117 void begin_critical_section(int which_one)
119 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
121 /* For all types of critical sections except those listed here,
122 * ensure nobody ever tries to do a critical section within a
123 * transaction; this could lead to deadlock.
125 if ( (which_one != S_FLOORCACHE)
126 #ifdef DEBUG_MEMORY_LEAKS
127 && (which_one != S_DEBUGMEMLEAKS)
129 && (which_one != S_RPLIST)
133 citthread_mutex_lock(&Critters[which_one]);
137 * Release a semaphore lock to end a critical section.
139 void end_critical_section(int which_one)
141 citthread_mutex_unlock(&Critters[which_one]);
146 * A function to destroy the TSD
148 static void ctdl_thread_internal_dest_tsd(void *arg)
158 * A function to initialise the thread TSD
160 void ctdl_thread_internal_init_tsd(void)
164 if ((ret = citthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
165 CtdlLogPrintf(CTDL_EMERG, "citthread_key_create: %s\n", strerror(ret));
171 * Ensure that we have a key for thread-specific data.
173 * This should be called immediately after startup by any thread
176 void CtdlThreadAllocTSD(void)
180 if (citthread_getspecific(ThreadKey) != NULL)
183 tsd = malloc(sizeof(ThreadTSD));
187 memset(tsd->cursors, 0, sizeof tsd->cursors);
190 citthread_setspecific(ThreadKey, tsd);
194 void ctdl_thread_internal_free_tsd(void)
196 ctdl_thread_internal_dest_tsd(citthread_getspecific(ThreadKey));
197 citthread_setspecific(ThreadKey, NULL);
201 void ctdl_thread_internal_cleanup(void)
204 CtdlThreadNode *this_thread, *that_thread;
206 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
208 free (CtdlThreadStates[i]);
211 /* Clean up the scheduled thread list */
212 this_thread = CtdlThreadSchedList;
215 that_thread = this_thread;
216 this_thread = this_thread->next;
217 citthread_mutex_destroy(&that_thread->ThreadMutex);
218 citthread_cond_destroy(&that_thread->ThreadCond);
219 citthread_mutex_destroy(&that_thread->SleepMutex);
220 citthread_cond_destroy(&that_thread->SleepCond);
221 citthread_attr_destroy(&that_thread->attr);
224 ctdl_thread_internal_free_tsd();
227 void ctdl_thread_internal_init(void)
229 CtdlThreadNode *this_thread;
232 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
233 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
234 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
235 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
236 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
237 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
238 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
239 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
240 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
241 CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
243 /* Get ourself a thread entry */
244 this_thread = malloc(sizeof(CtdlThreadNode));
245 if (this_thread == NULL) {
246 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
249 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
250 memset (this_thread, 0, sizeof(CtdlThreadNode));
252 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
253 citthread_cond_init (&(this_thread->ThreadCond), NULL);
254 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
255 citthread_cond_init (&(this_thread->SleepCond), NULL);
257 /* We are garbage collector so create us as running */
258 this_thread->state = CTDL_THREAD_RUNNING;
260 if ((ret = citthread_attr_init(&this_thread->attr))) {
261 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
266 this_thread->name = "Garbage Collection Thread";
268 this_thread->tid = citthread_self();
269 GC_thread = this_thread;
272 num_threads++; // Increase the count of threads in the system.
274 this_thread->next = CtdlThreadList;
275 CtdlThreadList = this_thread;
276 if (this_thread->next)
277 this_thread->next->prev = this_thread;
278 /* Set up start times */
279 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
280 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
285 * A function to update a threads load averages
287 void ctdl_thread_internal_update_avgs(CtdlThreadNode *this_thread)
289 struct timeval now, result;
290 double last_duration;
292 gettimeofday(&now, NULL);
293 timersub(&now, &(this_thread->last_state_change), &result);
294 /* I don't think these mutex's are needed here */
295 citthread_mutex_lock(&this_thread->ThreadMutex);
296 // result now has a timeval for the time we spent in the last state since we last updated
297 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
298 if (this_thread->state == CTDL_THREAD_SLEEPING)
299 this_thread->avg_sleeping += last_duration;
300 if (this_thread->state == CTDL_THREAD_RUNNING)
301 this_thread->avg_running += last_duration;
302 if (this_thread->state == CTDL_THREAD_BLOCKED)
303 this_thread->avg_blocked += last_duration;
304 memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
305 citthread_mutex_unlock(&this_thread->ThreadMutex);
309 * A function to chenge the state of a thread
311 void ctdl_thread_internal_change_state (CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
314 * Wether we change state or not we need update the load values
316 ctdl_thread_internal_update_avgs(this_thread);
317 /* This mutex not needed here? */
318 citthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
319 if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
320 this_thread->state = new_state;
321 if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
322 this_thread->state = new_state;
323 if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
324 this_thread->state = new_state;
325 citthread_mutex_unlock(&this_thread->ThreadMutex);
330 * A function to tell all threads to exit
332 void CtdlThreadStopAll(void)
334 /* First run any registered shutdown hooks. This probably doesn't belong here. */
335 PerformSessionHooks(EVT_SHUTDOWN);
337 //FIXME: The signalling of the condition should not be in the critical_section
338 // We need to build a list of threads we are going to signal and then signal them afterwards
340 CtdlThreadNode *this_thread;
342 begin_critical_section(S_THREAD_LIST);
343 this_thread = CtdlThreadList;
344 // Ask the GC thread to stop first so everything knows we are shutting down.
345 GC_thread->state = CTDL_THREAD_STOP_REQ;
348 if (!citthread_equal(this_thread->tid, GC_thread->tid))
349 citthread_kill(this_thread->tid, SIGHUP);
351 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
352 citthread_cond_signal(&this_thread->ThreadCond);
353 citthread_cond_signal(&this_thread->SleepCond);
354 this_thread->stop_ticker = time(NULL);
355 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (0x%08lx).\n",
356 this_thread->name, this_thread->tid);
357 this_thread = this_thread->next;
359 end_critical_section(S_THREAD_LIST);
364 * A function to wake up all sleeping threads
366 void CtdlThreadWakeAll(void)
368 CtdlThreadNode *this_thread;
370 CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
372 begin_critical_section(S_THREAD_LIST);
373 this_thread = CtdlThreadList;
376 if (!this_thread->thread_func)
378 citthread_cond_signal(&this_thread->ThreadCond);
379 citthread_cond_signal(&this_thread->SleepCond);
381 this_thread = this_thread->next;
383 end_critical_section(S_THREAD_LIST);
388 * A function to return the number of threads running in the system
390 int CtdlThreadGetCount(void)
395 int CtdlThreadGetWorkers(void)
400 double CtdlThreadGetWorkerAvg(void)
404 begin_critical_section(S_THREAD_LIST);
405 ret = CtdlThreadWorkerAvg;
406 end_critical_section(S_THREAD_LIST);
410 double CtdlThreadGetLoadAvg(void)
412 double load_avg[3] = {0.0, 0.0, 0.0};
417 /* Borrowed this straight from procps */
418 smp_num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
419 if(smp_num_cpus<1) smp_num_cpus=1; /* SPARC glibc is buggy */
421 #ifdef HAVE_GETLOADAVG
422 ret = getloadavg(load_avg, 3);
426 return load_avg[0] / smp_num_cpus;
428 * This old chunk of code return a value that indicated the load on citserver
429 * This value could easily reach 100 % even when citserver was doing very little and
430 * hence the machine has much more spare capacity.
431 * Because this value was used to determine if the machine was under heavy load conditions
432 * from other processes in the system then citserver could be strangled un-necesarily
433 * What we are actually trying to achieve is to strangle citserver if the machine is heavily loaded.
434 * So we have changed this.
436 begin_critical_section(S_THREAD_LIST);
437 ret = CtdlThreadLoadAvg;
438 end_critical_section(S_THREAD_LIST);
447 * A function to rename a thread
448 * Returns a const char *
450 const char *CtdlThreadName(const char *name)
452 const char *old_name;
456 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
467 * A function to force a thread to exit
469 void CtdlThreadCancel(CtdlThreadNode *thread)
471 CtdlThreadNode *this_thread;
476 this_thread = thread;
479 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
484 if (!this_thread->thread_func)
486 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
491 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
492 citthread_cancel(this_thread->tid);
497 * A function for a thread to check if it has been asked to stop
499 int CtdlThreadCheckStop(void)
505 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
514 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
515 if (CT->signal == SIGHUP)
516 CT->state = CTDL_THREAD_STOP_REQ;
519 if(state == CTDL_THREAD_STOP_REQ)
521 CT->state = CTDL_THREAD_STOPPING;
524 else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
533 * A function to ask a thread to exit
534 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
536 void CtdlThreadStop(CtdlThreadNode *thread)
538 CtdlThreadNode *this_thread;
543 this_thread = thread;
546 if (!(this_thread->thread_func))
547 return; // Don't stop garbage collector
549 if (!citthread_equal(this_thread->tid, GC_thread->tid))
550 citthread_kill(this_thread->tid, SIGHUP);
552 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
553 citthread_cond_signal(&this_thread->ThreadCond);
554 citthread_cond_signal(&this_thread->SleepCond);
555 this_thread->stop_ticker = time(NULL);
559 * So we now have a sleep command that works with threads but it is in seconds
561 void CtdlThreadSleep(int secs)
563 struct timespec wake_time;
564 struct timeval time_now;
569 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
573 memset (&wake_time, 0, sizeof(struct timespec));
574 gettimeofday(&time_now, NULL);
575 wake_time.tv_sec = time_now.tv_sec + secs;
576 wake_time.tv_nsec = time_now.tv_usec * 10;
578 ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
580 citthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
581 citthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
582 citthread_mutex_unlock(&CT->ThreadMutex);
584 ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
589 * Routine to clean up our thread function on exit
591 static void ctdl_internal_thread_cleanup(void *arg)
594 * In here we were called by the current thread because it is exiting
595 * NB. WE ARE THE CURRENT THREAD
597 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (0x%08lx) exited.\n", CT->name, CT->tid);
599 #ifdef HAVE_BACKTRACE
600 eCrash_UnregisterThread();
603 citthread_mutex_lock(&CT->ThreadMutex);
604 CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
605 citthread_mutex_unlock(&CT->ThreadMutex);
609 * A quick function to show the load averages
611 void ctdl_thread_internal_calc_loadavg(void)
613 CtdlThreadNode *that_thread;
614 double load_avg, worker_avg;
617 that_thread = CtdlThreadList;
622 /* Update load averages */
623 ctdl_thread_internal_update_avgs(that_thread);
624 citthread_mutex_lock(&that_thread->ThreadMutex);
625 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;
626 that_thread->avg_sleeping /= 2;
627 that_thread->avg_running /= 2;
628 that_thread->avg_blocked /= 2;
629 load_avg += that_thread->load_avg;
630 if (that_thread->flags & CTDLTHREAD_WORKER)
632 worker_avg += that_thread->load_avg;
635 #ifdef WITH_THREADLOG
636 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
639 CtdlThreadStates[that_thread->state],
640 that_thread->avg_sleeping,
641 that_thread->avg_running,
642 that_thread->avg_blocked,
643 that_thread->load_avg);
645 citthread_mutex_unlock(&that_thread->ThreadMutex);
646 that_thread = that_thread->next;
648 CtdlThreadLoadAvg = load_avg/num_threads;
649 CtdlThreadWorkerAvg = worker_avg/workers;
650 #ifdef WITH_THREADLOG
651 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);
657 * Garbage collection routine.
658 * Gets called by main() in a loop to clean up the thread list periodically.
660 void CtdlThreadGC (void)
662 CtdlThreadNode *this_thread, *that_thread;
663 int workers = 0, sys_workers;
666 begin_critical_section(S_THREAD_LIST);
668 /* Handle exiting of garbage collector thread */
670 CtdlThreadList->state = CTDL_THREAD_EXITED;
672 #ifdef WITH_THREADLOG
673 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
676 * Woke up to do garbage collection
678 this_thread = CtdlThreadList;
681 that_thread = this_thread;
682 this_thread = this_thread->next;
684 if ((that_thread->state == CTDL_THREAD_STOP_REQ || that_thread->state == CTDL_THREAD_STOPPING)
685 && (!citthread_equal(that_thread->tid, citthread_self())))
686 CtdlLogPrintf(CTDL_DEBUG, "Waiting for thread %s (0x%08lx) to exit.\n", that_thread->name, that_thread->tid);
690 * Catch the situation where a worker was asked to stop but couldn't and we are not
693 that_thread->stop_ticker = 0;
696 if (that_thread->stop_ticker + 5 == time(NULL))
698 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);
699 if ((that_thread->flags & CTDLTHREAD_WORKER) == 0)
700 CtdlLogPrintf(CTDL_INFO, "Thread System: A non worker thread would have been canceled this may cause message loss.\n");
701 // that_thread->state = CTDL_THREAD_CANCELLED;
702 that_thread->stop_ticker++;
703 // citthread_cancel(that_thread->tid);
707 /* Do we need to clean up this thread? */
708 if ((that_thread->state != CTDL_THREAD_EXITED) && (that_thread->state != CTDL_THREAD_CANCELLED))
710 if(that_thread->flags & CTDLTHREAD_WORKER)
711 workers++; /* Sanity check on number of worker threads */
715 if (citthread_equal(that_thread->tid, citthread_self()) && that_thread->thread_func)
717 end_critical_section(S_THREAD_LIST);
718 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
723 if (num_threads <= 0)
725 end_critical_section(S_THREAD_LIST);
726 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
731 if(that_thread->flags & CTDLTHREAD_WORKER)
732 num_workers--; /* This is a wroker thread so reduce the count. */
734 /* If we are unlinking the list head then the next becomes the list head */
735 if(that_thread->prev)
736 that_thread->prev->next = that_thread->next;
738 CtdlThreadList = that_thread->next;
739 if(that_thread->next)
740 that_thread->next->prev = that_thread->prev;
742 citthread_cond_signal(&that_thread->ThreadCond);
743 citthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
744 citthread_mutex_lock(&that_thread->ThreadMutex); // Make sure it has done what its doing
745 citthread_mutex_unlock(&that_thread->ThreadMutex);
747 * Join on the thread to do clean up and prevent memory leaks
748 * Also makes sure the thread has cleaned up after itself before we remove it from the list
749 * We can join on the garbage collector thread the join should just return EDEADLCK
751 ret = citthread_join (that_thread->tid, NULL);
753 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection on own thread.\n");
754 else if (ret == EINVAL)
755 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, that thread already joined on.\n");
756 else if (ret == ESRCH)
757 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, no thread to join on.\n");
759 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, citthread_join returned an unknown error(%d).\n", ret);
761 * Now we own that thread entry
763 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (0x%08lx).\n",
764 that_thread->name, that_thread->tid);
765 citthread_mutex_destroy(&that_thread->ThreadMutex);
766 citthread_cond_destroy(&that_thread->ThreadCond);
767 citthread_mutex_destroy(&that_thread->SleepMutex);
768 citthread_cond_destroy(&that_thread->SleepCond);
769 citthread_attr_destroy(&that_thread->attr);
772 sys_workers = num_workers;
773 end_critical_section(S_THREAD_LIST);
775 /* Sanity check number of worker threads */
776 if (workers != sys_workers)
778 CtdlLogPrintf(CTDL_EMERG,
779 "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
790 * Runtime function for a Citadel Thread.
791 * This initialises the threads environment and then calls the user supplied thread function
792 * Note that this is the REAL thread function and wraps the users thread function.
794 static void *ctdl_internal_thread_func (void *arg)
796 CtdlThreadNode *this_thread;
799 /* lock and unlock the thread list.
800 * This causes this thread to wait until all its creation stuff has finished before it
801 * can continue its execution.
803 begin_critical_section(S_THREAD_LIST);
804 this_thread = (CtdlThreadNode *) arg;
805 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
807 // Register the cleanup function to take care of when we exit.
808 citthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
809 // Get our thread data structure
810 CtdlThreadAllocTSD();
812 this_thread->pid = getpid();
813 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
814 /* Only change to running state if we weren't asked to stop during the create cycle
815 * Other wise there is a window to allow this threads creation to continue to full grown and
816 * therby prevent a shutdown of the server.
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 begin_critical_section(S_THREAD_LIST);
964 * We pass this_thread into the thread as its args so that it can find out information
965 * about itself and it has a bit of storage space for itself, not to mention that the REAL
966 * thread function needs to finish off the setup of the structure
968 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
970 end_critical_section(S_THREAD_LIST);
971 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
973 citthread_mutex_unlock(&this_thread->ThreadMutex);
974 citthread_mutex_destroy(&(this_thread->ThreadMutex));
975 citthread_cond_destroy(&(this_thread->ThreadCond));
976 citthread_mutex_destroy(&(this_thread->SleepMutex));
977 citthread_cond_destroy(&(this_thread->SleepCond));
978 citthread_attr_destroy(&this_thread->attr);
983 num_threads++; // Increase the count of threads in the system.
984 if(this_thread->flags & CTDLTHREAD_WORKER)
987 this_thread->next = CtdlThreadList;
988 CtdlThreadList = this_thread;
989 if (this_thread->next)
990 this_thread->next->prev = this_thread;
991 ctdl_thread_internal_calc_loadavg();
993 end_critical_section(S_THREAD_LIST);
999 * Wrapper function to create a thread
1000 * ensures the critical section and other protections are in place.
1001 * char *name = name to give to thread, if NULL, use generic name
1002 * int flags = flags to determine type of thread and standard facilities
1004 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1006 CtdlThreadNode *ret = NULL;
1008 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1015 * Internal function to schedule a thread.
1016 * Must be called from within a S_THREAD_LIST critical section
1018 CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
1020 CtdlThreadNode *this_thread;
1022 if (num_threads >= 32767)
1024 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1028 this_thread = malloc(sizeof(CtdlThreadNode));
1029 if (this_thread == NULL) {
1030 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1033 /* Initialise the thread structure */
1034 if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
1037 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
1042 * If we got here we are going to create the thread so we must initilise the structure
1043 * first because most implimentations of threading can't create it in a stopped state
1044 * and it might want to do things with its structure that aren't initialised otherwise.
1048 this_thread->name = name;
1052 this_thread->name = "Un-named Thread";
1055 this_thread->flags = flags;
1056 this_thread->thread_func = thread_func;
1057 this_thread->user_args = args;
1060 * When to start this thread
1062 this_thread->when = when;
1064 begin_critical_section(S_SCHEDULE_LIST);
1065 this_thread->next = CtdlThreadSchedList;
1066 CtdlThreadSchedList = this_thread;
1067 if (this_thread->next)
1068 this_thread->next->prev = this_thread;
1069 end_critical_section(S_SCHEDULE_LIST);
1076 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
1080 begin_critical_section(S_THREAD_LIST);
1082 * We pass this_thread into the thread as its args so that it can find out information
1083 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1084 * thread function needs to finish off the setup of the structure
1086 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1088 end_critical_section(S_THREAD_LIST);
1089 CtdlLogPrintf(CTDL_DEBUG, "Failed to start scheduled thread \"%s\": %s\n", this_thread->name, strerror(ret));
1090 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1091 citthread_cond_destroy(&(this_thread->ThreadCond));
1092 citthread_mutex_destroy(&(this_thread->SleepMutex));
1093 citthread_cond_destroy(&(this_thread->SleepCond));
1094 citthread_attr_destroy(&this_thread->attr);
1100 num_threads++; // Increase the count of threads in the system.
1101 if(this_thread->flags & CTDLTHREAD_WORKER)
1104 this_thread->next = CtdlThreadList;
1105 CtdlThreadList = this_thread;
1106 if (this_thread->next)
1107 this_thread->next->prev = this_thread;
1109 ctdl_thread_internal_calc_loadavg();
1110 end_critical_section(S_THREAD_LIST);
1118 void ctdl_thread_internal_check_scheduled(void)
1120 CtdlThreadNode *this_thread, *that_thread;
1123 /* Don't start scheduled threads if the system wants single user mode */
1124 if (CtdlWantSingleUser())
1127 if (try_critical_section(S_SCHEDULE_LIST))
1128 return; /* If this list is locked we wait till the next chance */
1132 #ifdef WITH_THREADLOG
1133 CtdlLogPrintf(CTDL_DEBUG, "Checking for scheduled threads to start.\n");
1136 this_thread = CtdlThreadSchedList;
1139 that_thread = this_thread;
1140 this_thread = this_thread->next;
1142 if (now > that_thread->when)
1144 /* Unlink from schedule list */
1145 if (that_thread->prev)
1146 that_thread->prev->next = that_thread->next;
1148 CtdlThreadSchedList = that_thread->next;
1149 if (that_thread->next)
1150 that_thread->next->prev = that_thread->prev;
1152 that_thread->next = that_thread->prev = NULL;
1153 #ifdef WITH_THREADLOG
1154 CtdlLogPrintf(CTDL_DEBUG, "About to start scheduled thread \"%s\".\n", that_thread->name);
1156 if (CT->state > CTDL_THREAD_STOP_REQ)
1157 { /* Only start it if the system is not stopping */
1158 if (ctdl_thread_internal_start_scheduled (that_thread))
1160 #ifdef WITH_THREADLOG
1161 CtdlLogPrintf(CTDL_INFO, "Thread system, Started a scheduled thread \"%s\" (0x%08lx).\n",
1162 that_thread->name, that_thread->tid);
1167 #ifdef WITH_THREADLOG
1170 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" will start in %ld seconds.\n",
1171 that_thread->name, that_thread->when - time(NULL));
1175 end_critical_section(S_SCHEDULE_LIST);
1180 * A warapper function for select so we can show a thread as blocked
1182 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
1186 ctdl_thread_internal_change_state(CT, CTDL_THREAD_BLOCKED);
1187 if (!CtdlThreadCheckStop())
1188 ret = select(n, readfds, writefds, exceptfds, timeout);
1190 * If the select returned <= 0 then it failed due to an error
1191 * or timeout so this thread could stop if asked to do so.
1192 * Anything else means it needs to continue unless the system is shutting down
1197 * The select says this thread needs to do something useful.
1198 * This thread was in an idle state so it may have been asked to stop
1199 * but if the system isn't shutting down this thread is no longer
1200 * idle and select has given it a task to do so it must not stop
1201 * In this condition we need to force it into the running state.
1202 * CtdlThreadGC will clear its ticker for us.
1204 * FIXME: there is still a small hole here. It is possible for the sequence of locking
1205 * to allow the state to get changed to STOP_REQ just after this code if the other thread
1206 * has decided to change the state before this lock, it there fore has to wait till the lock
1207 * completes but it will continue to change the state. We need something a bit better here.
1209 citthread_mutex_lock(&CT->ThreadMutex); /* To prevent race condition of a sleeping thread */
1210 if (GC_thread->state > CTDL_THREAD_STOP_REQ && CT->state <= CTDL_THREAD_STOP_REQ)
1212 CtdlLogPrintf(CTDL_DEBUG, "Thread %s (0x%08lx) refused stop request.\n", CT->name, CT->tid);
1213 CT->state = CTDL_THREAD_RUNNING;
1215 citthread_mutex_unlock(&CT->ThreadMutex);
1218 ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1225 void *new_worker_thread(void *arg);
1226 extern void close_masters (void);
1229 void *simulation_worker (void*arg) {
1230 struct CitContext *this;
1232 this = CreateNewContext();
1235 this->state = CON_IDLE;
1236 dead_session_purge(1);
1237 begin_critical_section(S_SESSION_TABLE);
1239 end_critical_section(S_SESSION_TABLE);
1244 void *simulation_thread (void *arg)
1246 long stats = statcount;
1248 while(stats && !CtdlThreadCheckStop()) {
1249 CtdlThreadCreate("Connection simulation worker", CTDLTHREAD_BIGSTACK, simulation_worker, NULL);
1252 CtdlThreadStopAll();
1256 void go_threading(void)
1259 CtdlThreadNode *last_worker;
1260 struct timeval start, now, result;
1261 double last_duration;
1264 * Initialise the thread system
1266 ctdl_thread_internal_init();
1268 /* Second call to module init functions now that threading is up */
1270 initialise_modules(1);
1271 CtdlThreadCreate("select_on_master", CTDLTHREAD_BIGSTACK, select_on_master, NULL);
1274 CtdlLogPrintf(CTDL_EMERG, "Running connection simulation stats\n");
1275 gettimeofday(&start, NULL);
1276 CtdlThreadCreate("Connection simulation master", CTDLTHREAD_BIGSTACK, simulation_thread, NULL);
1281 * This thread is now used for garbage collection of other threads in the thread list
1283 CtdlLogPrintf(CTDL_INFO, "Startup thread %d becoming garbage collector,\n", citthread_self());
1286 * We do a lot of locking and unlocking of the thread list in here.
1287 * We do this so that we can repeatedly release time for other threads
1288 * that may be waiting on the thread list.
1289 * We are a low priority thread so we can afford to do this
1292 while (CtdlThreadGetCount())
1295 exit_signal = CT->signal;
1298 CtdlThreadStopAll();
1300 check_sched_shutdown();
1301 if (CT->state > CTDL_THREAD_STOP_REQ)
1303 begin_critical_section(S_THREAD_LIST);
1304 ctdl_thread_internal_calc_loadavg();
1305 end_critical_section(S_THREAD_LIST);
1307 ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
1310 /* Reduce the size of the worker thread pool if necessary. */
1311 if ((CtdlThreadGetWorkers() > config.c_min_workers + 1) && (CtdlThreadWorkerAvg < 20) && (CT->state > CTDL_THREAD_STOP_REQ))
1313 /* Ask a worker thread to stop as we no longer need it */
1314 begin_critical_section(S_THREAD_LIST);
1315 last_worker = CtdlThreadList;
1318 citthread_mutex_lock(&last_worker->ThreadMutex);
1319 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1321 citthread_mutex_unlock(&last_worker->ThreadMutex);
1324 citthread_mutex_unlock(&last_worker->ThreadMutex);
1325 last_worker = last_worker->next;
1327 end_critical_section(S_THREAD_LIST);
1330 #ifdef WITH_THREADLOG
1331 CtdlLogPrintf(CTDL_DEBUG, "Thread system, stopping excess worker thread \"%s\" (0x%08lx).\n",
1336 CtdlThreadStop(last_worker);
1341 * If all our workers are working hard, start some more to help out
1344 /* FIXME: come up with a better way to dynamically alter the number of threads
1345 * based on the system load
1348 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkerAvg() > 60)) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1350 /* Only start new threads if we are not going to overload the machine */
1351 /* Temporarily set to 10 should be enough to make sure we don't stranglew the server
1352 * at least until we make this a config option */
1353 if (CtdlThreadGetLoadAvg() < ((double)10.00)) {
1354 for (i=0; i<5 ; i++) {
1355 CtdlThreadCreate("Worker Thread",
1356 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1363 CtdlLogPrintf (CTDL_WARNING, "Server strangled due to machine load average too high.\n");
1369 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1374 #ifdef THREADS_USESIGNALS
1375 if (CtdlThreadGetCount() && CT->state > CTDL_THREAD_STOP_REQ)
1377 if (CtdlThreadGetCount())
1382 * If the above loop exits we must be shutting down since we obviously have no threads
1384 ctdl_thread_internal_cleanup();
1387 gettimeofday(&now, NULL);
1388 timersub(&now, &start, &result);
1389 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1390 CtdlLogPrintf(CTDL_EMERG, "Simulated %ld connections in %f seconds\n", stats_done, last_duration);