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>
33 #else if HAVE_SYS_SYSCALL_H
34 #include <sys/syscall.h>
36 #include <libcitadel.h>
39 #include "ctdl_module.h"
40 #include "modules_init.h"
41 #include "housekeeping.h"
43 #include "citserver.h"
44 #include "sysdep_decls.h"
48 * define this to use the new worker_thread method of handling connections
53 * New thread interface.
54 * To create a thread you must call one of the create thread functions.
55 * You must pass it the address of (a pointer to a CtdlThreadNode initialised to NULL) like this
56 * struct CtdlThreadNode *node = NULL;
58 * If the thread is created *node will point to the thread control structure for the created thread.
59 * If the thread creation fails *node remains NULL
60 * Do not free the memory pointed to by *node, it doesn't belong to you.
61 * This new interface duplicates much of the eCrash stuff. We should go for closer integration since that would
62 * remove the need for the calls to eCrashRegisterThread and friends
65 static int num_threads = 0; /* Current number of threads */
66 static int num_workers = 0; /* Current number of worker threads */
67 long statcount = 0; /* are we doing a stats check? */
68 static long stats_done = 0;
70 CtdlThreadNode *CtdlThreadList = NULL;
71 CtdlThreadNode *CtdlThreadSchedList = NULL;
73 static CtdlThreadNode *GC_thread = NULL;
74 static char *CtdlThreadStates[CTDL_THREAD_LAST_STATE];
75 double CtdlThreadLoadAvg = 0;
76 double CtdlThreadWorkerAvg = 0;
77 citthread_key_t ThreadKey;
79 citthread_mutex_t Critters[MAX_SEMAPHORES]; /* Things needing locking */
83 void InitialiseSemaphores(void)
87 /* Set up a bunch of semaphores to be used for critical sections */
88 for (i=0; i<MAX_SEMAPHORES; ++i) {
89 citthread_mutex_init(&Critters[i], NULL);
97 * Obtain a semaphore lock to begin a critical section.
98 * but only if no one else has one
100 int try_critical_section(int which_one)
102 /* For all types of critical sections except those listed here,
103 * ensure nobody ever tries to do a critical section within a
104 * transaction; this could lead to deadlock.
106 if ( (which_one != S_FLOORCACHE)
107 #ifdef DEBUG_MEMORY_LEAKS
108 && (which_one != S_DEBUGMEMLEAKS)
110 && (which_one != S_RPLIST)
114 return (citthread_mutex_trylock(&Critters[which_one]));
119 * Obtain a semaphore lock to begin a critical section.
121 void begin_critical_section(int which_one)
123 /* CtdlLogPrintf(CTDL_DEBUG, "begin_critical_section(%d)\n", which_one); */
125 /* For all types of critical sections except those listed here,
126 * ensure nobody ever tries to do a critical section within a
127 * transaction; this could lead to deadlock.
129 if ( (which_one != S_FLOORCACHE)
130 #ifdef DEBUG_MEMORY_LEAKS
131 && (which_one != S_DEBUGMEMLEAKS)
133 && (which_one != S_RPLIST)
137 citthread_mutex_lock(&Critters[which_one]);
141 * Release a semaphore lock to end a critical section.
143 void end_critical_section(int which_one)
145 citthread_mutex_unlock(&Critters[which_one]);
150 * A function to destroy the TSD
152 static void ctdl_thread_internal_dest_tsd(void *arg)
162 * A function to initialise the thread TSD
164 void ctdl_thread_internal_init_tsd(void)
168 if ((ret = citthread_key_create(&ThreadKey, ctdl_thread_internal_dest_tsd))) {
169 CtdlLogPrintf(CTDL_EMERG, "citthread_key_create: %s\n", strerror(ret));
175 * Ensure that we have a key for thread-specific data.
177 * This should be called immediately after startup by any thread
180 void CtdlThreadAllocTSD(void)
184 if (citthread_getspecific(ThreadKey) != NULL)
187 tsd = malloc(sizeof(ThreadTSD));
191 memset(tsd->cursors, 0, sizeof tsd->cursors);
194 citthread_setspecific(ThreadKey, tsd);
198 void ctdl_thread_internal_free_tsd(void)
200 ctdl_thread_internal_dest_tsd(citthread_getspecific(ThreadKey));
201 citthread_setspecific(ThreadKey, NULL);
205 void ctdl_thread_internal_cleanup(void)
208 CtdlThreadNode *this_thread, *that_thread;
210 for (i=0; i<CTDL_THREAD_LAST_STATE; i++)
212 free (CtdlThreadStates[i]);
215 /* Clean up the scheduled thread list */
216 this_thread = CtdlThreadSchedList;
219 that_thread = this_thread;
220 this_thread = this_thread->next;
221 citthread_mutex_destroy(&that_thread->ThreadMutex);
222 citthread_cond_destroy(&that_thread->ThreadCond);
223 citthread_mutex_destroy(&that_thread->SleepMutex);
224 citthread_cond_destroy(&that_thread->SleepCond);
225 citthread_attr_destroy(&that_thread->attr);
228 ctdl_thread_internal_free_tsd();
231 void ctdl_thread_internal_init(void)
233 CtdlThreadNode *this_thread;
236 CtdlThreadStates[CTDL_THREAD_INVALID] = strdup ("Invalid Thread");
237 CtdlThreadStates[CTDL_THREAD_VALID] = strdup("Valid Thread");
238 CtdlThreadStates[CTDL_THREAD_CREATE] = strdup("Thread being Created");
239 CtdlThreadStates[CTDL_THREAD_CANCELLED] = strdup("Thread Cancelled");
240 CtdlThreadStates[CTDL_THREAD_EXITED] = strdup("Thread Exited");
241 CtdlThreadStates[CTDL_THREAD_STOPPING] = strdup("Thread Stopping");
242 CtdlThreadStates[CTDL_THREAD_STOP_REQ] = strdup("Thread Stop Requested");
243 CtdlThreadStates[CTDL_THREAD_SLEEPING] = strdup("Thread Sleeping");
244 CtdlThreadStates[CTDL_THREAD_RUNNING] = strdup("Thread Running");
245 CtdlThreadStates[CTDL_THREAD_BLOCKED] = strdup("Thread Blocked");
247 /* Get ourself a thread entry */
248 this_thread = malloc(sizeof(CtdlThreadNode));
249 if (this_thread == NULL) {
250 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
253 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
254 memset (this_thread, 0, sizeof(CtdlThreadNode));
256 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
257 citthread_cond_init (&(this_thread->ThreadCond), NULL);
258 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
259 citthread_cond_init (&(this_thread->SleepCond), NULL);
261 /* We are garbage collector so create us as running */
262 this_thread->state = CTDL_THREAD_RUNNING;
264 if ((ret = citthread_attr_init(&this_thread->attr))) {
265 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
270 this_thread->name = "Garbage Collection Thread";
272 this_thread->tid = citthread_self();
273 GC_thread = this_thread;
276 num_threads++; // Increase the count of threads in the system.
278 this_thread->next = CtdlThreadList;
279 CtdlThreadList = this_thread;
280 if (this_thread->next)
281 this_thread->next->prev = this_thread;
282 /* Set up start times */
283 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
284 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
289 * A function to update a threads load averages
291 void ctdl_thread_internal_update_avgs(CtdlThreadNode *this_thread)
293 struct timeval now, result;
294 double last_duration;
296 gettimeofday(&now, NULL);
297 timersub(&now, &(this_thread->last_state_change), &result);
298 /* I don't think these mutex's are needed here */
299 citthread_mutex_lock(&this_thread->ThreadMutex);
300 // result now has a timeval for the time we spent in the last state since we last updated
301 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
302 if (this_thread->state == CTDL_THREAD_SLEEPING)
303 this_thread->avg_sleeping += last_duration;
304 if (this_thread->state == CTDL_THREAD_RUNNING)
305 this_thread->avg_running += last_duration;
306 if (this_thread->state == CTDL_THREAD_BLOCKED)
307 this_thread->avg_blocked += last_duration;
308 memcpy (&this_thread->last_state_change, &now, sizeof (struct timeval));
309 citthread_mutex_unlock(&this_thread->ThreadMutex);
313 * A function to chenge the state of a thread
315 void ctdl_thread_internal_change_state (CtdlThreadNode *this_thread, enum CtdlThreadState new_state)
318 * Wether we change state or not we need update the load values
320 ctdl_thread_internal_update_avgs(this_thread);
321 /* This mutex not needed here? */
322 citthread_mutex_lock(&this_thread->ThreadMutex); /* To prevent race condition of a sleeping thread */
323 if ((new_state == CTDL_THREAD_STOP_REQ) && (this_thread->state > CTDL_THREAD_STOP_REQ))
324 this_thread->state = new_state;
325 if (((new_state == CTDL_THREAD_SLEEPING) || (new_state == CTDL_THREAD_BLOCKED)) && (this_thread->state == CTDL_THREAD_RUNNING))
326 this_thread->state = new_state;
327 if ((new_state == CTDL_THREAD_RUNNING) && ((this_thread->state == CTDL_THREAD_SLEEPING) || (this_thread->state == CTDL_THREAD_BLOCKED)))
328 this_thread->state = new_state;
329 citthread_mutex_unlock(&this_thread->ThreadMutex);
334 * A function to tell all threads to exit
336 void CtdlThreadStopAll(void)
338 /* First run any registered shutdown hooks. This probably doesn't belong here. */
339 PerformSessionHooks(EVT_SHUTDOWN);
341 //FIXME: The signalling of the condition should not be in the critical_section
342 // We need to build a list of threads we are going to signal and then signal them afterwards
344 CtdlThreadNode *this_thread;
346 begin_critical_section(S_THREAD_LIST);
347 this_thread = CtdlThreadList;
348 // Ask the GC thread to stop first so everything knows we are shutting down.
349 GC_thread->state = CTDL_THREAD_STOP_REQ;
352 if (!citthread_equal(this_thread->tid, GC_thread->tid))
353 citthread_kill(this_thread->tid, SIGHUP);
355 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
356 citthread_cond_signal(&this_thread->ThreadCond);
357 citthread_cond_signal(&this_thread->SleepCond);
358 this_thread->stop_ticker = time(NULL);
359 CtdlLogPrintf(CTDL_DEBUG, "Thread system stopping thread \"%s\" (0x%08lx).\n",
360 this_thread->name, this_thread->tid);
361 this_thread = this_thread->next;
363 end_critical_section(S_THREAD_LIST);
368 * A function to wake up all sleeping threads
370 void CtdlThreadWakeAll(void)
372 CtdlThreadNode *this_thread;
374 CtdlLogPrintf(CTDL_DEBUG, "Thread system waking all threads.\n");
376 begin_critical_section(S_THREAD_LIST);
377 this_thread = CtdlThreadList;
380 if (!this_thread->thread_func)
382 citthread_cond_signal(&this_thread->ThreadCond);
383 citthread_cond_signal(&this_thread->SleepCond);
385 this_thread = this_thread->next;
387 end_critical_section(S_THREAD_LIST);
392 * A function to return the number of threads running in the system
394 int CtdlThreadGetCount(void)
399 int CtdlThreadGetWorkers(void)
404 double CtdlThreadGetWorkerAvg(void)
408 begin_critical_section(S_THREAD_LIST);
409 ret = CtdlThreadWorkerAvg;
410 end_critical_section(S_THREAD_LIST);
414 double CtdlThreadGetLoadAvg(void)
416 double load_avg[3] = {0.0, 0.0, 0.0};
421 /* Borrowed this straight from procps */
422 smp_num_cpus = sysconf(_SC_NPROCESSORS_ONLN);
423 if(smp_num_cpus<1) smp_num_cpus=1; /* SPARC glibc is buggy */
425 #ifdef HAVE_GETLOADAVG
426 ret = getloadavg(load_avg, 3);
430 return load_avg[0] / smp_num_cpus;
432 * This old chunk of code return a value that indicated the load on citserver
433 * This value could easily reach 100 % even when citserver was doing very little and
434 * hence the machine has much more spare capacity.
435 * Because this value was used to determine if the machine was under heavy load conditions
436 * from other processes in the system then citserver could be strangled un-necesarily
437 * What we are actually trying to achieve is to strangle citserver if the machine is heavily loaded.
438 * So we have changed this.
440 begin_critical_section(S_THREAD_LIST);
441 ret = CtdlThreadLoadAvg;
442 end_critical_section(S_THREAD_LIST);
451 * A function to rename a thread
452 * Returns a const char *
454 const char *CtdlThreadName(const char *name)
456 const char *old_name;
460 CtdlLogPrintf(CTDL_WARNING, "Thread system WARNING. Attempt to CtdlThreadRename() a non thread. %s\n", name);
471 * A function to force a thread to exit
473 void CtdlThreadCancel(CtdlThreadNode *thread)
475 CtdlThreadNode *this_thread;
480 this_thread = thread;
483 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() a non thread.\n");
488 if (!this_thread->thread_func)
490 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC. Attempt to CtdlThreadCancel() the garbage collector.\n");
495 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_CANCELLED);
496 citthread_cancel(this_thread->tid);
501 * A function for a thread to check if it has been asked to stop
503 int CtdlThreadCheckStop(void)
509 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, CtdlThreadCheckStop() called by a non thread.\n");
518 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" caught signal %d.\n", CT->name, CT->signal);
519 if (CT->signal == SIGHUP)
520 CT->state = CTDL_THREAD_STOP_REQ;
523 if(state == CTDL_THREAD_STOP_REQ)
525 CT->state = CTDL_THREAD_STOPPING;
528 else if((state < CTDL_THREAD_STOP_REQ) && (state > CTDL_THREAD_CREATE))
537 * A function to ask a thread to exit
538 * The thread must call CtdlThreadCheckStop() periodically to determine if it should exit
540 void CtdlThreadStop(CtdlThreadNode *thread)
542 CtdlThreadNode *this_thread;
547 this_thread = thread;
550 if (!(this_thread->thread_func))
551 return; // Don't stop garbage collector
553 if (!citthread_equal(this_thread->tid, GC_thread->tid))
554 citthread_kill(this_thread->tid, SIGHUP);
556 ctdl_thread_internal_change_state (this_thread, CTDL_THREAD_STOP_REQ);
557 citthread_cond_signal(&this_thread->ThreadCond);
558 citthread_cond_signal(&this_thread->SleepCond);
559 this_thread->stop_ticker = time(NULL);
563 * So we now have a sleep command that works with threads but it is in seconds
565 void CtdlThreadSleep(int secs)
567 struct timespec wake_time;
568 struct timeval time_now;
573 CtdlLogPrintf(CTDL_WARNING, "CtdlThreadSleep() called by something that is not a thread. Should we die?\n");
577 memset (&wake_time, 0, sizeof(struct timespec));
578 gettimeofday(&time_now, NULL);
579 wake_time.tv_sec = time_now.tv_sec + secs;
580 wake_time.tv_nsec = time_now.tv_usec * 10;
582 ctdl_thread_internal_change_state (CT, CTDL_THREAD_SLEEPING);
584 citthread_mutex_lock(&CT->ThreadMutex); /* Prevent something asking us to awaken before we've gone to sleep */
585 citthread_cond_timedwait(&CT->SleepCond, &CT->ThreadMutex, &wake_time);
586 citthread_mutex_unlock(&CT->ThreadMutex);
588 ctdl_thread_internal_change_state (CT, CTDL_THREAD_RUNNING);
593 * Routine to clean up our thread function on exit
595 static void ctdl_internal_thread_cleanup(void *arg)
598 * In here we were called by the current thread because it is exiting
599 * NB. WE ARE THE CURRENT THREAD
603 const char *name = CT->name;
604 const pid_t tid = CT->tid;
606 CtdlLogPrintf(CTDL_NOTICE, "Thread \"%s\" (0x%08lx) exited.\n", name, tid);
610 CtdlLogPrintf(CTDL_NOTICE, "some ((unknown ? ? ?) Thread exited.\n");
613 #ifdef HAVE_BACKTRACE
614 /// eCrash_UnregisterThread();
617 citthread_mutex_lock(&CT->ThreadMutex);
618 CT->state = CTDL_THREAD_EXITED; // needs to be last thing else house keeping will unlink us too early
619 citthread_mutex_unlock(&CT->ThreadMutex);
623 * A quick function to show the load averages
625 void ctdl_thread_internal_calc_loadavg(void)
627 CtdlThreadNode *that_thread;
628 double load_avg, worker_avg;
631 that_thread = CtdlThreadList;
636 /* Update load averages */
637 ctdl_thread_internal_update_avgs(that_thread);
638 citthread_mutex_lock(&that_thread->ThreadMutex);
639 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;
640 that_thread->avg_sleeping /= 2;
641 that_thread->avg_running /= 2;
642 that_thread->avg_blocked /= 2;
643 load_avg += that_thread->load_avg;
644 if (that_thread->flags & CTDLTHREAD_WORKER)
646 worker_avg += that_thread->load_avg;
649 #ifdef WITH_THREADLOG
650 CtdlLogPrintf(CTDL_DEBUG, "CtdlThread, \"%s\" (%lu) \"%s\" %.2f %.2f %.2f %.2f\n",
653 CtdlThreadStates[that_thread->state],
654 that_thread->avg_sleeping,
655 that_thread->avg_running,
656 that_thread->avg_blocked,
657 that_thread->load_avg);
659 citthread_mutex_unlock(&that_thread->ThreadMutex);
660 that_thread = that_thread->next;
662 CtdlThreadLoadAvg = load_avg/num_threads;
663 CtdlThreadWorkerAvg = worker_avg/workers;
664 #ifdef WITH_THREADLOG
665 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);
671 * Garbage collection routine.
672 * Gets called by main() in a loop to clean up the thread list periodically.
674 void CtdlThreadGC (void)
676 CtdlThreadNode *this_thread, *that_thread;
677 int workers = 0, sys_workers;
680 begin_critical_section(S_THREAD_LIST);
682 /* Handle exiting of garbage collector thread */
684 CtdlThreadList->state = CTDL_THREAD_EXITED;
686 #ifdef WITH_THREADLOG
687 CtdlLogPrintf(CTDL_DEBUG, "Thread system running garbage collection.\n");
690 * Woke up to do garbage collection
692 this_thread = CtdlThreadList;
695 that_thread = this_thread;
696 this_thread = this_thread->next;
698 if ((that_thread->state == CTDL_THREAD_STOP_REQ || that_thread->state == CTDL_THREAD_STOPPING)
699 && (!citthread_equal(that_thread->tid, citthread_self())))
700 CtdlLogPrintf(CTDL_DEBUG, "Waiting for thread %s (0x%08lx) to exit.\n", that_thread->name, that_thread->tid);
704 * Catch the situation where a worker was asked to stop but couldn't and we are not
707 that_thread->stop_ticker = 0;
710 if (that_thread->stop_ticker + 5 == time(NULL))
712 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);
713 if ((that_thread->flags & CTDLTHREAD_WORKER) == 0)
714 CtdlLogPrintf(CTDL_INFO, "Thread System: A non worker thread would have been canceled this may cause message loss.\n");
715 // that_thread->state = CTDL_THREAD_CANCELLED;
716 that_thread->stop_ticker++;
717 // citthread_cancel(that_thread->tid);
721 /* Do we need to clean up this thread? */
722 if ((that_thread->state != CTDL_THREAD_EXITED) && (that_thread->state != CTDL_THREAD_CANCELLED))
724 if(that_thread->flags & CTDLTHREAD_WORKER)
725 workers++; /* Sanity check on number of worker threads */
729 if (citthread_equal(that_thread->tid, citthread_self()) && that_thread->thread_func)
731 end_critical_section(S_THREAD_LIST);
732 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, a thread is trying to clean up after itself.\n");
737 if (num_threads <= 0)
739 end_critical_section(S_THREAD_LIST);
740 CtdlLogPrintf(CTDL_EMERG, "Thread system PANIC, num_threads <= 0 and trying to do Garbage Collection.\n");
745 if(that_thread->flags & CTDLTHREAD_WORKER)
746 num_workers--; /* This is a wroker thread so reduce the count. */
748 /* If we are unlinking the list head then the next becomes the list head */
749 if(that_thread->prev)
750 that_thread->prev->next = that_thread->next;
752 CtdlThreadList = that_thread->next;
753 if(that_thread->next)
754 that_thread->next->prev = that_thread->prev;
756 citthread_cond_signal(&that_thread->ThreadCond);
757 citthread_cond_signal(&that_thread->SleepCond); // Make sure this thread is awake
758 citthread_mutex_lock(&that_thread->ThreadMutex); // Make sure it has done what its doing
759 citthread_mutex_unlock(&that_thread->ThreadMutex);
761 * Join on the thread to do clean up and prevent memory leaks
762 * Also makes sure the thread has cleaned up after itself before we remove it from the list
763 * We can join on the garbage collector thread the join should just return EDEADLCK
765 ret = citthread_join (that_thread->tid, NULL);
767 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection on own thread.\n");
768 else if (ret == EINVAL)
769 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, that thread already joined on.\n");
770 else if (ret == ESRCH)
771 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, no thread to join on.\n");
773 CtdlLogPrintf(CTDL_DEBUG, "Garbage collection, citthread_join returned an unknown error(%d).\n", ret);
775 * Now we own that thread entry
777 CtdlLogPrintf(CTDL_INFO, "Garbage Collection for thread \"%s\" (0x%08lx).\n",
778 that_thread->name, that_thread->tid);
779 citthread_mutex_destroy(&that_thread->ThreadMutex);
780 citthread_cond_destroy(&that_thread->ThreadCond);
781 citthread_mutex_destroy(&that_thread->SleepMutex);
782 citthread_cond_destroy(&that_thread->SleepCond);
783 citthread_attr_destroy(&that_thread->attr);
786 sys_workers = num_workers;
787 end_critical_section(S_THREAD_LIST);
789 /* Sanity check number of worker threads */
790 if (workers != sys_workers)
792 CtdlLogPrintf(CTDL_EMERG,
793 "Thread system PANIC, discrepancy in number of worker threads. Counted %d, should be %d.\n",
804 * Runtime function for a Citadel Thread.
805 * This initialises the threads environment and then calls the user supplied thread function
806 * Note that this is the REAL thread function and wraps the users thread function.
808 static void *ctdl_internal_thread_func (void *arg)
810 CtdlThreadNode *this_thread;
813 /* lock and unlock the thread list.
814 * This causes this thread to wait until all its creation stuff has finished before it
815 * can continue its execution.
817 begin_critical_section(S_THREAD_LIST);
818 this_thread = (CtdlThreadNode *) arg;
819 gettimeofday(&this_thread->start_time, NULL); /* Time this thread started */
821 // Register the cleanup function to take care of when we exit.
822 citthread_cleanup_push(ctdl_internal_thread_cleanup, NULL);
823 // Get our thread data structure
824 CtdlThreadAllocTSD();
826 this_thread->pid = getpid();
827 memcpy(&this_thread->last_state_change, &this_thread->start_time, sizeof (struct timeval)); /* Changed state so mark it. */
828 /* Only change to running state if we weren't asked to stop during the create cycle
829 * Other wise there is a window to allow this threads creation to continue to full grown and
830 * therby prevent a shutdown of the server.
832 if (!CtdlThreadCheckStop())
834 citthread_mutex_lock(&this_thread->ThreadMutex);
835 this_thread->state = CTDL_THREAD_RUNNING;
836 citthread_mutex_unlock(&this_thread->ThreadMutex);
838 end_critical_section(S_THREAD_LIST);
840 // Register for tracing
841 #ifdef HAVE_BACKTRACE
842 /// eCrash_RegisterThread(this_thread->name, 0);
845 // Tell the world we are here
846 #ifdef HAVE_SYSCALL_H
847 this_thread->reltid = syscall(SYS_gettid);
849 CtdlLogPrintf(CTDL_NOTICE, "Created a new thread \"%s\" (0x%08lx).\n",
850 this_thread->name, this_thread->tid);
853 * run the thread to do the work but only if we haven't been asked to stop
855 if (!CtdlThreadCheckStop())
856 ret = (this_thread->thread_func)(this_thread->user_args);
859 * Our thread is exiting either because it wanted to end or because the server is stopping
860 * We need to clean up
862 citthread_cleanup_pop(1); // Execute our cleanup routine and remove it
871 * Function to initialise an empty thread structure
873 CtdlThreadNode *ctdl_internal_init_thread_struct(CtdlThreadNode *this_thread, long flags)
877 // Ensuring this is zero'd means we make sure the thread doesn't start doing its thing until we are ready.
878 memset (this_thread, 0, sizeof(CtdlThreadNode));
880 /* Create the mutex's early so we can use them */
881 citthread_mutex_init (&(this_thread->ThreadMutex), NULL);
882 citthread_cond_init (&(this_thread->ThreadCond), NULL);
883 citthread_mutex_init (&(this_thread->SleepMutex), NULL);
884 citthread_cond_init (&(this_thread->SleepCond), NULL);
886 this_thread->state = CTDL_THREAD_CREATE;
888 if ((ret = citthread_attr_init(&this_thread->attr))) {
889 citthread_mutex_unlock(&this_thread->ThreadMutex);
890 citthread_mutex_destroy(&(this_thread->ThreadMutex));
891 citthread_cond_destroy(&(this_thread->ThreadCond));
892 citthread_mutex_destroy(&(this_thread->SleepMutex));
893 citthread_cond_destroy(&(this_thread->SleepCond));
894 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_init: %s\n", strerror(ret));
899 /* Our per-thread stacks need to be bigger than the default size,
900 * otherwise the MIME parser crashes on FreeBSD, and the IMAP service
901 * crashes on 64-bit Linux.
903 if (flags & CTDLTHREAD_BIGSTACK)
905 #ifdef WITH_THREADLOG
906 CtdlLogPrintf(CTDL_INFO, "Thread system. Creating BIG STACK thread.\n");
908 if ((ret = citthread_attr_setstacksize(&this_thread->attr, THREADSTACKSIZE))) {
909 citthread_mutex_unlock(&this_thread->ThreadMutex);
910 citthread_mutex_destroy(&(this_thread->ThreadMutex));
911 citthread_cond_destroy(&(this_thread->ThreadCond));
912 citthread_mutex_destroy(&(this_thread->SleepMutex));
913 citthread_cond_destroy(&(this_thread->SleepCond));
914 citthread_attr_destroy(&this_thread->attr);
915 CtdlLogPrintf(CTDL_EMERG, "Thread system, citthread_attr_setstacksize: %s\n",
922 /* Set this new thread with an avg_blocked of 2. We do this so that its creation affects the
923 * load average for the system. If we don't do this then we create a mass of threads at the same time
924 * because the creation didn't affect the load average.
926 this_thread->avg_blocked = 2;
928 return (this_thread);
935 * Internal function to create a thread.
937 CtdlThreadNode *ctdl_internal_create_thread(char *name, long flags, void *(*thread_func) (void *arg), void *args)
940 CtdlThreadNode *this_thread;
942 if (num_threads >= 32767)
944 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
948 this_thread = malloc(sizeof(CtdlThreadNode));
949 if (this_thread == NULL) {
950 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
954 /* Initialise the thread structure */
955 if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
958 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
962 * If we got here we are going to create the thread so we must initilise the structure
963 * first because most implimentations of threading can't create it in a stopped state
964 * and it might want to do things with its structure that aren't initialised otherwise.
968 this_thread->name = name;
972 this_thread->name = "Un-named Thread";
975 this_thread->flags = flags;
976 this_thread->thread_func = thread_func;
977 this_thread->user_args = args;
979 begin_critical_section(S_THREAD_LIST);
981 * We pass this_thread into the thread as its args so that it can find out information
982 * about itself and it has a bit of storage space for itself, not to mention that the REAL
983 * thread function needs to finish off the setup of the structure
985 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
987 end_critical_section(S_THREAD_LIST);
988 CtdlLogPrintf(CTDL_ALERT, "Thread system, Can't create thread: %s\n",
990 citthread_mutex_unlock(&this_thread->ThreadMutex);
991 citthread_mutex_destroy(&(this_thread->ThreadMutex));
992 citthread_cond_destroy(&(this_thread->ThreadCond));
993 citthread_mutex_destroy(&(this_thread->SleepMutex));
994 citthread_cond_destroy(&(this_thread->SleepCond));
995 citthread_attr_destroy(&this_thread->attr);
999 num_threads++; // Increase the count of threads in the system.
1000 if(this_thread->flags & CTDLTHREAD_WORKER)
1003 this_thread->next = CtdlThreadList;
1004 CtdlThreadList = this_thread;
1005 if (this_thread->next)
1006 this_thread->next->prev = this_thread;
1007 ctdl_thread_internal_calc_loadavg();
1009 end_critical_section(S_THREAD_LIST);
1015 * Wrapper function to create a thread
1016 * ensures the critical section and other protections are in place.
1017 * char *name = name to give to thread, if NULL, use generic name
1018 * int flags = flags to determine type of thread and standard facilities
1020 CtdlThreadNode *CtdlThreadCreate(char *name, long flags, void *(*thread_func) (void *arg), void *args)
1022 CtdlThreadNode *ret = NULL;
1024 ret = ctdl_internal_create_thread(name, flags, thread_func, args);
1031 * Internal function to schedule a thread.
1032 * Must be called from within a S_THREAD_LIST critical section
1034 CtdlThreadNode *CtdlThreadSchedule(char *name, long flags, void *(*thread_func) (void *arg), void *args, time_t when)
1036 CtdlThreadNode *this_thread;
1038 if (num_threads >= 32767)
1040 CtdlLogPrintf(CTDL_EMERG, "Thread system. Thread list full.\n");
1044 this_thread = malloc(sizeof(CtdlThreadNode));
1045 if (this_thread == NULL) {
1046 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't allocate CtdlThreadNode, exiting\n");
1049 /* Initialise the thread structure */
1050 if (ctdl_internal_init_thread_struct(this_thread, flags) == NULL)
1053 CtdlLogPrintf(CTDL_EMERG, "Thread system, can't initialise CtdlThreadNode, exiting\n");
1058 * If we got here we are going to create the thread so we must initilise the structure
1059 * first because most implimentations of threading can't create it in a stopped state
1060 * and it might want to do things with its structure that aren't initialised otherwise.
1064 this_thread->name = name;
1068 this_thread->name = "Un-named Thread";
1071 this_thread->flags = flags;
1072 this_thread->thread_func = thread_func;
1073 this_thread->user_args = args;
1076 * When to start this thread
1078 this_thread->when = when;
1080 begin_critical_section(S_SCHEDULE_LIST);
1081 this_thread->next = CtdlThreadSchedList;
1082 CtdlThreadSchedList = this_thread;
1083 if (this_thread->next)
1084 this_thread->next->prev = this_thread;
1085 end_critical_section(S_SCHEDULE_LIST);
1092 CtdlThreadNode *ctdl_thread_internal_start_scheduled (CtdlThreadNode *this_thread)
1096 begin_critical_section(S_THREAD_LIST);
1098 * We pass this_thread into the thread as its args so that it can find out information
1099 * about itself and it has a bit of storage space for itself, not to mention that the REAL
1100 * thread function needs to finish off the setup of the structure
1102 if ((ret = citthread_create(&this_thread->tid, &this_thread->attr, ctdl_internal_thread_func, this_thread) != 0))
1104 end_critical_section(S_THREAD_LIST);
1105 CtdlLogPrintf(CTDL_DEBUG, "Failed to start scheduled thread \"%s\": %s\n", this_thread->name, strerror(ret));
1106 citthread_mutex_destroy(&(this_thread->ThreadMutex));
1107 citthread_cond_destroy(&(this_thread->ThreadCond));
1108 citthread_mutex_destroy(&(this_thread->SleepMutex));
1109 citthread_cond_destroy(&(this_thread->SleepCond));
1110 citthread_attr_destroy(&this_thread->attr);
1116 num_threads++; // Increase the count of threads in the system.
1117 if(this_thread->flags & CTDLTHREAD_WORKER)
1120 this_thread->next = CtdlThreadList;
1121 CtdlThreadList = this_thread;
1122 if (this_thread->next)
1123 this_thread->next->prev = this_thread;
1125 ctdl_thread_internal_calc_loadavg();
1126 end_critical_section(S_THREAD_LIST);
1134 void ctdl_thread_internal_check_scheduled(void)
1136 CtdlThreadNode *this_thread, *that_thread;
1139 /* Don't start scheduled threads if the system wants single user mode */
1140 if (CtdlWantSingleUser())
1143 if (try_critical_section(S_SCHEDULE_LIST))
1144 return; /* If this list is locked we wait till the next chance */
1148 #ifdef WITH_THREADLOG
1149 CtdlLogPrintf(CTDL_DEBUG, "Checking for scheduled threads to start.\n");
1152 this_thread = CtdlThreadSchedList;
1155 that_thread = this_thread;
1156 this_thread = this_thread->next;
1158 if (now > that_thread->when)
1160 /* Unlink from schedule list */
1161 if (that_thread->prev)
1162 that_thread->prev->next = that_thread->next;
1164 CtdlThreadSchedList = that_thread->next;
1165 if (that_thread->next)
1166 that_thread->next->prev = that_thread->prev;
1168 that_thread->next = that_thread->prev = NULL;
1169 #ifdef WITH_THREADLOG
1170 CtdlLogPrintf(CTDL_DEBUG, "About to start scheduled thread \"%s\".\n", that_thread->name);
1172 if (CT->state > CTDL_THREAD_STOP_REQ)
1173 { /* Only start it if the system is not stopping */
1174 if (ctdl_thread_internal_start_scheduled (that_thread))
1176 #ifdef WITH_THREADLOG
1177 CtdlLogPrintf(CTDL_INFO, "Thread system, Started a scheduled thread \"%s\" (0x%08lx).\n",
1178 that_thread->name, that_thread->tid);
1183 #ifdef WITH_THREADLOG
1186 CtdlLogPrintf(CTDL_DEBUG, "Thread \"%s\" will start in %ld seconds.\n",
1187 that_thread->name, that_thread->when - time(NULL));
1191 end_critical_section(S_SCHEDULE_LIST);
1196 * A warapper function for select so we can show a thread as blocked
1198 int CtdlThreadSelect(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
1202 ctdl_thread_internal_change_state(CT, CTDL_THREAD_BLOCKED);
1203 if (!CtdlThreadCheckStop())
1204 ret = select(n, readfds, writefds, exceptfds, timeout);
1206 * If the select returned <= 0 then it failed due to an error
1207 * or timeout so this thread could stop if asked to do so.
1208 * Anything else means it needs to continue unless the system is shutting down
1213 * The select says this thread needs to do something useful.
1214 * This thread was in an idle state so it may have been asked to stop
1215 * but if the system isn't shutting down this thread is no longer
1216 * idle and select has given it a task to do so it must not stop
1217 * In this condition we need to force it into the running state.
1218 * CtdlThreadGC will clear its ticker for us.
1220 * FIXME: there is still a small hole here. It is possible for the sequence of locking
1221 * to allow the state to get changed to STOP_REQ just after this code if the other thread
1222 * has decided to change the state before this lock, it there fore has to wait till the lock
1223 * completes but it will continue to change the state. We need something a bit better here.
1225 citthread_mutex_lock(&CT->ThreadMutex); /* To prevent race condition of a sleeping thread */
1226 if (GC_thread->state > CTDL_THREAD_STOP_REQ && CT->state <= CTDL_THREAD_STOP_REQ)
1228 CtdlLogPrintf(CTDL_DEBUG, "Thread %s (0x%08lx) refused stop request.\n", CT->name, CT->tid);
1229 CT->state = CTDL_THREAD_RUNNING;
1231 citthread_mutex_unlock(&CT->ThreadMutex);
1234 ctdl_thread_internal_change_state(CT, CTDL_THREAD_RUNNING);
1241 void *new_worker_thread(void *arg);
1242 extern void close_masters (void);
1245 void *simulation_worker (void*arg) {
1246 struct CitContext *this;
1248 this = CreateNewContext();
1251 this->state = CON_IDLE;
1252 dead_session_purge(1);
1253 begin_critical_section(S_SESSION_TABLE);
1255 end_critical_section(S_SESSION_TABLE);
1260 void *simulation_thread (void *arg)
1262 long stats = statcount;
1264 while(stats && !CtdlThreadCheckStop()) {
1265 CtdlThreadCreate("Connection simulation worker", CTDLTHREAD_BIGSTACK, simulation_worker, NULL);
1268 CtdlThreadStopAll();
1272 void go_threading(void)
1275 CtdlThreadNode *last_worker;
1276 struct timeval start, now, result;
1277 double last_duration;
1280 * Initialise the thread system
1282 ctdl_thread_internal_init();
1284 /* Second call to module init functions now that threading is up */
1286 initialise_modules(1);
1287 CtdlThreadCreate("select_on_master", CTDLTHREAD_BIGSTACK, select_on_master, NULL);
1290 CtdlLogPrintf(CTDL_EMERG, "Running connection simulation stats\n");
1291 gettimeofday(&start, NULL);
1292 CtdlThreadCreate("Connection simulation master", CTDLTHREAD_BIGSTACK, simulation_thread, NULL);
1297 * This thread is now used for garbage collection of other threads in the thread list
1299 CtdlLogPrintf(CTDL_INFO, "Startup thread %d becoming garbage collector,\n", citthread_self());
1302 * We do a lot of locking and unlocking of the thread list in here.
1303 * We do this so that we can repeatedly release time for other threads
1304 * that may be waiting on the thread list.
1305 * We are a low priority thread so we can afford to do this
1308 while (CtdlThreadGetCount())
1311 exit_signal = CT->signal;
1314 CtdlThreadStopAll();
1316 check_sched_shutdown();
1317 if (CT->state > CTDL_THREAD_STOP_REQ)
1319 begin_critical_section(S_THREAD_LIST);
1320 ctdl_thread_internal_calc_loadavg();
1321 end_critical_section(S_THREAD_LIST);
1323 ctdl_thread_internal_check_scheduled(); /* start scheduled threads */
1326 /* Reduce the size of the worker thread pool if necessary. */
1327 if ((CtdlThreadGetWorkers() > config.c_min_workers + 1) && (CtdlThreadWorkerAvg < 20) && (CT->state > CTDL_THREAD_STOP_REQ))
1329 /* Ask a worker thread to stop as we no longer need it */
1330 begin_critical_section(S_THREAD_LIST);
1331 last_worker = CtdlThreadList;
1334 citthread_mutex_lock(&last_worker->ThreadMutex);
1335 if (last_worker->flags & CTDLTHREAD_WORKER && (last_worker->state > CTDL_THREAD_STOPPING) && (last_worker->Context == NULL))
1337 citthread_mutex_unlock(&last_worker->ThreadMutex);
1340 citthread_mutex_unlock(&last_worker->ThreadMutex);
1341 last_worker = last_worker->next;
1343 end_critical_section(S_THREAD_LIST);
1346 #ifdef WITH_THREADLOG
1347 CtdlLogPrintf(CTDL_DEBUG, "Thread system, stopping excess worker thread \"%s\" (0x%08lx).\n",
1352 CtdlThreadStop(last_worker);
1357 * If all our workers are working hard, start some more to help out
1360 /* FIXME: come up with a better way to dynamically alter the number of threads
1361 * based on the system load
1364 if ((((CtdlThreadGetWorkers() < config.c_max_workers) && (CtdlThreadGetWorkerAvg() > 60)) || CtdlThreadGetWorkers() < config.c_min_workers) && (CT->state > CTDL_THREAD_STOP_REQ))
1366 /* Only start new threads if we are not going to overload the machine */
1367 /* Temporarily set to 10 should be enough to make sure we don't stranglew the server
1368 * at least until we make this a config option */
1369 if (CtdlThreadGetLoadAvg() < ((double)10.00)) {
1370 for (i=0; i<5 ; i++) {
1371 CtdlThreadCreate("Worker Thread",
1372 CTDLTHREAD_BIGSTACK + CTDLTHREAD_WORKER,
1379 CtdlLogPrintf (CTDL_WARNING, "Server strangled due to machine load average too high.\n");
1385 if (CtdlThreadGetCount() <= 1) // Shutting down clean up the garbage collector
1390 #ifdef THREADS_USESIGNALS
1391 if (CtdlThreadGetCount() && CT->state > CTDL_THREAD_STOP_REQ)
1393 if (CtdlThreadGetCount())
1398 * If the above loop exits we must be shutting down since we obviously have no threads
1400 ctdl_thread_internal_cleanup();
1403 gettimeofday(&now, NULL);
1404 timersub(&now, &start, &result);
1405 last_duration = (double)result.tv_sec + ((double)result.tv_usec / (double) 1000000);
1406 CtdlLogPrintf(CTDL_EMERG, "Simulated %ld connections in %f seconds\n", stats_done, last_duration);